WebGLRenderer.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609
  1. import {
  2. REVISION,
  3. RGBAFormat,
  4. HalfFloatType,
  5. FloatType,
  6. UnsignedByteType,
  7. TriangleFanDrawMode,
  8. TriangleStripDrawMode,
  9. TrianglesDrawMode,
  10. LinearToneMapping,
  11. BackSide
  12. } from '../constants.js';
  13. import { _Math } from '../math/Math.js';
  14. import { DataTexture } from '../textures/DataTexture.js';
  15. import { Frustum } from '../math/Frustum.js';
  16. import { Matrix4 } from '../math/Matrix4.js';
  17. import { ShaderLib } from './shaders/ShaderLib.js';
  18. import { UniformsLib } from './shaders/UniformsLib.js';
  19. import { UniformsUtils } from './shaders/UniformsUtils.js';
  20. import { Vector3 } from '../math/Vector3.js';
  21. import { Vector4 } from '../math/Vector4.js';
  22. import { WebGLAnimation } from './webgl/WebGLAnimation.js';
  23. import { WebGLAttributes } from './webgl/WebGLAttributes.js';
  24. import { WebGLBackground } from './webgl/WebGLBackground.js';
  25. import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer.js';
  26. import { WebGLCapabilities } from './webgl/WebGLCapabilities.js';
  27. import { WebGLClipping } from './webgl/WebGLClipping.js';
  28. import { WebGLExtensions } from './webgl/WebGLExtensions.js';
  29. import { WebGLGeometries } from './webgl/WebGLGeometries.js';
  30. import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer.js';
  31. import { WebGLInfo } from './webgl/WebGLInfo.js';
  32. import { WebGLMorphtargets } from './webgl/WebGLMorphtargets.js';
  33. import { WebGLObjects } from './webgl/WebGLObjects.js';
  34. import { WebGLPrograms } from './webgl/WebGLPrograms.js';
  35. import { WebGLProperties } from './webgl/WebGLProperties.js';
  36. import { WebGLRenderLists } from './webgl/WebGLRenderLists.js';
  37. import { WebGLRenderStates } from './webgl/WebGLRenderStates.js';
  38. import { WebGLShadowMap } from './webgl/WebGLShadowMap.js';
  39. import { WebGLState } from './webgl/WebGLState.js';
  40. import { WebGLTextures } from './webgl/WebGLTextures.js';
  41. import { WebGLUniforms } from './webgl/WebGLUniforms.js';
  42. import { WebGLUtils } from './webgl/WebGLUtils.js';
  43. import { WebVRManager } from './webvr/WebVRManager.js';
  44. import { WebXRManager } from './webvr/WebXRManager.js';
  45. /**
  46. * @author supereggbert / http://www.paulbrunt.co.uk/
  47. * @author mrdoob / http://mrdoob.com/
  48. * @author alteredq / http://alteredqualia.com/
  49. * @author szimek / https://github.com/szimek/
  50. * @author tschw
  51. */
  52. function WebGLRenderer( parameters ) {
  53. console.log( 'THREE.WebGLRenderer', REVISION );
  54. parameters = parameters || {};
  55. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  56. _context = parameters.context !== undefined ? parameters.context : null,
  57. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  58. _depth = parameters.depth !== undefined ? parameters.depth : true,
  59. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  60. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  61. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  62. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  63. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default';
  64. var currentRenderList = null;
  65. var currentRenderState = null;
  66. // public properties
  67. this.domElement = _canvas;
  68. this.context = null;
  69. // clearing
  70. this.autoClear = true;
  71. this.autoClearColor = true;
  72. this.autoClearDepth = true;
  73. this.autoClearStencil = true;
  74. // scene graph
  75. this.sortObjects = true;
  76. // user-defined clipping
  77. this.clippingPlanes = [];
  78. this.localClippingEnabled = false;
  79. // physically based shading
  80. this.gammaFactor = 2.0; // for backwards compatibility
  81. this.gammaInput = false;
  82. this.gammaOutput = false;
  83. // physical lights
  84. this.physicallyCorrectLights = false;
  85. // tone mapping
  86. this.toneMapping = LinearToneMapping;
  87. this.toneMappingExposure = 1.0;
  88. this.toneMappingWhitePoint = 1.0;
  89. // morphs
  90. this.maxMorphTargets = 8;
  91. this.maxMorphNormals = 4;
  92. // internal properties
  93. var _this = this,
  94. _isContextLost = false,
  95. // internal state cache
  96. _framebuffer = null,
  97. _currentRenderTarget = null,
  98. _currentFramebuffer = null,
  99. _currentMaterialId = - 1,
  100. // geometry and program caching
  101. _currentGeometryProgram = {
  102. geometry: null,
  103. program: null,
  104. wireframe: false
  105. },
  106. _currentCamera = null,
  107. _currentArrayCamera = null,
  108. _currentViewport = new Vector4(),
  109. _currentScissor = new Vector4(),
  110. _currentScissorTest = null,
  111. //
  112. _usedTextureUnits = 0,
  113. //
  114. _width = _canvas.width,
  115. _height = _canvas.height,
  116. _pixelRatio = 1,
  117. _viewport = new Vector4( 0, 0, _width, _height ),
  118. _scissor = new Vector4( 0, 0, _width, _height ),
  119. _scissorTest = false,
  120. // frustum
  121. _frustum = new Frustum(),
  122. // clipping
  123. _clipping = new WebGLClipping(),
  124. _clippingEnabled = false,
  125. _localClippingEnabled = false,
  126. // camera matrices cache
  127. _projScreenMatrix = new Matrix4(),
  128. _vector3 = new Vector3();
  129. function getTargetPixelRatio() {
  130. return _currentRenderTarget === null ? _pixelRatio : 1;
  131. }
  132. // initialize
  133. var _gl;
  134. try {
  135. var contextAttributes = {
  136. alpha: _alpha,
  137. depth: _depth,
  138. stencil: _stencil,
  139. antialias: _antialias,
  140. premultipliedAlpha: _premultipliedAlpha,
  141. preserveDrawingBuffer: _preserveDrawingBuffer,
  142. powerPreference: _powerPreference
  143. };
  144. // event listeners must be registered before WebGL context is created, see #12753
  145. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  146. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  147. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  148. if ( _gl === null ) {
  149. if ( _canvas.getContext( 'webgl' ) !== null ) {
  150. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  151. } else {
  152. throw new Error( 'Error creating WebGL context.' );
  153. }
  154. }
  155. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  156. if ( _gl.getShaderPrecisionFormat === undefined ) {
  157. _gl.getShaderPrecisionFormat = function () {
  158. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  159. };
  160. }
  161. } catch ( error ) {
  162. console.error( 'THREE.WebGLRenderer: ' + error.message );
  163. }
  164. var extensions, capabilities, state, info;
  165. var properties, textures, attributes, geometries, objects;
  166. var programCache, renderLists, renderStates;
  167. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  168. var utils;
  169. function initGLContext() {
  170. extensions = new WebGLExtensions( _gl );
  171. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  172. if ( ! capabilities.isWebGL2 ) {
  173. extensions.get( 'WEBGL_depth_texture' );
  174. extensions.get( 'OES_texture_float' );
  175. extensions.get( 'OES_texture_half_float' );
  176. extensions.get( 'OES_texture_half_float_linear' );
  177. extensions.get( 'OES_standard_derivatives' );
  178. extensions.get( 'OES_element_index_uint' );
  179. extensions.get( 'ANGLE_instanced_arrays' );
  180. }
  181. extensions.get( 'OES_texture_float_linear' );
  182. utils = new WebGLUtils( _gl, extensions, capabilities );
  183. state = new WebGLState( _gl, extensions, utils, capabilities );
  184. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  185. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  186. info = new WebGLInfo( _gl );
  187. properties = new WebGLProperties();
  188. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  189. attributes = new WebGLAttributes( _gl );
  190. geometries = new WebGLGeometries( _gl, attributes, info );
  191. objects = new WebGLObjects( geometries, info );
  192. morphtargets = new WebGLMorphtargets( _gl );
  193. programCache = new WebGLPrograms( _this, extensions, capabilities );
  194. renderLists = new WebGLRenderLists();
  195. renderStates = new WebGLRenderStates();
  196. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  197. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  198. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  199. info.programs = programCache.programs;
  200. _this.context = _gl;
  201. _this.capabilities = capabilities;
  202. _this.extensions = extensions;
  203. _this.properties = properties;
  204. _this.renderLists = renderLists;
  205. _this.state = state;
  206. _this.info = info;
  207. }
  208. initGLContext();
  209. // vr
  210. var vr = ( 'xr' in navigator ) ? new WebXRManager( _this ) : new WebVRManager( _this );
  211. this.vr = vr;
  212. // shadow map
  213. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  214. this.shadowMap = shadowMap;
  215. // API
  216. this.getContext = function () {
  217. return _gl;
  218. };
  219. this.getContextAttributes = function () {
  220. return _gl.getContextAttributes();
  221. };
  222. this.forceContextLoss = function () {
  223. var extension = extensions.get( 'WEBGL_lose_context' );
  224. if ( extension ) extension.loseContext();
  225. };
  226. this.forceContextRestore = function () {
  227. var extension = extensions.get( 'WEBGL_lose_context' );
  228. if ( extension ) extension.restoreContext();
  229. };
  230. this.getPixelRatio = function () {
  231. return _pixelRatio;
  232. };
  233. this.setPixelRatio = function ( value ) {
  234. if ( value === undefined ) return;
  235. _pixelRatio = value;
  236. this.setSize( _width, _height, false );
  237. };
  238. this.getSize = function () {
  239. return {
  240. width: _width,
  241. height: _height
  242. };
  243. };
  244. this.setSize = function ( width, height, updateStyle ) {
  245. if ( vr.isPresenting() ) {
  246. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  247. return;
  248. }
  249. _width = width;
  250. _height = height;
  251. _canvas.width = width * _pixelRatio;
  252. _canvas.height = height * _pixelRatio;
  253. if ( updateStyle !== false ) {
  254. _canvas.style.width = width + 'px';
  255. _canvas.style.height = height + 'px';
  256. }
  257. this.setViewport( 0, 0, width, height );
  258. };
  259. this.getDrawingBufferSize = function () {
  260. return {
  261. width: _width * _pixelRatio,
  262. height: _height * _pixelRatio
  263. };
  264. };
  265. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  266. _width = width;
  267. _height = height;
  268. _pixelRatio = pixelRatio;
  269. _canvas.width = width * pixelRatio;
  270. _canvas.height = height * pixelRatio;
  271. this.setViewport( 0, 0, width, height );
  272. };
  273. this.getCurrentViewport = function () {
  274. return _currentViewport;
  275. };
  276. this.setViewport = function ( x, y, width, height ) {
  277. _viewport.set( x, _height - y - height, width, height );
  278. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  279. };
  280. this.setScissor = function ( x, y, width, height ) {
  281. _scissor.set( x, _height - y - height, width, height );
  282. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  283. };
  284. this.setScissorTest = function ( boolean ) {
  285. state.setScissorTest( _scissorTest = boolean );
  286. };
  287. // Clearing
  288. this.getClearColor = function () {
  289. return background.getClearColor();
  290. };
  291. this.setClearColor = function () {
  292. background.setClearColor.apply( background, arguments );
  293. };
  294. this.getClearAlpha = function () {
  295. return background.getClearAlpha();
  296. };
  297. this.setClearAlpha = function () {
  298. background.setClearAlpha.apply( background, arguments );
  299. };
  300. this.clear = function ( color, depth, stencil ) {
  301. var bits = 0;
  302. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  303. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  304. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  305. _gl.clear( bits );
  306. };
  307. this.clearColor = function () {
  308. this.clear( true, false, false );
  309. };
  310. this.clearDepth = function () {
  311. this.clear( false, true, false );
  312. };
  313. this.clearStencil = function () {
  314. this.clear( false, false, true );
  315. };
  316. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  317. this.setRenderTarget( renderTarget );
  318. this.clear( color, depth, stencil );
  319. };
  320. //
  321. this.dispose = function () {
  322. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  323. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  324. renderLists.dispose();
  325. renderStates.dispose();
  326. properties.dispose();
  327. objects.dispose();
  328. vr.dispose();
  329. animation.stop();
  330. };
  331. // Events
  332. function onContextLost( event ) {
  333. event.preventDefault();
  334. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  335. _isContextLost = true;
  336. }
  337. function onContextRestore( /* event */ ) {
  338. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  339. _isContextLost = false;
  340. initGLContext();
  341. }
  342. function onMaterialDispose( event ) {
  343. var material = event.target;
  344. material.removeEventListener( 'dispose', onMaterialDispose );
  345. deallocateMaterial( material );
  346. }
  347. // Buffer deallocation
  348. function deallocateMaterial( material ) {
  349. releaseMaterialProgramReference( material );
  350. properties.remove( material );
  351. }
  352. function releaseMaterialProgramReference( material ) {
  353. var programInfo = properties.get( material ).program;
  354. material.program = undefined;
  355. if ( programInfo !== undefined ) {
  356. programCache.releaseProgram( programInfo );
  357. }
  358. }
  359. // Buffer rendering
  360. function renderObjectImmediate( object, program ) {
  361. object.render( function ( object ) {
  362. _this.renderBufferImmediate( object, program );
  363. } );
  364. }
  365. this.renderBufferImmediate = function ( object, program ) {
  366. state.initAttributes();
  367. var buffers = properties.get( object );
  368. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  369. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  370. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  371. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  372. var programAttributes = program.getAttributes();
  373. if ( object.hasPositions ) {
  374. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  375. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  376. state.enableAttribute( programAttributes.position );
  377. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  378. }
  379. if ( object.hasNormals ) {
  380. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  381. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  382. state.enableAttribute( programAttributes.normal );
  383. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  384. }
  385. if ( object.hasUvs ) {
  386. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  387. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  388. state.enableAttribute( programAttributes.uv );
  389. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  390. }
  391. if ( object.hasColors ) {
  392. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  393. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  394. state.enableAttribute( programAttributes.color );
  395. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  396. }
  397. state.disableUnusedAttributes();
  398. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  399. object.count = 0;
  400. };
  401. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  402. var frontFaceCW = ( object.isMesh && object.normalMatrix.determinant() < 0 );
  403. state.setMaterial( material, frontFaceCW );
  404. var program = setProgram( camera, fog, material, object );
  405. var updateBuffers = false;
  406. if ( geometry.id !== _currentGeometryProgram.geometry || program.id !== _currentGeometryProgram.program || material.wireframe !== _currentGeometryProgram.wireframe ) {
  407. _currentGeometryProgram.geometry = geometry.id;
  408. _currentGeometryProgram.program = program.id;
  409. _currentGeometryProgram.wireframe = material.wireframe;
  410. updateBuffers = true;
  411. }
  412. if ( object.morphTargetInfluences ) {
  413. morphtargets.update( object, geometry, material, program );
  414. updateBuffers = true;
  415. }
  416. //
  417. var index = geometry.index;
  418. var position = geometry.attributes.position;
  419. var rangeFactor = 1;
  420. if ( material.wireframe === true ) {
  421. index = geometries.getWireframeAttribute( geometry );
  422. rangeFactor = 2;
  423. }
  424. var attribute;
  425. var renderer = bufferRenderer;
  426. if ( index !== null ) {
  427. attribute = attributes.get( index );
  428. renderer = indexedBufferRenderer;
  429. renderer.setIndex( attribute );
  430. }
  431. if ( updateBuffers ) {
  432. setupVertexAttributes( material, program, geometry );
  433. if ( index !== null ) {
  434. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  435. }
  436. }
  437. //
  438. var dataCount = Infinity;
  439. if ( index !== null ) {
  440. dataCount = index.count;
  441. } else if ( position !== undefined ) {
  442. dataCount = position.count;
  443. }
  444. var rangeStart = geometry.drawRange.start * rangeFactor;
  445. var rangeCount = geometry.drawRange.count * rangeFactor;
  446. var groupStart = group !== null ? group.start * rangeFactor : 0;
  447. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  448. var drawStart = Math.max( rangeStart, groupStart );
  449. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  450. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  451. if ( drawCount === 0 ) return;
  452. //
  453. if ( object.isMesh ) {
  454. if ( material.wireframe === true ) {
  455. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  456. renderer.setMode( _gl.LINES );
  457. } else {
  458. switch ( object.drawMode ) {
  459. case TrianglesDrawMode:
  460. renderer.setMode( _gl.TRIANGLES );
  461. break;
  462. case TriangleStripDrawMode:
  463. renderer.setMode( _gl.TRIANGLE_STRIP );
  464. break;
  465. case TriangleFanDrawMode:
  466. renderer.setMode( _gl.TRIANGLE_FAN );
  467. break;
  468. }
  469. }
  470. } else if ( object.isLine ) {
  471. var lineWidth = material.linewidth;
  472. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  473. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  474. if ( object.isLineSegments ) {
  475. renderer.setMode( _gl.LINES );
  476. } else if ( object.isLineLoop ) {
  477. renderer.setMode( _gl.LINE_LOOP );
  478. } else {
  479. renderer.setMode( _gl.LINE_STRIP );
  480. }
  481. } else if ( object.isPoints ) {
  482. renderer.setMode( _gl.POINTS );
  483. } else if ( object.isSprite ) {
  484. renderer.setMode( _gl.TRIANGLES );
  485. }
  486. if ( geometry && geometry.isInstancedBufferGeometry ) {
  487. if ( geometry.maxInstancedCount > 0 ) {
  488. renderer.renderInstances( geometry, drawStart, drawCount );
  489. }
  490. } else {
  491. renderer.render( drawStart, drawCount );
  492. }
  493. };
  494. function setupVertexAttributes( material, program, geometry ) {
  495. if ( geometry && geometry.isInstancedBufferGeometry & ! capabilities.isWebGL2 ) {
  496. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  497. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  498. return;
  499. }
  500. }
  501. state.initAttributes();
  502. var geometryAttributes = geometry.attributes;
  503. var programAttributes = program.getAttributes();
  504. var materialDefaultAttributeValues = material.defaultAttributeValues;
  505. for ( var name in programAttributes ) {
  506. var programAttribute = programAttributes[ name ];
  507. if ( programAttribute >= 0 ) {
  508. var geometryAttribute = geometryAttributes[ name ];
  509. if ( geometryAttribute !== undefined ) {
  510. var normalized = geometryAttribute.normalized;
  511. var size = geometryAttribute.itemSize;
  512. var attribute = attributes.get( geometryAttribute );
  513. // TODO Attribute may not be available on context restore
  514. if ( attribute === undefined ) continue;
  515. var buffer = attribute.buffer;
  516. var type = attribute.type;
  517. var bytesPerElement = attribute.bytesPerElement;
  518. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  519. var data = geometryAttribute.data;
  520. var stride = data.stride;
  521. var offset = geometryAttribute.offset;
  522. if ( data && data.isInstancedInterleavedBuffer ) {
  523. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  524. if ( geometry.maxInstancedCount === undefined ) {
  525. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  526. }
  527. } else {
  528. state.enableAttribute( programAttribute );
  529. }
  530. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  531. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  532. } else {
  533. if ( geometryAttribute.isInstancedBufferAttribute ) {
  534. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  535. if ( geometry.maxInstancedCount === undefined ) {
  536. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  537. }
  538. } else {
  539. state.enableAttribute( programAttribute );
  540. }
  541. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  542. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  543. }
  544. } else if ( materialDefaultAttributeValues !== undefined ) {
  545. var value = materialDefaultAttributeValues[ name ];
  546. if ( value !== undefined ) {
  547. switch ( value.length ) {
  548. case 2:
  549. _gl.vertexAttrib2fv( programAttribute, value );
  550. break;
  551. case 3:
  552. _gl.vertexAttrib3fv( programAttribute, value );
  553. break;
  554. case 4:
  555. _gl.vertexAttrib4fv( programAttribute, value );
  556. break;
  557. default:
  558. _gl.vertexAttrib1fv( programAttribute, value );
  559. }
  560. }
  561. }
  562. }
  563. }
  564. state.disableUnusedAttributes();
  565. }
  566. // Compile
  567. this.compile = function ( scene, camera ) {
  568. currentRenderState = renderStates.get( scene, camera );
  569. currentRenderState.init();
  570. scene.traverse( function ( object ) {
  571. if ( object.isLight ) {
  572. currentRenderState.pushLight( object );
  573. if ( object.castShadow ) {
  574. currentRenderState.pushShadow( object );
  575. }
  576. }
  577. } );
  578. currentRenderState.setupLights( camera );
  579. scene.traverse( function ( object ) {
  580. if ( object.material ) {
  581. if ( Array.isArray( object.material ) ) {
  582. for ( var i = 0; i < object.material.length; i ++ ) {
  583. initMaterial( object.material[ i ], scene.fog, object );
  584. }
  585. } else {
  586. initMaterial( object.material, scene.fog, object );
  587. }
  588. }
  589. } );
  590. };
  591. // Animation Loop
  592. var onAnimationFrameCallback = null;
  593. function onAnimationFrame( time ) {
  594. if ( vr.isPresenting() ) return;
  595. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  596. }
  597. var animation = new WebGLAnimation();
  598. animation.setAnimationLoop( onAnimationFrame );
  599. if ( typeof window !== 'undefined' ) animation.setContext( window );
  600. this.setAnimationLoop = function ( callback ) {
  601. onAnimationFrameCallback = callback;
  602. vr.setAnimationLoop( callback );
  603. animation.start();
  604. };
  605. // Rendering
  606. this.render = function ( scene, camera, renderTarget, forceClear ) {
  607. if ( ! ( camera && camera.isCamera ) ) {
  608. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  609. return;
  610. }
  611. if ( _isContextLost ) return;
  612. // reset caching for this frame
  613. _currentGeometryProgram.geometry = null;
  614. _currentGeometryProgram.program = null;
  615. _currentGeometryProgram.wireframe = false;
  616. _currentMaterialId = - 1;
  617. _currentCamera = null;
  618. // update scene graph
  619. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  620. // update camera matrices and frustum
  621. if ( camera.parent === null ) camera.updateMatrixWorld();
  622. if ( vr.enabled ) {
  623. camera = vr.getCamera( camera );
  624. }
  625. //
  626. currentRenderState = renderStates.get( scene, camera );
  627. currentRenderState.init();
  628. scene.onBeforeRender( _this, scene, camera, renderTarget );
  629. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  630. _frustum.setFromMatrix( _projScreenMatrix );
  631. _localClippingEnabled = this.localClippingEnabled;
  632. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  633. currentRenderList = renderLists.get( scene, camera );
  634. currentRenderList.init();
  635. projectObject( scene, camera, _this.sortObjects );
  636. if ( _this.sortObjects === true ) {
  637. currentRenderList.sort();
  638. }
  639. //
  640. if ( _clippingEnabled ) _clipping.beginShadows();
  641. var shadowsArray = currentRenderState.state.shadowsArray;
  642. shadowMap.render( shadowsArray, scene, camera );
  643. currentRenderState.setupLights( camera );
  644. if ( _clippingEnabled ) _clipping.endShadows();
  645. //
  646. if ( this.info.autoReset ) this.info.reset();
  647. if ( renderTarget === undefined ) {
  648. renderTarget = null;
  649. }
  650. this.setRenderTarget( renderTarget );
  651. //
  652. background.render( currentRenderList, scene, camera, forceClear );
  653. // render scene
  654. var opaqueObjects = currentRenderList.opaque;
  655. var transparentObjects = currentRenderList.transparent;
  656. if ( scene.overrideMaterial ) {
  657. var overrideMaterial = scene.overrideMaterial;
  658. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  659. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  660. } else {
  661. // opaque pass (front-to-back order)
  662. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  663. // transparent pass (back-to-front order)
  664. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  665. }
  666. // Generate mipmap if we're using any kind of mipmap filtering
  667. if ( renderTarget ) {
  668. textures.updateRenderTargetMipmap( renderTarget );
  669. }
  670. // Ensure depth buffer writing is enabled so it can be cleared on next render
  671. state.buffers.depth.setTest( true );
  672. state.buffers.depth.setMask( true );
  673. state.buffers.color.setMask( true );
  674. state.setPolygonOffset( false );
  675. scene.onAfterRender( _this, scene, camera );
  676. if ( vr.enabled ) {
  677. vr.submitFrame();
  678. }
  679. // _gl.finish();
  680. currentRenderList = null;
  681. currentRenderState = null;
  682. };
  683. /*
  684. // TODO Duplicated code (Frustum)
  685. var _sphere = new Sphere();
  686. function isObjectViewable( object ) {
  687. var geometry = object.geometry;
  688. if ( geometry.boundingSphere === null )
  689. geometry.computeBoundingSphere();
  690. _sphere.copy( geometry.boundingSphere ).
  691. applyMatrix4( object.matrixWorld );
  692. return isSphereViewable( _sphere );
  693. }
  694. function isSpriteViewable( sprite ) {
  695. _sphere.center.set( 0, 0, 0 );
  696. _sphere.radius = 0.7071067811865476;
  697. _sphere.applyMatrix4( sprite.matrixWorld );
  698. return isSphereViewable( _sphere );
  699. }
  700. function isSphereViewable( sphere ) {
  701. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  702. var numPlanes = _clipping.numPlanes;
  703. if ( numPlanes === 0 ) return true;
  704. var planes = _this.clippingPlanes,
  705. center = sphere.center,
  706. negRad = - sphere.radius,
  707. i = 0;
  708. do {
  709. // out when deeper than radius in the negative halfspace
  710. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  711. } while ( ++ i !== numPlanes );
  712. return true;
  713. }
  714. */
  715. function projectObject( object, camera, sortObjects ) {
  716. if ( object.visible === false ) return;
  717. var visible = object.layers.test( camera.layers );
  718. if ( visible ) {
  719. if ( object.isLight ) {
  720. currentRenderState.pushLight( object );
  721. if ( object.castShadow ) {
  722. currentRenderState.pushShadow( object );
  723. }
  724. } else if ( object.isSprite ) {
  725. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  726. if ( sortObjects ) {
  727. _vector3.setFromMatrixPosition( object.matrixWorld )
  728. .applyMatrix4( _projScreenMatrix );
  729. }
  730. var geometry = objects.update( object );
  731. var material = object.material;
  732. currentRenderList.push( object, geometry, material, _vector3.z, null );
  733. }
  734. } else if ( object.isImmediateRenderObject ) {
  735. if ( sortObjects ) {
  736. _vector3.setFromMatrixPosition( object.matrixWorld )
  737. .applyMatrix4( _projScreenMatrix );
  738. }
  739. currentRenderList.push( object, null, object.material, _vector3.z, null );
  740. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  741. if ( object.isSkinnedMesh ) {
  742. object.skeleton.update();
  743. }
  744. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  745. if ( sortObjects ) {
  746. _vector3.setFromMatrixPosition( object.matrixWorld )
  747. .applyMatrix4( _projScreenMatrix );
  748. }
  749. var geometry = objects.update( object );
  750. var material = object.material;
  751. if ( Array.isArray( material ) ) {
  752. var groups = geometry.groups;
  753. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  754. var group = groups[ i ];
  755. var groupMaterial = material[ group.materialIndex ];
  756. if ( groupMaterial && groupMaterial.visible ) {
  757. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  758. }
  759. }
  760. } else if ( material.visible ) {
  761. currentRenderList.push( object, geometry, material, _vector3.z, null );
  762. }
  763. }
  764. }
  765. }
  766. var children = object.children;
  767. for ( var i = 0, l = children.length; i < l; i ++ ) {
  768. projectObject( children[ i ], camera, sortObjects );
  769. }
  770. }
  771. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  772. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  773. var renderItem = renderList[ i ];
  774. var object = renderItem.object;
  775. var geometry = renderItem.geometry;
  776. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  777. var group = renderItem.group;
  778. if ( camera.isArrayCamera ) {
  779. _currentArrayCamera = camera;
  780. var cameras = camera.cameras;
  781. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  782. var camera2 = cameras[ j ];
  783. if ( object.layers.test( camera2.layers ) ) {
  784. if ( 'viewport' in camera2 ) { // XR
  785. state.viewport( _currentViewport.copy( camera2.viewport ) );
  786. } else {
  787. var bounds = camera2.bounds;
  788. var x = bounds.x * _width;
  789. var y = bounds.y * _height;
  790. var width = bounds.z * _width;
  791. var height = bounds.w * _height;
  792. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  793. }
  794. renderObject( object, scene, camera2, geometry, material, group );
  795. }
  796. }
  797. } else {
  798. _currentArrayCamera = null;
  799. renderObject( object, scene, camera, geometry, material, group );
  800. }
  801. }
  802. }
  803. function renderObject( object, scene, camera, geometry, material, group ) {
  804. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  805. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  806. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  807. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  808. if ( object.isImmediateRenderObject ) {
  809. state.setMaterial( material );
  810. var program = setProgram( camera, scene.fog, material, object );
  811. _currentGeometryProgram.geometry = null;
  812. _currentGeometryProgram.program = null;
  813. _currentGeometryProgram.wireframe = false;
  814. renderObjectImmediate( object, program );
  815. } else {
  816. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  817. }
  818. object.onAfterRender( _this, scene, camera, geometry, material, group );
  819. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  820. }
  821. function initMaterial( material, fog, object ) {
  822. var materialProperties = properties.get( material );
  823. var lights = currentRenderState.state.lights;
  824. var shadowsArray = currentRenderState.state.shadowsArray;
  825. var parameters = programCache.getParameters(
  826. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  827. var code = programCache.getProgramCode( material, parameters );
  828. var program = materialProperties.program;
  829. var programChange = true;
  830. if ( program === undefined ) {
  831. // new material
  832. material.addEventListener( 'dispose', onMaterialDispose );
  833. } else if ( program.code !== code ) {
  834. // changed glsl or parameters
  835. releaseMaterialProgramReference( material );
  836. } else if ( materialProperties.lightsHash !== lights.state.hash ) {
  837. properties.update( material, 'lightsHash', lights.state.hash );
  838. programChange = false;
  839. } else if ( parameters.shaderID !== undefined ) {
  840. // same glsl and uniform list
  841. return;
  842. } else {
  843. // only rebuild uniform list
  844. programChange = false;
  845. }
  846. if ( programChange ) {
  847. if ( parameters.shaderID ) {
  848. var shader = ShaderLib[ parameters.shaderID ];
  849. materialProperties.shader = {
  850. name: material.type,
  851. uniforms: UniformsUtils.clone( shader.uniforms ),
  852. vertexShader: shader.vertexShader,
  853. fragmentShader: shader.fragmentShader
  854. };
  855. } else {
  856. materialProperties.shader = {
  857. name: material.type,
  858. uniforms: material.uniforms,
  859. vertexShader: material.vertexShader,
  860. fragmentShader: material.fragmentShader
  861. };
  862. }
  863. material.onBeforeCompile( materialProperties.shader, _this );
  864. // Computing code again as onBeforeCompile may have changed the shaders
  865. code = programCache.getProgramCode( material, parameters );
  866. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  867. materialProperties.program = program;
  868. material.program = program;
  869. }
  870. var programAttributes = program.getAttributes();
  871. if ( material.morphTargets ) {
  872. material.numSupportedMorphTargets = 0;
  873. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  874. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  875. material.numSupportedMorphTargets ++;
  876. }
  877. }
  878. }
  879. if ( material.morphNormals ) {
  880. material.numSupportedMorphNormals = 0;
  881. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  882. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  883. material.numSupportedMorphNormals ++;
  884. }
  885. }
  886. }
  887. var uniforms = materialProperties.shader.uniforms;
  888. if ( ! material.isShaderMaterial &&
  889. ! material.isRawShaderMaterial ||
  890. material.clipping === true ) {
  891. materialProperties.numClippingPlanes = _clipping.numPlanes;
  892. materialProperties.numIntersection = _clipping.numIntersection;
  893. uniforms.clippingPlanes = _clipping.uniform;
  894. }
  895. materialProperties.fog = fog;
  896. // store the light setup it was created for
  897. materialProperties.lightsHash = lights.state.hash;
  898. if ( material.lights ) {
  899. // wire up the material to this renderer's lighting state
  900. uniforms.ambientLightColor.value = lights.state.ambient;
  901. uniforms.directionalLights.value = lights.state.directional;
  902. uniforms.spotLights.value = lights.state.spot;
  903. uniforms.rectAreaLights.value = lights.state.rectArea;
  904. uniforms.pointLights.value = lights.state.point;
  905. uniforms.hemisphereLights.value = lights.state.hemi;
  906. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  907. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  908. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  909. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  910. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  911. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  912. // TODO (abelnation): add area lights shadow info to uniforms
  913. }
  914. var progUniforms = materialProperties.program.getUniforms(),
  915. uniformsList =
  916. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  917. materialProperties.uniformsList = uniformsList;
  918. }
  919. function setProgram( camera, fog, material, object ) {
  920. _usedTextureUnits = 0;
  921. var materialProperties = properties.get( material );
  922. var lights = currentRenderState.state.lights;
  923. if ( _clippingEnabled ) {
  924. if ( _localClippingEnabled || camera !== _currentCamera ) {
  925. var useCache =
  926. camera === _currentCamera &&
  927. material.id === _currentMaterialId;
  928. // we might want to call this function with some ClippingGroup
  929. // object instead of the material, once it becomes feasible
  930. // (#8465, #8379)
  931. _clipping.setState(
  932. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  933. camera, materialProperties, useCache );
  934. }
  935. }
  936. if ( material.needsUpdate === false ) {
  937. if ( materialProperties.program === undefined ) {
  938. material.needsUpdate = true;
  939. } else if ( material.fog && materialProperties.fog !== fog ) {
  940. material.needsUpdate = true;
  941. } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) {
  942. material.needsUpdate = true;
  943. } else if ( materialProperties.numClippingPlanes !== undefined &&
  944. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  945. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  946. material.needsUpdate = true;
  947. }
  948. }
  949. if ( material.needsUpdate ) {
  950. initMaterial( material, fog, object );
  951. material.needsUpdate = false;
  952. }
  953. var refreshProgram = false;
  954. var refreshMaterial = false;
  955. var refreshLights = false;
  956. var program = materialProperties.program,
  957. p_uniforms = program.getUniforms(),
  958. m_uniforms = materialProperties.shader.uniforms;
  959. if ( state.useProgram( program.program ) ) {
  960. refreshProgram = true;
  961. refreshMaterial = true;
  962. refreshLights = true;
  963. }
  964. if ( material.id !== _currentMaterialId ) {
  965. _currentMaterialId = material.id;
  966. refreshMaterial = true;
  967. }
  968. if ( refreshProgram || camera !== _currentCamera ) {
  969. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  970. if ( capabilities.logarithmicDepthBuffer ) {
  971. p_uniforms.setValue( _gl, 'logDepthBufFC',
  972. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  973. }
  974. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  975. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  976. _currentCamera = ( _currentArrayCamera || camera );
  977. // lighting uniforms depend on the camera so enforce an update
  978. // now, in case this material supports lights - or later, when
  979. // the next material that does gets activated:
  980. refreshMaterial = true; // set to true on material change
  981. refreshLights = true; // remains set until update done
  982. }
  983. // load material specific uniforms
  984. // (shader material also gets them for the sake of genericity)
  985. if ( material.isShaderMaterial ||
  986. material.isMeshPhongMaterial ||
  987. material.isMeshStandardMaterial ||
  988. material.envMap ) {
  989. var uCamPos = p_uniforms.map.cameraPosition;
  990. if ( uCamPos !== undefined ) {
  991. uCamPos.setValue( _gl,
  992. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  993. }
  994. }
  995. if ( material.isMeshPhongMaterial ||
  996. material.isMeshLambertMaterial ||
  997. material.isMeshBasicMaterial ||
  998. material.isMeshStandardMaterial ||
  999. material.isShaderMaterial ||
  1000. material.skinning ) {
  1001. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1002. }
  1003. }
  1004. // skinning uniforms must be set even if material didn't change
  1005. // auto-setting of texture unit for bone texture must go before other textures
  1006. // not sure why, but otherwise weird things happen
  1007. if ( material.skinning ) {
  1008. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1009. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1010. var skeleton = object.skeleton;
  1011. if ( skeleton ) {
  1012. var bones = skeleton.bones;
  1013. if ( capabilities.floatVertexTextures ) {
  1014. if ( skeleton.boneTexture === undefined ) {
  1015. // layout (1 matrix = 4 pixels)
  1016. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  1017. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  1018. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  1019. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  1020. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  1021. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  1022. size = _Math.ceilPowerOfTwo( size );
  1023. size = Math.max( size, 4 );
  1024. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  1025. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  1026. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  1027. boneTexture.needsUpdate = true;
  1028. skeleton.boneMatrices = boneMatrices;
  1029. skeleton.boneTexture = boneTexture;
  1030. skeleton.boneTextureSize = size;
  1031. }
  1032. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  1033. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  1034. } else {
  1035. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  1036. }
  1037. }
  1038. }
  1039. if ( refreshMaterial ) {
  1040. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  1041. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  1042. if ( material.lights ) {
  1043. // the current material requires lighting info
  1044. // note: all lighting uniforms are always set correctly
  1045. // they simply reference the renderer's state for their
  1046. // values
  1047. //
  1048. // use the current material's .needsUpdate flags to set
  1049. // the GL state when required
  1050. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1051. }
  1052. // refresh uniforms common to several materials
  1053. if ( fog && material.fog ) {
  1054. refreshUniformsFog( m_uniforms, fog );
  1055. }
  1056. if ( material.isMeshBasicMaterial ) {
  1057. refreshUniformsCommon( m_uniforms, material );
  1058. } else if ( material.isMeshLambertMaterial ) {
  1059. refreshUniformsCommon( m_uniforms, material );
  1060. refreshUniformsLambert( m_uniforms, material );
  1061. } else if ( material.isMeshPhongMaterial ) {
  1062. refreshUniformsCommon( m_uniforms, material );
  1063. if ( material.isMeshToonMaterial ) {
  1064. refreshUniformsToon( m_uniforms, material );
  1065. } else {
  1066. refreshUniformsPhong( m_uniforms, material );
  1067. }
  1068. } else if ( material.isMeshStandardMaterial ) {
  1069. refreshUniformsCommon( m_uniforms, material );
  1070. if ( material.isMeshPhysicalMaterial ) {
  1071. refreshUniformsPhysical( m_uniforms, material );
  1072. } else {
  1073. refreshUniformsStandard( m_uniforms, material );
  1074. }
  1075. } else if ( material.isMeshDepthMaterial ) {
  1076. refreshUniformsCommon( m_uniforms, material );
  1077. refreshUniformsDepth( m_uniforms, material );
  1078. } else if ( material.isMeshDistanceMaterial ) {
  1079. refreshUniformsCommon( m_uniforms, material );
  1080. refreshUniformsDistance( m_uniforms, material );
  1081. } else if ( material.isMeshNormalMaterial ) {
  1082. refreshUniformsCommon( m_uniforms, material );
  1083. refreshUniformsNormal( m_uniforms, material );
  1084. } else if ( material.isLineBasicMaterial ) {
  1085. refreshUniformsLine( m_uniforms, material );
  1086. if ( material.isLineDashedMaterial ) {
  1087. refreshUniformsDash( m_uniforms, material );
  1088. }
  1089. } else if ( material.isPointsMaterial ) {
  1090. refreshUniformsPoints( m_uniforms, material );
  1091. } else if ( material.isSpriteMaterial ) {
  1092. refreshUniformsSprites( m_uniforms, material );
  1093. } else if ( material.isShadowMaterial ) {
  1094. m_uniforms.color.value = material.color;
  1095. m_uniforms.opacity.value = material.opacity;
  1096. }
  1097. // RectAreaLight Texture
  1098. // TODO (mrdoob): Find a nicer implementation
  1099. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  1100. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  1101. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  1102. }
  1103. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  1104. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  1105. material.uniformsNeedUpdate = false;
  1106. }
  1107. if ( material.isSpriteMaterial ) {
  1108. p_uniforms.setValue( _gl, 'center', object.center );
  1109. }
  1110. // common matrices
  1111. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1112. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1113. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1114. return program;
  1115. }
  1116. // Uniforms (refresh uniforms objects)
  1117. function refreshUniformsCommon( uniforms, material ) {
  1118. uniforms.opacity.value = material.opacity;
  1119. if ( material.color ) {
  1120. uniforms.diffuse.value = material.color;
  1121. }
  1122. if ( material.emissive ) {
  1123. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1124. }
  1125. if ( material.map ) {
  1126. uniforms.map.value = material.map;
  1127. }
  1128. if ( material.alphaMap ) {
  1129. uniforms.alphaMap.value = material.alphaMap;
  1130. }
  1131. if ( material.specularMap ) {
  1132. uniforms.specularMap.value = material.specularMap;
  1133. }
  1134. if ( material.envMap ) {
  1135. uniforms.envMap.value = material.envMap;
  1136. // don't flip CubeTexture envMaps, flip everything else:
  1137. // WebGLRenderTargetCube will be flipped for backwards compatibility
  1138. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  1139. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  1140. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  1141. uniforms.reflectivity.value = material.reflectivity;
  1142. uniforms.refractionRatio.value = material.refractionRatio;
  1143. uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel;
  1144. }
  1145. if ( material.lightMap ) {
  1146. uniforms.lightMap.value = material.lightMap;
  1147. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1148. }
  1149. if ( material.aoMap ) {
  1150. uniforms.aoMap.value = material.aoMap;
  1151. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1152. }
  1153. // uv repeat and offset setting priorities
  1154. // 1. color map
  1155. // 2. specular map
  1156. // 3. normal map
  1157. // 4. bump map
  1158. // 5. alpha map
  1159. // 6. emissive map
  1160. var uvScaleMap;
  1161. if ( material.map ) {
  1162. uvScaleMap = material.map;
  1163. } else if ( material.specularMap ) {
  1164. uvScaleMap = material.specularMap;
  1165. } else if ( material.displacementMap ) {
  1166. uvScaleMap = material.displacementMap;
  1167. } else if ( material.normalMap ) {
  1168. uvScaleMap = material.normalMap;
  1169. } else if ( material.bumpMap ) {
  1170. uvScaleMap = material.bumpMap;
  1171. } else if ( material.roughnessMap ) {
  1172. uvScaleMap = material.roughnessMap;
  1173. } else if ( material.metalnessMap ) {
  1174. uvScaleMap = material.metalnessMap;
  1175. } else if ( material.alphaMap ) {
  1176. uvScaleMap = material.alphaMap;
  1177. } else if ( material.emissiveMap ) {
  1178. uvScaleMap = material.emissiveMap;
  1179. }
  1180. if ( uvScaleMap !== undefined ) {
  1181. // backwards compatibility
  1182. if ( uvScaleMap.isWebGLRenderTarget ) {
  1183. uvScaleMap = uvScaleMap.texture;
  1184. }
  1185. if ( uvScaleMap.matrixAutoUpdate === true ) {
  1186. uvScaleMap.updateMatrix();
  1187. }
  1188. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  1189. }
  1190. }
  1191. function refreshUniformsLine( uniforms, material ) {
  1192. uniforms.diffuse.value = material.color;
  1193. uniforms.opacity.value = material.opacity;
  1194. }
  1195. function refreshUniformsDash( uniforms, material ) {
  1196. uniforms.dashSize.value = material.dashSize;
  1197. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1198. uniforms.scale.value = material.scale;
  1199. }
  1200. function refreshUniformsPoints( uniforms, material ) {
  1201. uniforms.diffuse.value = material.color;
  1202. uniforms.opacity.value = material.opacity;
  1203. uniforms.size.value = material.size * _pixelRatio;
  1204. uniforms.scale.value = _height * 0.5;
  1205. uniforms.map.value = material.map;
  1206. if ( material.map !== null ) {
  1207. if ( material.map.matrixAutoUpdate === true ) {
  1208. material.map.updateMatrix();
  1209. }
  1210. uniforms.uvTransform.value.copy( material.map.matrix );
  1211. }
  1212. }
  1213. function refreshUniformsSprites( uniforms, material ) {
  1214. uniforms.diffuse.value = material.color;
  1215. uniforms.opacity.value = material.opacity;
  1216. uniforms.rotation.value = material.rotation;
  1217. uniforms.map.value = material.map;
  1218. if ( material.map !== null ) {
  1219. if ( material.map.matrixAutoUpdate === true ) {
  1220. material.map.updateMatrix();
  1221. }
  1222. uniforms.uvTransform.value.copy( material.map.matrix );
  1223. }
  1224. }
  1225. function refreshUniformsFog( uniforms, fog ) {
  1226. uniforms.fogColor.value = fog.color;
  1227. if ( fog.isFog ) {
  1228. uniforms.fogNear.value = fog.near;
  1229. uniforms.fogFar.value = fog.far;
  1230. } else if ( fog.isFogExp2 ) {
  1231. uniforms.fogDensity.value = fog.density;
  1232. }
  1233. }
  1234. function refreshUniformsLambert( uniforms, material ) {
  1235. if ( material.emissiveMap ) {
  1236. uniforms.emissiveMap.value = material.emissiveMap;
  1237. }
  1238. }
  1239. function refreshUniformsPhong( uniforms, material ) {
  1240. uniforms.specular.value = material.specular;
  1241. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1242. if ( material.emissiveMap ) {
  1243. uniforms.emissiveMap.value = material.emissiveMap;
  1244. }
  1245. if ( material.bumpMap ) {
  1246. uniforms.bumpMap.value = material.bumpMap;
  1247. uniforms.bumpScale.value = material.bumpScale;
  1248. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1249. }
  1250. if ( material.normalMap ) {
  1251. uniforms.normalMap.value = material.normalMap;
  1252. uniforms.normalScale.value.copy( material.normalScale );
  1253. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1254. }
  1255. if ( material.displacementMap ) {
  1256. uniforms.displacementMap.value = material.displacementMap;
  1257. uniforms.displacementScale.value = material.displacementScale;
  1258. uniforms.displacementBias.value = material.displacementBias;
  1259. }
  1260. }
  1261. function refreshUniformsToon( uniforms, material ) {
  1262. refreshUniformsPhong( uniforms, material );
  1263. if ( material.gradientMap ) {
  1264. uniforms.gradientMap.value = material.gradientMap;
  1265. }
  1266. }
  1267. function refreshUniformsStandard( uniforms, material ) {
  1268. uniforms.roughness.value = material.roughness;
  1269. uniforms.metalness.value = material.metalness;
  1270. if ( material.roughnessMap ) {
  1271. uniforms.roughnessMap.value = material.roughnessMap;
  1272. }
  1273. if ( material.metalnessMap ) {
  1274. uniforms.metalnessMap.value = material.metalnessMap;
  1275. }
  1276. if ( material.emissiveMap ) {
  1277. uniforms.emissiveMap.value = material.emissiveMap;
  1278. }
  1279. if ( material.bumpMap ) {
  1280. uniforms.bumpMap.value = material.bumpMap;
  1281. uniforms.bumpScale.value = material.bumpScale;
  1282. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1283. }
  1284. if ( material.normalMap ) {
  1285. uniforms.normalMap.value = material.normalMap;
  1286. uniforms.normalScale.value.copy( material.normalScale );
  1287. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1288. }
  1289. if ( material.displacementMap ) {
  1290. uniforms.displacementMap.value = material.displacementMap;
  1291. uniforms.displacementScale.value = material.displacementScale;
  1292. uniforms.displacementBias.value = material.displacementBias;
  1293. }
  1294. if ( material.envMap ) {
  1295. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1296. uniforms.envMapIntensity.value = material.envMapIntensity;
  1297. }
  1298. }
  1299. function refreshUniformsPhysical( uniforms, material ) {
  1300. refreshUniformsStandard( uniforms, material );
  1301. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  1302. uniforms.clearCoat.value = material.clearCoat;
  1303. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  1304. }
  1305. function refreshUniformsDepth( uniforms, material ) {
  1306. if ( material.displacementMap ) {
  1307. uniforms.displacementMap.value = material.displacementMap;
  1308. uniforms.displacementScale.value = material.displacementScale;
  1309. uniforms.displacementBias.value = material.displacementBias;
  1310. }
  1311. }
  1312. function refreshUniformsDistance( uniforms, material ) {
  1313. if ( material.displacementMap ) {
  1314. uniforms.displacementMap.value = material.displacementMap;
  1315. uniforms.displacementScale.value = material.displacementScale;
  1316. uniforms.displacementBias.value = material.displacementBias;
  1317. }
  1318. uniforms.referencePosition.value.copy( material.referencePosition );
  1319. uniforms.nearDistance.value = material.nearDistance;
  1320. uniforms.farDistance.value = material.farDistance;
  1321. }
  1322. function refreshUniformsNormal( uniforms, material ) {
  1323. if ( material.bumpMap ) {
  1324. uniforms.bumpMap.value = material.bumpMap;
  1325. uniforms.bumpScale.value = material.bumpScale;
  1326. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1327. }
  1328. if ( material.normalMap ) {
  1329. uniforms.normalMap.value = material.normalMap;
  1330. uniforms.normalScale.value.copy( material.normalScale );
  1331. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1332. }
  1333. if ( material.displacementMap ) {
  1334. uniforms.displacementMap.value = material.displacementMap;
  1335. uniforms.displacementScale.value = material.displacementScale;
  1336. uniforms.displacementBias.value = material.displacementBias;
  1337. }
  1338. }
  1339. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1340. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1341. uniforms.ambientLightColor.needsUpdate = value;
  1342. uniforms.directionalLights.needsUpdate = value;
  1343. uniforms.pointLights.needsUpdate = value;
  1344. uniforms.spotLights.needsUpdate = value;
  1345. uniforms.rectAreaLights.needsUpdate = value;
  1346. uniforms.hemisphereLights.needsUpdate = value;
  1347. }
  1348. // Textures
  1349. function allocTextureUnit() {
  1350. var textureUnit = _usedTextureUnits;
  1351. if ( textureUnit >= capabilities.maxTextures ) {
  1352. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  1353. }
  1354. _usedTextureUnits += 1;
  1355. return textureUnit;
  1356. }
  1357. this.allocTextureUnit = allocTextureUnit;
  1358. // this.setTexture2D = setTexture2D;
  1359. this.setTexture2D = ( function () {
  1360. var warned = false;
  1361. // backwards compatibility: peel texture.texture
  1362. return function setTexture2D( texture, slot ) {
  1363. if ( texture && texture.isWebGLRenderTarget ) {
  1364. if ( ! warned ) {
  1365. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  1366. warned = true;
  1367. }
  1368. texture = texture.texture;
  1369. }
  1370. textures.setTexture2D( texture, slot );
  1371. };
  1372. }() );
  1373. this.setTexture = ( function () {
  1374. var warned = false;
  1375. return function setTexture( texture, slot ) {
  1376. if ( ! warned ) {
  1377. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  1378. warned = true;
  1379. }
  1380. textures.setTexture2D( texture, slot );
  1381. };
  1382. }() );
  1383. this.setTextureCube = ( function () {
  1384. var warned = false;
  1385. return function setTextureCube( texture, slot ) {
  1386. // backwards compatibility: peel texture.texture
  1387. if ( texture && texture.isWebGLRenderTargetCube ) {
  1388. if ( ! warned ) {
  1389. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  1390. warned = true;
  1391. }
  1392. texture = texture.texture;
  1393. }
  1394. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  1395. // TODO: unify these code paths
  1396. if ( ( texture && texture.isCubeTexture ) ||
  1397. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  1398. // CompressedTexture can have Array in image :/
  1399. // this function alone should take care of cube textures
  1400. textures.setTextureCube( texture, slot );
  1401. } else {
  1402. // assumed: texture property of THREE.WebGLRenderTargetCube
  1403. textures.setTextureCubeDynamic( texture, slot );
  1404. }
  1405. };
  1406. }() );
  1407. //
  1408. this.setFramebuffer = function ( value ) {
  1409. _framebuffer = value;
  1410. };
  1411. this.getRenderTarget = function () {
  1412. return _currentRenderTarget;
  1413. };
  1414. this.setRenderTarget = function ( renderTarget ) {
  1415. _currentRenderTarget = renderTarget;
  1416. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1417. textures.setupRenderTarget( renderTarget );
  1418. }
  1419. var framebuffer = _framebuffer;
  1420. var isCube = false;
  1421. if ( renderTarget ) {
  1422. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1423. if ( renderTarget.isWebGLRenderTargetCube ) {
  1424. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  1425. isCube = true;
  1426. } else {
  1427. framebuffer = __webglFramebuffer;
  1428. }
  1429. _currentViewport.copy( renderTarget.viewport );
  1430. _currentScissor.copy( renderTarget.scissor );
  1431. _currentScissorTest = renderTarget.scissorTest;
  1432. } else {
  1433. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  1434. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  1435. _currentScissorTest = _scissorTest;
  1436. }
  1437. if ( _currentFramebuffer !== framebuffer ) {
  1438. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1439. _currentFramebuffer = framebuffer;
  1440. }
  1441. state.viewport( _currentViewport );
  1442. state.scissor( _currentScissor );
  1443. state.setScissorTest( _currentScissorTest );
  1444. if ( isCube ) {
  1445. var textureProperties = properties.get( renderTarget.texture );
  1446. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  1447. }
  1448. };
  1449. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  1450. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1451. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1452. return;
  1453. }
  1454. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1455. if ( framebuffer ) {
  1456. var restore = false;
  1457. if ( framebuffer !== _currentFramebuffer ) {
  1458. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1459. restore = true;
  1460. }
  1461. try {
  1462. var texture = renderTarget.texture;
  1463. var textureFormat = texture.format;
  1464. var textureType = texture.type;
  1465. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1466. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1467. return;
  1468. }
  1469. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  1470. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  1471. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  1472. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1473. return;
  1474. }
  1475. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  1476. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1477. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1478. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  1479. }
  1480. } else {
  1481. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  1482. }
  1483. } finally {
  1484. if ( restore ) {
  1485. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  1486. }
  1487. }
  1488. }
  1489. };
  1490. this.copyFramebufferToTexture = function ( position, texture, level ) {
  1491. var width = texture.image.width;
  1492. var height = texture.image.height;
  1493. var glFormat = utils.convert( texture.format );
  1494. this.setTexture2D( texture, 0 );
  1495. _gl.copyTexImage2D( _gl.TEXTURE_2D, level || 0, glFormat, position.x, position.y, width, height, 0 );
  1496. };
  1497. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  1498. var width = srcTexture.image.width;
  1499. var height = srcTexture.image.height;
  1500. var glFormat = utils.convert( dstTexture.format );
  1501. var glType = utils.convert( dstTexture.type );
  1502. this.setTexture2D( dstTexture, 0 );
  1503. if ( srcTexture.isDataTexture ) {
  1504. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  1505. } else {
  1506. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  1507. }
  1508. };
  1509. }
  1510. export { WebGLRenderer };
粤ICP备19079148号