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. // shadow map
  225. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  226. this.shadowMap = shadowMap;
  227. // API
  228. this.getContext = function () {
  229. return _gl;
  230. };
  231. this.getContextAttributes = function () {
  232. return _gl.getContextAttributes();
  233. };
  234. this.forceContextLoss = function () {
  235. var extension = extensions.get( 'WEBGL_lose_context' );
  236. if ( extension ) extension.loseContext();
  237. };
  238. this.forceContextRestore = function () {
  239. var extension = extensions.get( 'WEBGL_lose_context' );
  240. if ( extension ) extension.restoreContext();
  241. };
  242. this.getPixelRatio = function () {
  243. return _pixelRatio;
  244. };
  245. this.setPixelRatio = function ( value ) {
  246. if ( value === undefined ) return;
  247. _pixelRatio = value;
  248. this.setSize( _width, _height, false );
  249. };
  250. this.getSize = function ( target ) {
  251. if ( target === undefined ) {
  252. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  253. target = new Vector2();
  254. }
  255. return target.set( _width, _height );
  256. };
  257. this.setSize = function ( width, height, updateStyle ) {
  258. if ( vr.isPresenting() ) {
  259. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  260. return;
  261. }
  262. _width = width;
  263. _height = height;
  264. _canvas.width = Math.floor( width * _pixelRatio );
  265. _canvas.height = Math.floor( height * _pixelRatio );
  266. if ( updateStyle !== false ) {
  267. _canvas.style.width = width + 'px';
  268. _canvas.style.height = height + 'px';
  269. }
  270. this.setViewport( 0, 0, width, height );
  271. };
  272. this.getDrawingBufferSize = function ( target ) {
  273. if ( target === undefined ) {
  274. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  275. target = new Vector2();
  276. }
  277. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  278. };
  279. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  280. _width = width;
  281. _height = height;
  282. _pixelRatio = pixelRatio;
  283. _canvas.width = Math.floor( width * pixelRatio );
  284. _canvas.height = Math.floor( height * pixelRatio );
  285. this.setViewport( 0, 0, width, height );
  286. };
  287. this.getCurrentViewport = function ( target ) {
  288. if ( target === undefined ) {
  289. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  290. target = new Vector4();
  291. }
  292. return target.copy( _currentViewport );
  293. };
  294. this.getViewport = function ( target ) {
  295. return target.copy( _viewport );
  296. };
  297. this.setViewport = function ( x, y, width, height ) {
  298. if ( x.isVector4 ) {
  299. _viewport.set( x.x, x.y, x.z, x.w );
  300. } else {
  301. _viewport.set( x, y, width, height );
  302. }
  303. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  304. };
  305. this.getScissor = function ( target ) {
  306. return target.copy( _scissor );
  307. };
  308. this.setScissor = function ( x, y, width, height ) {
  309. if ( x.isVector4 ) {
  310. _scissor.set( x.x, x.y, x.z, x.w );
  311. } else {
  312. _scissor.set( x, y, width, height );
  313. }
  314. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  315. };
  316. this.getScissorTest = function () {
  317. return _scissorTest;
  318. };
  319. this.setScissorTest = function ( boolean ) {
  320. state.setScissorTest( _scissorTest = boolean );
  321. };
  322. // Clearing
  323. this.getClearColor = function () {
  324. return background.getClearColor();
  325. };
  326. this.setClearColor = function () {
  327. background.setClearColor.apply( background, arguments );
  328. };
  329. this.getClearAlpha = function () {
  330. return background.getClearAlpha();
  331. };
  332. this.setClearAlpha = function () {
  333. background.setClearAlpha.apply( background, arguments );
  334. };
  335. this.clear = function ( color, depth, stencil ) {
  336. var bits = 0;
  337. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  338. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  339. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  340. _gl.clear( bits );
  341. };
  342. this.clearColor = function () {
  343. this.clear( true, false, false );
  344. };
  345. this.clearDepth = function () {
  346. this.clear( false, true, false );
  347. };
  348. this.clearStencil = function () {
  349. this.clear( false, false, true );
  350. };
  351. //
  352. this.dispose = function () {
  353. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  354. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  355. renderLists.dispose();
  356. renderStates.dispose();
  357. properties.dispose();
  358. objects.dispose();
  359. vr.dispose();
  360. animation.stop();
  361. };
  362. // Events
  363. function onContextLost( event ) {
  364. event.preventDefault();
  365. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  366. _isContextLost = true;
  367. }
  368. function onContextRestore( /* event */ ) {
  369. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  370. _isContextLost = false;
  371. initGLContext();
  372. }
  373. function onMaterialDispose( event ) {
  374. var material = event.target;
  375. material.removeEventListener( 'dispose', onMaterialDispose );
  376. deallocateMaterial( material );
  377. }
  378. // Buffer deallocation
  379. function deallocateMaterial( material ) {
  380. releaseMaterialProgramReference( material );
  381. properties.remove( material );
  382. }
  383. function releaseMaterialProgramReference( material ) {
  384. var programInfo = properties.get( material ).program;
  385. material.program = undefined;
  386. if ( programInfo !== undefined ) {
  387. programCache.releaseProgram( programInfo );
  388. }
  389. }
  390. // Buffer rendering
  391. function renderObjectImmediate( object, program ) {
  392. object.render( function ( object ) {
  393. _this.renderBufferImmediate( object, program );
  394. } );
  395. }
  396. this.renderBufferImmediate = function ( object, program ) {
  397. state.initAttributes();
  398. var buffers = properties.get( object );
  399. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  400. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  401. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  402. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  403. var programAttributes = program.getAttributes();
  404. if ( object.hasPositions ) {
  405. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  406. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  407. state.enableAttribute( programAttributes.position );
  408. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  409. }
  410. if ( object.hasNormals ) {
  411. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  412. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  413. state.enableAttribute( programAttributes.normal );
  414. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  415. }
  416. if ( object.hasUvs ) {
  417. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  418. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  419. state.enableAttribute( programAttributes.uv );
  420. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  421. }
  422. if ( object.hasColors ) {
  423. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  424. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  425. state.enableAttribute( programAttributes.color );
  426. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  427. }
  428. state.disableUnusedAttributes();
  429. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  430. object.count = 0;
  431. };
  432. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  433. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  434. state.setMaterial( material, frontFaceCW );
  435. var program = setProgram( camera, fog, material, object );
  436. var updateBuffers = false;
  437. if ( _currentGeometryProgram.geometry !== geometry.id ||
  438. _currentGeometryProgram.program !== program.id ||
  439. _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
  440. _currentGeometryProgram.geometry = geometry.id;
  441. _currentGeometryProgram.program = program.id;
  442. _currentGeometryProgram.wireframe = material.wireframe === true;
  443. updateBuffers = true;
  444. }
  445. if ( object.morphTargetInfluences ) {
  446. morphtargets.update( object, geometry, material, program );
  447. updateBuffers = true;
  448. }
  449. //
  450. var index = geometry.index;
  451. var position = geometry.attributes.position;
  452. var rangeFactor = 1;
  453. if ( material.wireframe === true ) {
  454. index = geometries.getWireframeAttribute( geometry );
  455. rangeFactor = 2;
  456. }
  457. var attribute;
  458. var renderer = bufferRenderer;
  459. if ( index !== null ) {
  460. attribute = attributes.get( index );
  461. renderer = indexedBufferRenderer;
  462. renderer.setIndex( attribute );
  463. }
  464. if ( updateBuffers ) {
  465. setupVertexAttributes( material, program, geometry );
  466. if ( index !== null ) {
  467. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  468. }
  469. }
  470. //
  471. var dataCount = Infinity;
  472. if ( index !== null ) {
  473. dataCount = index.count;
  474. } else if ( position !== undefined ) {
  475. dataCount = position.count;
  476. }
  477. var rangeStart = geometry.drawRange.start * rangeFactor;
  478. var rangeCount = geometry.drawRange.count * rangeFactor;
  479. var groupStart = group !== null ? group.start * rangeFactor : 0;
  480. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  481. var drawStart = Math.max( rangeStart, groupStart );
  482. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  483. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  484. if ( drawCount === 0 ) return;
  485. //
  486. if ( object.isMesh ) {
  487. if ( material.wireframe === true ) {
  488. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  489. renderer.setMode( _gl.LINES );
  490. } else {
  491. switch ( object.drawMode ) {
  492. case TrianglesDrawMode:
  493. renderer.setMode( _gl.TRIANGLES );
  494. break;
  495. case TriangleStripDrawMode:
  496. renderer.setMode( _gl.TRIANGLE_STRIP );
  497. break;
  498. case TriangleFanDrawMode:
  499. renderer.setMode( _gl.TRIANGLE_FAN );
  500. break;
  501. }
  502. }
  503. } else if ( object.isLine ) {
  504. var lineWidth = material.linewidth;
  505. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  506. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  507. if ( object.isLineSegments ) {
  508. renderer.setMode( _gl.LINES );
  509. } else if ( object.isLineLoop ) {
  510. renderer.setMode( _gl.LINE_LOOP );
  511. } else {
  512. renderer.setMode( _gl.LINE_STRIP );
  513. }
  514. } else if ( object.isPoints ) {
  515. renderer.setMode( _gl.POINTS );
  516. } else if ( object.isSprite ) {
  517. renderer.setMode( _gl.TRIANGLES );
  518. }
  519. if ( geometry && geometry.isInstancedBufferGeometry ) {
  520. if ( geometry.maxInstancedCount > 0 ) {
  521. renderer.renderInstances( geometry, drawStart, drawCount );
  522. }
  523. } else {
  524. renderer.render( drawStart, drawCount );
  525. }
  526. };
  527. function setupVertexAttributes( material, program, geometry ) {
  528. if ( geometry && geometry.isInstancedBufferGeometry && ! capabilities.isWebGL2 ) {
  529. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  530. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  531. return;
  532. }
  533. }
  534. state.initAttributes();
  535. var geometryAttributes = geometry.attributes;
  536. var programAttributes = program.getAttributes();
  537. var materialDefaultAttributeValues = material.defaultAttributeValues;
  538. for ( var name in programAttributes ) {
  539. var programAttribute = programAttributes[ name ];
  540. if ( programAttribute >= 0 ) {
  541. var geometryAttribute = geometryAttributes[ name ];
  542. if ( geometryAttribute !== undefined ) {
  543. var normalized = geometryAttribute.normalized;
  544. var size = geometryAttribute.itemSize;
  545. var attribute = attributes.get( geometryAttribute );
  546. // TODO Attribute may not be available on context restore
  547. if ( attribute === undefined ) continue;
  548. var buffer = attribute.buffer;
  549. var type = attribute.type;
  550. var bytesPerElement = attribute.bytesPerElement;
  551. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  552. var data = geometryAttribute.data;
  553. var stride = data.stride;
  554. var offset = geometryAttribute.offset;
  555. if ( data && data.isInstancedInterleavedBuffer ) {
  556. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  557. if ( geometry.maxInstancedCount === undefined ) {
  558. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  559. }
  560. } else {
  561. state.enableAttribute( programAttribute );
  562. }
  563. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  564. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  565. } else {
  566. if ( geometryAttribute.isInstancedBufferAttribute ) {
  567. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  568. if ( geometry.maxInstancedCount === undefined ) {
  569. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  570. }
  571. } else {
  572. state.enableAttribute( programAttribute );
  573. }
  574. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  575. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  576. }
  577. } else if ( materialDefaultAttributeValues !== undefined ) {
  578. var value = materialDefaultAttributeValues[ name ];
  579. if ( value !== undefined ) {
  580. switch ( value.length ) {
  581. case 2:
  582. _gl.vertexAttrib2fv( programAttribute, value );
  583. break;
  584. case 3:
  585. _gl.vertexAttrib3fv( programAttribute, value );
  586. break;
  587. case 4:
  588. _gl.vertexAttrib4fv( programAttribute, value );
  589. break;
  590. default:
  591. _gl.vertexAttrib1fv( programAttribute, value );
  592. }
  593. }
  594. }
  595. }
  596. }
  597. state.disableUnusedAttributes();
  598. }
  599. // Compile
  600. this.compile = function ( scene, camera ) {
  601. currentRenderState = renderStates.get( scene, camera );
  602. currentRenderState.init();
  603. scene.traverse( function ( object ) {
  604. if ( object.isLight ) {
  605. currentRenderState.pushLight( object );
  606. if ( object.castShadow ) {
  607. currentRenderState.pushShadow( object );
  608. }
  609. }
  610. } );
  611. currentRenderState.setupLights( camera );
  612. scene.traverse( function ( object ) {
  613. if ( object.material ) {
  614. if ( Array.isArray( object.material ) ) {
  615. for ( var i = 0; i < object.material.length; i ++ ) {
  616. initMaterial( object.material[ i ], scene.fog, object );
  617. }
  618. } else {
  619. initMaterial( object.material, scene.fog, object );
  620. }
  621. }
  622. } );
  623. };
  624. // Animation Loop
  625. var onAnimationFrameCallback = null;
  626. function onAnimationFrame( time ) {
  627. if ( vr.isPresenting() ) return;
  628. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  629. }
  630. var animation = new WebGLAnimation();
  631. animation.setAnimationLoop( onAnimationFrame );
  632. if ( typeof window !== 'undefined' ) animation.setContext( window );
  633. this.setAnimationLoop = function ( callback ) {
  634. onAnimationFrameCallback = callback;
  635. vr.setAnimationLoop( callback );
  636. animation.start();
  637. };
  638. // Rendering
  639. this.render = function ( scene, camera ) {
  640. var renderTarget, forceClear;
  641. if ( arguments[ 2 ] !== undefined ) {
  642. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  643. renderTarget = arguments[ 2 ];
  644. }
  645. if ( arguments[ 3 ] !== undefined ) {
  646. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  647. forceClear = arguments[ 3 ];
  648. }
  649. if ( ! ( camera && camera.isCamera ) ) {
  650. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  651. return;
  652. }
  653. if ( _isContextLost ) return;
  654. // reset caching for this frame
  655. _currentGeometryProgram.geometry = null;
  656. _currentGeometryProgram.program = null;
  657. _currentGeometryProgram.wireframe = false;
  658. _currentMaterialId = - 1;
  659. _currentCamera = null;
  660. // update scene graph
  661. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  662. // update camera matrices and frustum
  663. if ( camera.parent === null ) camera.updateMatrixWorld();
  664. if ( vr.enabled ) {
  665. camera = vr.getCamera( camera );
  666. }
  667. //
  668. currentRenderState = renderStates.get( scene, camera );
  669. currentRenderState.init();
  670. scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  671. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  672. _frustum.setFromMatrix( _projScreenMatrix );
  673. _localClippingEnabled = this.localClippingEnabled;
  674. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  675. currentRenderList = renderLists.get( scene, camera );
  676. currentRenderList.init();
  677. projectObject( scene, camera, 0, _this.sortObjects );
  678. if ( _this.sortObjects === true ) {
  679. currentRenderList.sort();
  680. }
  681. //
  682. if ( _clippingEnabled ) _clipping.beginShadows();
  683. var shadowsArray = currentRenderState.state.shadowsArray;
  684. shadowMap.render( shadowsArray, scene, camera );
  685. currentRenderState.setupLights( camera );
  686. if ( _clippingEnabled ) _clipping.endShadows();
  687. //
  688. if ( this.info.autoReset ) this.info.reset();
  689. if ( renderTarget !== undefined ) {
  690. this.setRenderTarget( renderTarget );
  691. }
  692. if ( capabilities.multiview ) {
  693. multiview.attachRenderTarget( camera );
  694. }
  695. //
  696. background.render( currentRenderList, scene, camera, forceClear );
  697. // render scene
  698. var opaqueObjects = currentRenderList.opaque;
  699. var transparentObjects = currentRenderList.transparent;
  700. if ( scene.overrideMaterial ) {
  701. var overrideMaterial = scene.overrideMaterial;
  702. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  703. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  704. } else {
  705. // opaque pass (front-to-back order)
  706. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  707. // transparent pass (back-to-front order)
  708. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  709. }
  710. //
  711. scene.onAfterRender( _this, scene, camera );
  712. //
  713. if ( _currentRenderTarget !== null ) {
  714. // Generate mipmap if we're using any kind of mipmap filtering
  715. textures.updateRenderTargetMipmap( _currentRenderTarget );
  716. // resolve multisample renderbuffers to a single-sample texture if necessary
  717. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  718. }
  719. // Ensure depth buffer writing is enabled so it can be cleared on next render
  720. state.buffers.depth.setTest( true );
  721. state.buffers.depth.setMask( true );
  722. state.buffers.color.setMask( true );
  723. state.setPolygonOffset( false );
  724. if ( capabilities.multiview ) {
  725. multiview.detachRenderTarget( camera );
  726. }
  727. if ( vr.enabled ) {
  728. vr.submitFrame();
  729. }
  730. // _gl.finish();
  731. currentRenderList = null;
  732. currentRenderState = null;
  733. };
  734. function projectObject( object, camera, groupOrder, sortObjects ) {
  735. if ( object.visible === false ) return;
  736. var visible = object.layers.test( camera.layers );
  737. if ( visible ) {
  738. if ( object.isGroup ) {
  739. groupOrder = object.renderOrder;
  740. } else if ( object.isLOD ) {
  741. if ( object.autoUpdate === true ) object.update( camera );
  742. } else if ( object.isLight ) {
  743. currentRenderState.pushLight( object );
  744. if ( object.castShadow ) {
  745. currentRenderState.pushShadow( object );
  746. }
  747. } else if ( object.isSprite ) {
  748. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  749. if ( sortObjects ) {
  750. _vector3.setFromMatrixPosition( object.matrixWorld )
  751. .applyMatrix4( _projScreenMatrix );
  752. }
  753. var geometry = objects.update( object );
  754. var material = object.material;
  755. if ( material.visible ) {
  756. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  757. }
  758. }
  759. } else if ( object.isImmediateRenderObject ) {
  760. if ( sortObjects ) {
  761. _vector3.setFromMatrixPosition( object.matrixWorld )
  762. .applyMatrix4( _projScreenMatrix );
  763. }
  764. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  765. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  766. if ( object.isSkinnedMesh ) {
  767. object.skeleton.update();
  768. }
  769. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  770. if ( sortObjects ) {
  771. _vector3.setFromMatrixPosition( object.matrixWorld )
  772. .applyMatrix4( _projScreenMatrix );
  773. }
  774. var geometry = objects.update( object );
  775. var material = object.material;
  776. if ( Array.isArray( material ) ) {
  777. var groups = geometry.groups;
  778. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  779. var group = groups[ i ];
  780. var groupMaterial = material[ group.materialIndex ];
  781. if ( groupMaterial && groupMaterial.visible ) {
  782. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  783. }
  784. }
  785. } else if ( material.visible ) {
  786. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  787. }
  788. }
  789. }
  790. }
  791. var children = object.children;
  792. for ( var i = 0, l = children.length; i < l; i ++ ) {
  793. projectObject( children[ i ], camera, groupOrder, sortObjects );
  794. }
  795. }
  796. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  797. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  798. var renderItem = renderList[ i ];
  799. var object = renderItem.object;
  800. var geometry = renderItem.geometry;
  801. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  802. var group = renderItem.group;
  803. if ( camera.isArrayCamera ) {
  804. _currentArrayCamera = camera;
  805. if ( capabilities.multiview ) {
  806. renderObject( object, scene, camera, geometry, material, group );
  807. } else {
  808. var cameras = camera.cameras;
  809. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  810. var camera2 = cameras[ j ];
  811. if ( object.layers.test( camera2.layers ) ) {
  812. state.viewport( _currentViewport.copy( camera2.viewport ) );
  813. currentRenderState.setupLights( camera2 );
  814. renderObject( object, scene, camera2, geometry, material, group );
  815. }
  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 };
粤ICP备19079148号