WebGLRenderer.js 61 KB

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