WebGLRenderer.js 59 KB

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