WebGLRenderer.js 53 KB

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