WebGLRenderer.js 61 KB

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