WebGLRenderer.js 61 KB

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