WebGLRenderer.js 57 KB

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