WebGLRenderer.js 61 KB

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