WebGLRenderer.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776
  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 === false ) {
  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, 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( _gl, geometries, attributes, 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 && 'isSessionSupported' 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( object, geometry, material, program );
  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 ( object.isInstancedMesh ) {
  520. renderer.renderInstances( geometry, drawStart, drawCount, object.count );
  521. } else if ( geometry.isInstancedBufferGeometry ) {
  522. renderer.renderInstances( geometry, drawStart, drawCount, geometry.maxInstancedCount );
  523. } else {
  524. renderer.render( drawStart, drawCount );
  525. }
  526. };
  527. function setupVertexAttributes( object, geometry, material, program ) {
  528. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  529. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  530. }
  531. state.initAttributes();
  532. var geometryAttributes = geometry.attributes;
  533. var programAttributes = program.getAttributes();
  534. var materialDefaultAttributeValues = material.defaultAttributeValues;
  535. for ( var name in programAttributes ) {
  536. var programAttribute = programAttributes[ name ];
  537. if ( programAttribute >= 0 ) {
  538. var geometryAttribute = geometryAttributes[ name ];
  539. if ( geometryAttribute !== undefined ) {
  540. var normalized = geometryAttribute.normalized;
  541. var size = geometryAttribute.itemSize;
  542. var attribute = attributes.get( geometryAttribute );
  543. // TODO Attribute may not be available on context restore
  544. if ( attribute === undefined ) continue;
  545. var buffer = attribute.buffer;
  546. var type = attribute.type;
  547. var bytesPerElement = attribute.bytesPerElement;
  548. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  549. var data = geometryAttribute.data;
  550. var stride = data.stride;
  551. var offset = geometryAttribute.offset;
  552. if ( data && data.isInstancedInterleavedBuffer ) {
  553. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  554. if ( geometry.maxInstancedCount === undefined ) {
  555. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  556. }
  557. } else {
  558. state.enableAttribute( programAttribute );
  559. }
  560. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  561. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  562. } else {
  563. if ( geometryAttribute.isInstancedBufferAttribute ) {
  564. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  565. if ( geometry.maxInstancedCount === undefined ) {
  566. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  567. }
  568. } else {
  569. state.enableAttribute( programAttribute );
  570. }
  571. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  572. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  573. }
  574. } else if ( name === 'instanceMatrix' ) {
  575. var attribute = attributes.get( object.instanceMatrix );
  576. // TODO Attribute may not be available on context restore
  577. if ( attribute === undefined ) continue;
  578. var buffer = attribute.buffer;
  579. var type = attribute.type;
  580. state.enableAttributeAndDivisor( programAttribute + 0, 1 );
  581. state.enableAttributeAndDivisor( programAttribute + 1, 1 );
  582. state.enableAttributeAndDivisor( programAttribute + 2, 1 );
  583. state.enableAttributeAndDivisor( programAttribute + 3, 1 );
  584. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  585. _gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  586. _gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  587. _gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  588. _gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  589. } else if ( materialDefaultAttributeValues !== undefined ) {
  590. var value = materialDefaultAttributeValues[ name ];
  591. if ( value !== undefined ) {
  592. switch ( value.length ) {
  593. case 2:
  594. _gl.vertexAttrib2fv( programAttribute, value );
  595. break;
  596. case 3:
  597. _gl.vertexAttrib3fv( programAttribute, value );
  598. break;
  599. case 4:
  600. _gl.vertexAttrib4fv( programAttribute, value );
  601. break;
  602. default:
  603. _gl.vertexAttrib1fv( programAttribute, value );
  604. }
  605. }
  606. }
  607. }
  608. }
  609. state.disableUnusedAttributes();
  610. }
  611. // Compile
  612. this.compile = function ( scene, camera ) {
  613. currentRenderState = renderStates.get( scene, camera );
  614. currentRenderState.init();
  615. scene.traverse( function ( object ) {
  616. if ( object.isLight ) {
  617. currentRenderState.pushLight( object );
  618. if ( object.castShadow ) {
  619. currentRenderState.pushShadow( object );
  620. }
  621. }
  622. } );
  623. currentRenderState.setupLights( camera );
  624. scene.traverse( function ( object ) {
  625. if ( object.material ) {
  626. if ( Array.isArray( object.material ) ) {
  627. for ( var i = 0; i < object.material.length; i ++ ) {
  628. initMaterial( object.material[ i ], scene.fog, object );
  629. }
  630. } else {
  631. initMaterial( object.material, scene.fog, object );
  632. }
  633. }
  634. } );
  635. };
  636. // Animation Loop
  637. var onAnimationFrameCallback = null;
  638. function onAnimationFrame( time ) {
  639. if ( vr.isPresenting() ) return;
  640. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  641. }
  642. var animation = new WebGLAnimation();
  643. animation.setAnimationLoop( onAnimationFrame );
  644. if ( typeof window !== 'undefined' ) animation.setContext( window );
  645. this.setAnimationLoop = function ( callback ) {
  646. onAnimationFrameCallback = callback;
  647. vr.setAnimationLoop( callback );
  648. animation.start();
  649. };
  650. // Rendering
  651. this.render = function ( scene, camera ) {
  652. var renderTarget, forceClear;
  653. if ( arguments[ 2 ] !== undefined ) {
  654. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  655. renderTarget = arguments[ 2 ];
  656. }
  657. if ( arguments[ 3 ] !== undefined ) {
  658. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  659. forceClear = arguments[ 3 ];
  660. }
  661. if ( ! ( camera && camera.isCamera ) ) {
  662. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  663. return;
  664. }
  665. if ( _isContextLost ) return;
  666. // reset caching for this frame
  667. _currentGeometryProgram.geometry = null;
  668. _currentGeometryProgram.program = null;
  669. _currentGeometryProgram.wireframe = false;
  670. _currentMaterialId = - 1;
  671. _currentCamera = null;
  672. // update scene graph
  673. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  674. // update camera matrices and frustum
  675. if ( camera.parent === null ) camera.updateMatrixWorld();
  676. if ( vr.enabled ) {
  677. camera = vr.getCamera( camera );
  678. }
  679. //
  680. currentRenderState = renderStates.get( scene, camera );
  681. currentRenderState.init();
  682. scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  683. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  684. _frustum.setFromMatrix( _projScreenMatrix );
  685. _localClippingEnabled = this.localClippingEnabled;
  686. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  687. currentRenderList = renderLists.get( scene, camera );
  688. currentRenderList.init();
  689. projectObject( scene, camera, 0, _this.sortObjects );
  690. if ( _this.sortObjects === true ) {
  691. currentRenderList.sort();
  692. }
  693. //
  694. if ( _clippingEnabled ) _clipping.beginShadows();
  695. var shadowsArray = currentRenderState.state.shadowsArray;
  696. shadowMap.render( shadowsArray, scene, camera );
  697. currentRenderState.setupLights( camera );
  698. if ( _clippingEnabled ) _clipping.endShadows();
  699. //
  700. if ( this.info.autoReset ) this.info.reset();
  701. if ( renderTarget !== undefined ) {
  702. this.setRenderTarget( renderTarget );
  703. }
  704. if ( vr.enabled && multiview.isAvailable() ) {
  705. multiview.attachCamera( camera );
  706. }
  707. //
  708. background.render( currentRenderList, scene, camera, forceClear );
  709. // render scene
  710. var opaqueObjects = currentRenderList.opaque;
  711. var transparentObjects = currentRenderList.transparent;
  712. if ( scene.overrideMaterial ) {
  713. var overrideMaterial = scene.overrideMaterial;
  714. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  715. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  716. } else {
  717. // opaque pass (front-to-back order)
  718. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  719. // transparent pass (back-to-front order)
  720. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  721. }
  722. //
  723. scene.onAfterRender( _this, scene, camera );
  724. //
  725. if ( _currentRenderTarget !== null ) {
  726. // Generate mipmap if we're using any kind of mipmap filtering
  727. textures.updateRenderTargetMipmap( _currentRenderTarget );
  728. // resolve multisample renderbuffers to a single-sample texture if necessary
  729. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  730. }
  731. // Ensure depth buffer writing is enabled so it can be cleared on next render
  732. state.buffers.depth.setTest( true );
  733. state.buffers.depth.setMask( true );
  734. state.buffers.color.setMask( true );
  735. state.setPolygonOffset( false );
  736. if ( vr.enabled ) {
  737. if ( multiview.isAvailable() ) {
  738. multiview.detachCamera( camera );
  739. }
  740. vr.submitFrame();
  741. }
  742. // _gl.finish();
  743. currentRenderList = null;
  744. currentRenderState = null;
  745. };
  746. function projectObject( object, camera, groupOrder, sortObjects ) {
  747. if ( object.visible === false ) return;
  748. var visible = object.layers.test( camera.layers );
  749. if ( visible ) {
  750. if ( object.isGroup ) {
  751. groupOrder = object.renderOrder;
  752. } else if ( object.isLOD ) {
  753. if ( object.autoUpdate === true ) object.update( camera );
  754. } else if ( object.isLight ) {
  755. currentRenderState.pushLight( object );
  756. if ( object.castShadow ) {
  757. currentRenderState.pushShadow( object );
  758. }
  759. } else if ( object.isSprite ) {
  760. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  761. if ( sortObjects ) {
  762. _vector3.setFromMatrixPosition( object.matrixWorld )
  763. .applyMatrix4( _projScreenMatrix );
  764. }
  765. var geometry = objects.update( object );
  766. var material = object.material;
  767. if ( material.visible ) {
  768. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  769. }
  770. }
  771. } else if ( object.isImmediateRenderObject ) {
  772. if ( sortObjects ) {
  773. _vector3.setFromMatrixPosition( object.matrixWorld )
  774. .applyMatrix4( _projScreenMatrix );
  775. }
  776. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  777. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  778. if ( object.isSkinnedMesh ) {
  779. // update skeleton only once in a frame
  780. if ( object.skeleton.frame !== info.render.frame ) {
  781. object.skeleton.update();
  782. object.skeleton.frame = info.render.frame;
  783. }
  784. }
  785. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  786. if ( sortObjects ) {
  787. _vector3.setFromMatrixPosition( object.matrixWorld )
  788. .applyMatrix4( _projScreenMatrix );
  789. }
  790. var geometry = objects.update( object );
  791. var material = object.material;
  792. if ( Array.isArray( material ) ) {
  793. var groups = geometry.groups;
  794. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  795. var group = groups[ i ];
  796. var groupMaterial = material[ group.materialIndex ];
  797. if ( groupMaterial && groupMaterial.visible ) {
  798. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  799. }
  800. }
  801. } else if ( material.visible ) {
  802. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  803. }
  804. }
  805. }
  806. }
  807. var children = object.children;
  808. for ( var i = 0, l = children.length; i < l; i ++ ) {
  809. projectObject( children[ i ], camera, groupOrder, sortObjects );
  810. }
  811. }
  812. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  813. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  814. var renderItem = renderList[ i ];
  815. var object = renderItem.object;
  816. var geometry = renderItem.geometry;
  817. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  818. var group = renderItem.group;
  819. if ( camera.isArrayCamera ) {
  820. _currentArrayCamera = camera;
  821. if ( vr.enabled && multiview.isAvailable() ) {
  822. renderObject( object, scene, camera, geometry, material, group );
  823. } else {
  824. var cameras = camera.cameras;
  825. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  826. var camera2 = cameras[ j ];
  827. if ( object.layers.test( camera2.layers ) ) {
  828. state.viewport( _currentViewport.copy( camera2.viewport ) );
  829. currentRenderState.setupLights( camera2 );
  830. renderObject( object, scene, camera2, geometry, material, group );
  831. }
  832. }
  833. }
  834. } else {
  835. _currentArrayCamera = null;
  836. renderObject( object, scene, camera, geometry, material, group );
  837. }
  838. }
  839. }
  840. function renderObject( object, scene, camera, geometry, material, group ) {
  841. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  842. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  843. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  844. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  845. if ( object.isImmediateRenderObject ) {
  846. state.setMaterial( material );
  847. var program = setProgram( camera, scene.fog, material, object );
  848. _currentGeometryProgram.geometry = null;
  849. _currentGeometryProgram.program = null;
  850. _currentGeometryProgram.wireframe = false;
  851. renderObjectImmediate( object, program );
  852. } else {
  853. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  854. }
  855. object.onAfterRender( _this, scene, camera, geometry, material, group );
  856. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  857. }
  858. function initMaterial( material, fog, object ) {
  859. var materialProperties = properties.get( material );
  860. var lights = currentRenderState.state.lights;
  861. var shadowsArray = currentRenderState.state.shadowsArray;
  862. var lightsStateVersion = lights.state.version;
  863. var parameters = programCache.getParameters(
  864. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  865. var programCacheKey = programCache.getProgramCacheKey( material, parameters );
  866. var program = materialProperties.program;
  867. var programChange = true;
  868. if ( program === undefined ) {
  869. // new material
  870. material.addEventListener( 'dispose', onMaterialDispose );
  871. } else if ( program.cacheKey !== programCacheKey ) {
  872. // changed glsl or parameters
  873. releaseMaterialProgramReference( material );
  874. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  875. materialProperties.lightsStateVersion = lightsStateVersion;
  876. programChange = false;
  877. } else if ( parameters.shaderID !== undefined ) {
  878. // same glsl and uniform list
  879. return;
  880. } else {
  881. // only rebuild uniform list
  882. programChange = false;
  883. }
  884. if ( programChange ) {
  885. if ( parameters.shaderID ) {
  886. var shader = ShaderLib[ parameters.shaderID ];
  887. materialProperties.shader = {
  888. name: material.type,
  889. uniforms: cloneUniforms( shader.uniforms ),
  890. vertexShader: shader.vertexShader,
  891. fragmentShader: shader.fragmentShader
  892. };
  893. } else {
  894. materialProperties.shader = {
  895. name: material.type,
  896. uniforms: material.uniforms,
  897. vertexShader: material.vertexShader,
  898. fragmentShader: material.fragmentShader
  899. };
  900. }
  901. material.onBeforeCompile( materialProperties.shader, _this );
  902. // Computing cache key again as onBeforeCompile may have changed the shaders
  903. programCacheKey = programCache.getProgramCacheKey( material, parameters );
  904. program = programCache.acquireProgram( material, materialProperties.shader, parameters, programCacheKey );
  905. materialProperties.program = program;
  906. material.program = program;
  907. }
  908. var programAttributes = program.getAttributes();
  909. if ( material.morphTargets ) {
  910. material.numSupportedMorphTargets = 0;
  911. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  912. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  913. material.numSupportedMorphTargets ++;
  914. }
  915. }
  916. }
  917. if ( material.morphNormals ) {
  918. material.numSupportedMorphNormals = 0;
  919. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  920. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  921. material.numSupportedMorphNormals ++;
  922. }
  923. }
  924. }
  925. var uniforms = materialProperties.shader.uniforms;
  926. if ( ! material.isShaderMaterial &&
  927. ! material.isRawShaderMaterial ||
  928. material.clipping === true ) {
  929. materialProperties.numClippingPlanes = _clipping.numPlanes;
  930. materialProperties.numIntersection = _clipping.numIntersection;
  931. uniforms.clippingPlanes = _clipping.uniform;
  932. }
  933. materialProperties.fog = fog;
  934. // store the light setup it was created for
  935. materialProperties.needsLights = materialNeedsLights( material );
  936. materialProperties.lightsStateVersion = lightsStateVersion;
  937. if ( materialProperties.needsLights ) {
  938. // wire up the material to this renderer's lighting state
  939. uniforms.ambientLightColor.value = lights.state.ambient;
  940. uniforms.lightProbe.value = lights.state.probe;
  941. uniforms.directionalLights.value = lights.state.directional;
  942. uniforms.spotLights.value = lights.state.spot;
  943. uniforms.rectAreaLights.value = lights.state.rectArea;
  944. uniforms.pointLights.value = lights.state.point;
  945. uniforms.hemisphereLights.value = lights.state.hemi;
  946. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  947. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  948. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  949. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  950. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  951. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  952. // TODO (abelnation): add area lights shadow info to uniforms
  953. }
  954. var progUniforms = materialProperties.program.getUniforms(),
  955. uniformsList =
  956. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  957. materialProperties.uniformsList = uniformsList;
  958. }
  959. function setProgram( camera, fog, material, object ) {
  960. textures.resetTextureUnits();
  961. var materialProperties = properties.get( material );
  962. var lights = currentRenderState.state.lights;
  963. if ( _clippingEnabled ) {
  964. if ( _localClippingEnabled || camera !== _currentCamera ) {
  965. var useCache =
  966. camera === _currentCamera &&
  967. material.id === _currentMaterialId;
  968. // we might want to call this function with some ClippingGroup
  969. // object instead of the material, once it becomes feasible
  970. // (#8465, #8379)
  971. _clipping.setState(
  972. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  973. camera, materialProperties, useCache );
  974. }
  975. }
  976. if ( material.needsUpdate === false ) {
  977. if ( materialProperties.program === undefined ) {
  978. material.needsUpdate = true;
  979. } else if ( material.fog && materialProperties.fog !== fog ) {
  980. material.needsUpdate = true;
  981. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  982. material.needsUpdate = true;
  983. } else if ( materialProperties.numClippingPlanes !== undefined &&
  984. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  985. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  986. material.needsUpdate = true;
  987. }
  988. }
  989. if ( material.needsUpdate ) {
  990. initMaterial( material, fog, object );
  991. material.needsUpdate = false;
  992. }
  993. var refreshProgram = false;
  994. var refreshMaterial = false;
  995. var refreshLights = false;
  996. var program = materialProperties.program,
  997. p_uniforms = program.getUniforms(),
  998. m_uniforms = materialProperties.shader.uniforms;
  999. if ( state.useProgram( program.program ) ) {
  1000. refreshProgram = true;
  1001. refreshMaterial = true;
  1002. refreshLights = true;
  1003. }
  1004. if ( material.id !== _currentMaterialId ) {
  1005. _currentMaterialId = material.id;
  1006. refreshMaterial = true;
  1007. }
  1008. if ( refreshProgram || _currentCamera !== camera ) {
  1009. if ( program.numMultiviewViews > 0 ) {
  1010. multiview.updateCameraProjectionMatricesUniform( camera, p_uniforms );
  1011. } else {
  1012. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  1013. }
  1014. if ( capabilities.logarithmicDepthBuffer ) {
  1015. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1016. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1017. }
  1018. if ( _currentCamera !== camera ) {
  1019. _currentCamera = camera;
  1020. // lighting uniforms depend on the camera so enforce an update
  1021. // now, in case this material supports lights - or later, when
  1022. // the next material that does gets activated:
  1023. refreshMaterial = true; // set to true on material change
  1024. refreshLights = true; // remains set until update done
  1025. }
  1026. // load material specific uniforms
  1027. // (shader material also gets them for the sake of genericity)
  1028. if ( material.isShaderMaterial ||
  1029. material.isMeshPhongMaterial ||
  1030. material.isMeshStandardMaterial ||
  1031. material.envMap ) {
  1032. var uCamPos = p_uniforms.map.cameraPosition;
  1033. if ( uCamPos !== undefined ) {
  1034. uCamPos.setValue( _gl,
  1035. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1036. }
  1037. }
  1038. if ( material.isMeshPhongMaterial ||
  1039. material.isMeshLambertMaterial ||
  1040. material.isMeshBasicMaterial ||
  1041. material.isMeshStandardMaterial ||
  1042. material.isShaderMaterial ||
  1043. material.skinning ) {
  1044. if ( program.numMultiviewViews > 0 ) {
  1045. multiview.updateCameraViewMatricesUniform( camera, p_uniforms );
  1046. } else {
  1047. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1048. }
  1049. }
  1050. }
  1051. // skinning uniforms must be set even if material didn't change
  1052. // auto-setting of texture unit for bone texture must go before other textures
  1053. // not sure why, but otherwise weird things happen
  1054. if ( material.skinning ) {
  1055. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1056. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1057. var skeleton = object.skeleton;
  1058. if ( skeleton ) {
  1059. var bones = skeleton.bones;
  1060. if ( capabilities.floatVertexTextures ) {
  1061. if ( skeleton.boneTexture === undefined ) {
  1062. // layout (1 matrix = 4 pixels)
  1063. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  1064. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  1065. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  1066. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  1067. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  1068. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  1069. size = _Math.ceilPowerOfTwo( size );
  1070. size = Math.max( size, 4 );
  1071. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  1072. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  1073. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  1074. skeleton.boneMatrices = boneMatrices;
  1075. skeleton.boneTexture = boneTexture;
  1076. skeleton.boneTextureSize = size;
  1077. }
  1078. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  1079. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  1080. } else {
  1081. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  1082. }
  1083. }
  1084. }
  1085. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  1086. materialProperties.receiveShadow = object.receiveShadow;
  1087. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  1088. }
  1089. if ( refreshMaterial ) {
  1090. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  1091. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  1092. if ( materialProperties.needsLights ) {
  1093. // the current material requires lighting info
  1094. // note: all lighting uniforms are always set correctly
  1095. // they simply reference the renderer's state for their
  1096. // values
  1097. //
  1098. // use the current material's .needsUpdate flags to set
  1099. // the GL state when required
  1100. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1101. }
  1102. // refresh uniforms common to several materials
  1103. if ( fog && material.fog ) {
  1104. refreshUniformsFog( m_uniforms, fog );
  1105. }
  1106. if ( material.isMeshBasicMaterial ) {
  1107. refreshUniformsCommon( m_uniforms, material );
  1108. } else if ( material.isMeshLambertMaterial ) {
  1109. refreshUniformsCommon( m_uniforms, material );
  1110. refreshUniformsLambert( m_uniforms, material );
  1111. } else if ( material.isMeshPhongMaterial ) {
  1112. refreshUniformsCommon( m_uniforms, material );
  1113. if ( material.isMeshToonMaterial ) {
  1114. refreshUniformsToon( m_uniforms, material );
  1115. } else {
  1116. refreshUniformsPhong( m_uniforms, material );
  1117. }
  1118. } else if ( material.isMeshStandardMaterial ) {
  1119. refreshUniformsCommon( m_uniforms, material );
  1120. if ( material.isMeshPhysicalMaterial ) {
  1121. refreshUniformsPhysical( m_uniforms, material );
  1122. } else {
  1123. refreshUniformsStandard( m_uniforms, material );
  1124. }
  1125. } else if ( material.isMeshMatcapMaterial ) {
  1126. refreshUniformsCommon( m_uniforms, material );
  1127. refreshUniformsMatcap( m_uniforms, material );
  1128. } else if ( material.isMeshDepthMaterial ) {
  1129. refreshUniformsCommon( m_uniforms, material );
  1130. refreshUniformsDepth( m_uniforms, material );
  1131. } else if ( material.isMeshDistanceMaterial ) {
  1132. refreshUniformsCommon( m_uniforms, material );
  1133. refreshUniformsDistance( m_uniforms, material );
  1134. } else if ( material.isMeshNormalMaterial ) {
  1135. refreshUniformsCommon( m_uniforms, material );
  1136. refreshUniformsNormal( m_uniforms, material );
  1137. } else if ( material.isLineBasicMaterial ) {
  1138. refreshUniformsLine( m_uniforms, material );
  1139. if ( material.isLineDashedMaterial ) {
  1140. refreshUniformsDash( m_uniforms, material );
  1141. }
  1142. } else if ( material.isPointsMaterial ) {
  1143. refreshUniformsPoints( m_uniforms, material );
  1144. } else if ( material.isSpriteMaterial ) {
  1145. refreshUniformsSprites( m_uniforms, material );
  1146. } else if ( material.isShadowMaterial ) {
  1147. m_uniforms.color.value.copy( material.color );
  1148. m_uniforms.opacity.value = material.opacity;
  1149. }
  1150. // RectAreaLight Texture
  1151. // TODO (mrdoob): Find a nicer implementation
  1152. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  1153. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  1154. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  1155. if ( material.isShaderMaterial ) {
  1156. material.uniformsNeedUpdate = false; // #15581
  1157. }
  1158. }
  1159. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  1160. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  1161. material.uniformsNeedUpdate = false;
  1162. }
  1163. if ( material.isSpriteMaterial ) {
  1164. p_uniforms.setValue( _gl, 'center', object.center );
  1165. }
  1166. // common matrices
  1167. if ( program.numMultiviewViews > 0 ) {
  1168. multiview.updateObjectMatricesUniforms( object, camera, p_uniforms );
  1169. } else {
  1170. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1171. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1172. }
  1173. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1174. return program;
  1175. }
  1176. // Uniforms (refresh uniforms objects)
  1177. function refreshUniformsCommon( uniforms, material ) {
  1178. uniforms.opacity.value = material.opacity;
  1179. if ( material.color ) {
  1180. uniforms.diffuse.value.copy( material.color );
  1181. }
  1182. if ( material.emissive ) {
  1183. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1184. }
  1185. if ( material.map ) {
  1186. uniforms.map.value = material.map;
  1187. }
  1188. if ( material.alphaMap ) {
  1189. uniforms.alphaMap.value = material.alphaMap;
  1190. }
  1191. if ( material.specularMap ) {
  1192. uniforms.specularMap.value = material.specularMap;
  1193. }
  1194. if ( material.envMap ) {
  1195. uniforms.envMap.value = material.envMap;
  1196. // don't flip CubeTexture envMaps, flip everything else:
  1197. // WebGLRenderTargetCube will be flipped for backwards compatibility
  1198. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  1199. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  1200. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  1201. uniforms.reflectivity.value = material.reflectivity;
  1202. uniforms.refractionRatio.value = material.refractionRatio;
  1203. uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel;
  1204. }
  1205. if ( material.lightMap ) {
  1206. uniforms.lightMap.value = material.lightMap;
  1207. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1208. }
  1209. if ( material.aoMap ) {
  1210. uniforms.aoMap.value = material.aoMap;
  1211. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1212. }
  1213. // uv repeat and offset setting priorities
  1214. // 1. color map
  1215. // 2. specular map
  1216. // 3. normal map
  1217. // 4. bump map
  1218. // 5. alpha map
  1219. // 6. emissive map
  1220. var uvScaleMap;
  1221. if ( material.map ) {
  1222. uvScaleMap = material.map;
  1223. } else if ( material.specularMap ) {
  1224. uvScaleMap = material.specularMap;
  1225. } else if ( material.displacementMap ) {
  1226. uvScaleMap = material.displacementMap;
  1227. } else if ( material.normalMap ) {
  1228. uvScaleMap = material.normalMap;
  1229. } else if ( material.bumpMap ) {
  1230. uvScaleMap = material.bumpMap;
  1231. } else if ( material.roughnessMap ) {
  1232. uvScaleMap = material.roughnessMap;
  1233. } else if ( material.metalnessMap ) {
  1234. uvScaleMap = material.metalnessMap;
  1235. } else if ( material.alphaMap ) {
  1236. uvScaleMap = material.alphaMap;
  1237. } else if ( material.emissiveMap ) {
  1238. uvScaleMap = material.emissiveMap;
  1239. }
  1240. if ( uvScaleMap !== undefined ) {
  1241. // backwards compatibility
  1242. if ( uvScaleMap.isWebGLRenderTarget ) {
  1243. uvScaleMap = uvScaleMap.texture;
  1244. }
  1245. if ( uvScaleMap.matrixAutoUpdate === true ) {
  1246. uvScaleMap.updateMatrix();
  1247. }
  1248. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  1249. }
  1250. }
  1251. function refreshUniformsLine( uniforms, material ) {
  1252. uniforms.diffuse.value.copy( material.color );
  1253. uniforms.opacity.value = material.opacity;
  1254. }
  1255. function refreshUniformsDash( uniforms, material ) {
  1256. uniforms.dashSize.value = material.dashSize;
  1257. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1258. uniforms.scale.value = material.scale;
  1259. }
  1260. function refreshUniformsPoints( uniforms, material ) {
  1261. uniforms.diffuse.value.copy( material.color );
  1262. uniforms.opacity.value = material.opacity;
  1263. uniforms.size.value = material.size * _pixelRatio;
  1264. uniforms.scale.value = _height * 0.5;
  1265. if ( material.map ) {
  1266. uniforms.map.value = material.map;
  1267. }
  1268. if ( material.alphaMap ) {
  1269. uniforms.alphaMap.value = material.alphaMap;
  1270. }
  1271. // uv repeat and offset setting priorities
  1272. // 1. color map
  1273. // 2. alpha map
  1274. var uvScaleMap;
  1275. if ( material.map ) {
  1276. uvScaleMap = material.map;
  1277. } else if ( material.alphaMap ) {
  1278. uvScaleMap = material.alphaMap;
  1279. }
  1280. if ( uvScaleMap !== undefined ) {
  1281. if ( uvScaleMap.matrixAutoUpdate === true ) {
  1282. uvScaleMap.updateMatrix();
  1283. }
  1284. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  1285. }
  1286. }
  1287. function refreshUniformsSprites( uniforms, material ) {
  1288. uniforms.diffuse.value.copy( material.color );
  1289. uniforms.opacity.value = material.opacity;
  1290. uniforms.rotation.value = material.rotation;
  1291. if ( material.map ) {
  1292. uniforms.map.value = material.map;
  1293. }
  1294. if ( material.alphaMap ) {
  1295. uniforms.alphaMap.value = material.alphaMap;
  1296. }
  1297. // uv repeat and offset setting priorities
  1298. // 1. color map
  1299. // 2. alpha map
  1300. var uvScaleMap;
  1301. if ( material.map ) {
  1302. uvScaleMap = material.map;
  1303. } else if ( material.alphaMap ) {
  1304. uvScaleMap = material.alphaMap;
  1305. }
  1306. if ( uvScaleMap !== undefined ) {
  1307. if ( uvScaleMap.matrixAutoUpdate === true ) {
  1308. uvScaleMap.updateMatrix();
  1309. }
  1310. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  1311. }
  1312. }
  1313. function refreshUniformsFog( uniforms, fog ) {
  1314. uniforms.fogColor.value.copy( fog.color );
  1315. if ( fog.isFog ) {
  1316. uniforms.fogNear.value = fog.near;
  1317. uniforms.fogFar.value = fog.far;
  1318. } else if ( fog.isFogExp2 ) {
  1319. uniforms.fogDensity.value = fog.density;
  1320. }
  1321. }
  1322. function refreshUniformsLambert( uniforms, material ) {
  1323. if ( material.emissiveMap ) {
  1324. uniforms.emissiveMap.value = material.emissiveMap;
  1325. }
  1326. }
  1327. function refreshUniformsPhong( uniforms, material ) {
  1328. uniforms.specular.value.copy( material.specular );
  1329. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1330. if ( material.emissiveMap ) {
  1331. uniforms.emissiveMap.value = material.emissiveMap;
  1332. }
  1333. if ( material.bumpMap ) {
  1334. uniforms.bumpMap.value = material.bumpMap;
  1335. uniforms.bumpScale.value = material.bumpScale;
  1336. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1337. }
  1338. if ( material.normalMap ) {
  1339. uniforms.normalMap.value = material.normalMap;
  1340. uniforms.normalScale.value.copy( material.normalScale );
  1341. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1342. }
  1343. if ( material.displacementMap ) {
  1344. uniforms.displacementMap.value = material.displacementMap;
  1345. uniforms.displacementScale.value = material.displacementScale;
  1346. uniforms.displacementBias.value = material.displacementBias;
  1347. }
  1348. }
  1349. function refreshUniformsToon( uniforms, material ) {
  1350. refreshUniformsPhong( uniforms, material );
  1351. if ( material.gradientMap ) {
  1352. uniforms.gradientMap.value = material.gradientMap;
  1353. }
  1354. }
  1355. function refreshUniformsStandard( uniforms, material ) {
  1356. uniforms.roughness.value = material.roughness;
  1357. uniforms.metalness.value = material.metalness;
  1358. if ( material.roughnessMap ) {
  1359. uniforms.roughnessMap.value = material.roughnessMap;
  1360. }
  1361. if ( material.metalnessMap ) {
  1362. uniforms.metalnessMap.value = material.metalnessMap;
  1363. }
  1364. if ( material.emissiveMap ) {
  1365. uniforms.emissiveMap.value = material.emissiveMap;
  1366. }
  1367. if ( material.bumpMap ) {
  1368. uniforms.bumpMap.value = material.bumpMap;
  1369. uniforms.bumpScale.value = material.bumpScale;
  1370. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1371. }
  1372. if ( material.normalMap ) {
  1373. uniforms.normalMap.value = material.normalMap;
  1374. uniforms.normalScale.value.copy( material.normalScale );
  1375. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1376. }
  1377. if ( material.displacementMap ) {
  1378. uniforms.displacementMap.value = material.displacementMap;
  1379. uniforms.displacementScale.value = material.displacementScale;
  1380. uniforms.displacementBias.value = material.displacementBias;
  1381. }
  1382. if ( material.envMap ) {
  1383. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1384. uniforms.envMapIntensity.value = material.envMapIntensity;
  1385. }
  1386. }
  1387. function refreshUniformsPhysical( uniforms, material ) {
  1388. refreshUniformsStandard( uniforms, material );
  1389. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  1390. uniforms.clearcoat.value = material.clearcoat;
  1391. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  1392. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  1393. if ( material.clearcoatNormalMap ) {
  1394. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  1395. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  1396. if ( material.side === BackSide ) {
  1397. uniforms.clearcoatNormalScale.value.negate();
  1398. }
  1399. }
  1400. uniforms.transparency.value = material.transparency;
  1401. }
  1402. function refreshUniformsMatcap( uniforms, material ) {
  1403. if ( material.matcap ) {
  1404. uniforms.matcap.value = material.matcap;
  1405. }
  1406. if ( material.bumpMap ) {
  1407. uniforms.bumpMap.value = material.bumpMap;
  1408. uniforms.bumpScale.value = material.bumpScale;
  1409. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1410. }
  1411. if ( material.normalMap ) {
  1412. uniforms.normalMap.value = material.normalMap;
  1413. uniforms.normalScale.value.copy( material.normalScale );
  1414. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1415. }
  1416. if ( material.displacementMap ) {
  1417. uniforms.displacementMap.value = material.displacementMap;
  1418. uniforms.displacementScale.value = material.displacementScale;
  1419. uniforms.displacementBias.value = material.displacementBias;
  1420. }
  1421. }
  1422. function refreshUniformsDepth( uniforms, material ) {
  1423. if ( material.displacementMap ) {
  1424. uniforms.displacementMap.value = material.displacementMap;
  1425. uniforms.displacementScale.value = material.displacementScale;
  1426. uniforms.displacementBias.value = material.displacementBias;
  1427. }
  1428. }
  1429. function refreshUniformsDistance( uniforms, material ) {
  1430. if ( material.displacementMap ) {
  1431. uniforms.displacementMap.value = material.displacementMap;
  1432. uniforms.displacementScale.value = material.displacementScale;
  1433. uniforms.displacementBias.value = material.displacementBias;
  1434. }
  1435. uniforms.referencePosition.value.copy( material.referencePosition );
  1436. uniforms.nearDistance.value = material.nearDistance;
  1437. uniforms.farDistance.value = material.farDistance;
  1438. }
  1439. function refreshUniformsNormal( uniforms, material ) {
  1440. if ( material.bumpMap ) {
  1441. uniforms.bumpMap.value = material.bumpMap;
  1442. uniforms.bumpScale.value = material.bumpScale;
  1443. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1444. }
  1445. if ( material.normalMap ) {
  1446. uniforms.normalMap.value = material.normalMap;
  1447. uniforms.normalScale.value.copy( material.normalScale );
  1448. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1449. }
  1450. if ( material.displacementMap ) {
  1451. uniforms.displacementMap.value = material.displacementMap;
  1452. uniforms.displacementScale.value = material.displacementScale;
  1453. uniforms.displacementBias.value = material.displacementBias;
  1454. }
  1455. }
  1456. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1457. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1458. uniforms.ambientLightColor.needsUpdate = value;
  1459. uniforms.lightProbe.needsUpdate = value;
  1460. uniforms.directionalLights.needsUpdate = value;
  1461. uniforms.pointLights.needsUpdate = value;
  1462. uniforms.spotLights.needsUpdate = value;
  1463. uniforms.rectAreaLights.needsUpdate = value;
  1464. uniforms.hemisphereLights.needsUpdate = value;
  1465. }
  1466. function materialNeedsLights( material ) {
  1467. return material.isMeshLambertMaterial || material.isMeshPhongMaterial ||
  1468. material.isMeshStandardMaterial || material.isShadowMaterial ||
  1469. ( material.isShaderMaterial && material.lights === true );
  1470. }
  1471. //
  1472. this.setFramebuffer = function ( value ) {
  1473. if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( _gl.FRAMEBUFFER, value );
  1474. _framebuffer = value;
  1475. };
  1476. this.getActiveCubeFace = function () {
  1477. return _currentActiveCubeFace;
  1478. };
  1479. this.getActiveMipmapLevel = function () {
  1480. return _currentActiveMipmapLevel;
  1481. };
  1482. this.getRenderTarget = function () {
  1483. return _currentRenderTarget;
  1484. };
  1485. this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) {
  1486. _currentRenderTarget = renderTarget;
  1487. _currentActiveCubeFace = activeCubeFace;
  1488. _currentActiveMipmapLevel = activeMipmapLevel;
  1489. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1490. textures.setupRenderTarget( renderTarget );
  1491. }
  1492. var framebuffer = _framebuffer;
  1493. var isCube = false;
  1494. if ( renderTarget ) {
  1495. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1496. if ( renderTarget.isWebGLRenderTargetCube ) {
  1497. framebuffer = __webglFramebuffer[ activeCubeFace || 0 ];
  1498. isCube = true;
  1499. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  1500. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  1501. } else {
  1502. framebuffer = __webglFramebuffer;
  1503. }
  1504. _currentViewport.copy( renderTarget.viewport );
  1505. _currentScissor.copy( renderTarget.scissor );
  1506. _currentScissorTest = renderTarget.scissorTest;
  1507. } else {
  1508. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  1509. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  1510. _currentScissorTest = _scissorTest;
  1511. }
  1512. if ( _currentFramebuffer !== framebuffer ) {
  1513. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1514. _currentFramebuffer = framebuffer;
  1515. }
  1516. state.viewport( _currentViewport );
  1517. state.scissor( _currentScissor );
  1518. state.setScissorTest( _currentScissorTest );
  1519. if ( isCube ) {
  1520. var textureProperties = properties.get( renderTarget.texture );
  1521. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 );
  1522. }
  1523. };
  1524. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1525. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1526. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1527. return;
  1528. }
  1529. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1530. if ( renderTarget.isWebGLRenderTargetCube && activeCubeFaceIndex !== undefined ) {
  1531. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1532. }
  1533. if ( framebuffer ) {
  1534. var restore = false;
  1535. if ( framebuffer !== _currentFramebuffer ) {
  1536. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1537. restore = true;
  1538. }
  1539. try {
  1540. var texture = renderTarget.texture;
  1541. var textureFormat = texture.format;
  1542. var textureType = texture.type;
  1543. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1544. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1545. return;
  1546. }
  1547. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  1548. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  1549. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  1550. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1551. return;
  1552. }
  1553. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  1554. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1555. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1556. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  1557. }
  1558. } else {
  1559. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  1560. }
  1561. } finally {
  1562. if ( restore ) {
  1563. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  1564. }
  1565. }
  1566. }
  1567. };
  1568. this.copyFramebufferToTexture = function ( position, texture, level ) {
  1569. if ( level === undefined ) level = 0;
  1570. var levelScale = Math.pow( 2, - level );
  1571. var width = Math.floor( texture.image.width * levelScale );
  1572. var height = Math.floor( texture.image.height * levelScale );
  1573. var glFormat = utils.convert( texture.format );
  1574. textures.setTexture2D( texture, 0 );
  1575. _gl.copyTexImage2D( _gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0 );
  1576. state.unbindTexture();
  1577. };
  1578. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  1579. var width = srcTexture.image.width;
  1580. var height = srcTexture.image.height;
  1581. var glFormat = utils.convert( dstTexture.format );
  1582. var glType = utils.convert( dstTexture.type );
  1583. textures.setTexture2D( dstTexture, 0 );
  1584. if ( srcTexture.isDataTexture ) {
  1585. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  1586. } else {
  1587. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  1588. }
  1589. state.unbindTexture();
  1590. };
  1591. this.initTexture = function ( texture ) {
  1592. textures.setTexture2D( texture, 0 );
  1593. state.unbindTexture();
  1594. };
  1595. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  1596. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  1597. }
  1598. }
  1599. export { WebGLRenderer };
粤ICP备19079148号