WebGLRenderer.js 62 KB

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