2
0

WebGLRenderer.js 59 KB

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