WebGLRenderer.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767
  1. import {
  2. REVISION,
  3. BackSide,
  4. FrontSide,
  5. DoubleSide,
  6. HalfFloatType,
  7. UnsignedByteType,
  8. NoToneMapping,
  9. LinearMipmapLinearFilter,
  10. SRGBColorSpace,
  11. LinearSRGBColorSpace,
  12. RGBAIntegerFormat,
  13. RGIntegerFormat,
  14. RedIntegerFormat,
  15. UnsignedIntType,
  16. UnsignedShortType,
  17. UnsignedInt248Type,
  18. UnsignedShort4444Type,
  19. UnsignedShort5551Type,
  20. WebGLCoordinateSystem,
  21. DisplayP3ColorSpace,
  22. LinearDisplayP3ColorSpace
  23. } from '../constants.js';
  24. import { Color } from '../math/Color.js';
  25. import { Frustum } from '../math/Frustum.js';
  26. import { Matrix4 } from '../math/Matrix4.js';
  27. import { Vector3 } from '../math/Vector3.js';
  28. import { Vector4 } from '../math/Vector4.js';
  29. import { WebGLAnimation } from './webgl/WebGLAnimation.js';
  30. import { WebGLAttributes } from './webgl/WebGLAttributes.js';
  31. import { WebGLBackground } from './webgl/WebGLBackground.js';
  32. import { WebGLBindingStates } from './webgl/WebGLBindingStates.js';
  33. import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer.js';
  34. import { WebGLCapabilities } from './webgl/WebGLCapabilities.js';
  35. import { WebGLClipping } from './webgl/WebGLClipping.js';
  36. import { WebGLCubeMaps } from './webgl/WebGLCubeMaps.js';
  37. import { WebGLCubeUVMaps } from './webgl/WebGLCubeUVMaps.js';
  38. import { WebGLExtensions } from './webgl/WebGLExtensions.js';
  39. import { WebGLGeometries } from './webgl/WebGLGeometries.js';
  40. import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer.js';
  41. import { WebGLInfo } from './webgl/WebGLInfo.js';
  42. import { WebGLMorphtargets } from './webgl/WebGLMorphtargets.js';
  43. import { WebGLObjects } from './webgl/WebGLObjects.js';
  44. import { WebGLPrograms } from './webgl/WebGLPrograms.js';
  45. import { WebGLProperties } from './webgl/WebGLProperties.js';
  46. import { WebGLRenderLists } from './webgl/WebGLRenderLists.js';
  47. import { WebGLRenderStates } from './webgl/WebGLRenderStates.js';
  48. import { WebGLRenderTarget } from './WebGLRenderTarget.js';
  49. import { WebGLShadowMap } from './webgl/WebGLShadowMap.js';
  50. import { WebGLState } from './webgl/WebGLState.js';
  51. import { WebGLTextures } from './webgl/WebGLTextures.js';
  52. import { WebGLUniforms } from './webgl/WebGLUniforms.js';
  53. import { WebGLUtils } from './webgl/WebGLUtils.js';
  54. import { WebXRManager } from './webxr/WebXRManager.js';
  55. import { WebGLMaterials } from './webgl/WebGLMaterials.js';
  56. import { WebGLUniformsGroups } from './webgl/WebGLUniformsGroups.js';
  57. import { createCanvasElement, probeAsync } from '../utils.js';
  58. import { ColorManagement } from '../math/ColorManagement.js';
  59. class WebGLRenderer {
  60. constructor( parameters = {} ) {
  61. const {
  62. canvas = createCanvasElement(),
  63. context = null,
  64. depth = true,
  65. stencil = false,
  66. alpha = false,
  67. antialias = false,
  68. premultipliedAlpha = true,
  69. preserveDrawingBuffer = false,
  70. powerPreference = 'default',
  71. failIfMajorPerformanceCaveat = false,
  72. } = parameters;
  73. this.isWebGLRenderer = true;
  74. let _alpha;
  75. if ( context !== null ) {
  76. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  77. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  78. }
  79. _alpha = context.getContextAttributes().alpha;
  80. } else {
  81. _alpha = alpha;
  82. }
  83. const uintClearColor = new Uint32Array( 4 );
  84. const intClearColor = new Int32Array( 4 );
  85. let currentRenderList = null;
  86. let currentRenderState = null;
  87. // render() can be called from within a callback triggered by another render.
  88. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  89. const renderListStack = [];
  90. const renderStateStack = [];
  91. // public properties
  92. this.domElement = canvas;
  93. // Debug configuration container
  94. this.debug = {
  95. /**
  96. * Enables error checking and reporting when shader programs are being compiled
  97. * @type {boolean}
  98. */
  99. checkShaderErrors: true,
  100. /**
  101. * Callback for custom error reporting.
  102. * @type {?Function}
  103. */
  104. onShaderError: null
  105. };
  106. // clearing
  107. this.autoClear = true;
  108. this.autoClearColor = true;
  109. this.autoClearDepth = true;
  110. this.autoClearStencil = true;
  111. // scene graph
  112. this.sortObjects = true;
  113. // user-defined clipping
  114. this.clippingPlanes = [];
  115. this.localClippingEnabled = false;
  116. // physically based shading
  117. this._outputColorSpace = SRGBColorSpace;
  118. // physical lights
  119. this._useLegacyLights = false;
  120. // tone mapping
  121. this.toneMapping = NoToneMapping;
  122. this.toneMappingExposure = 1.0;
  123. // internal properties
  124. const _this = this;
  125. let _isContextLost = false;
  126. // internal state cache
  127. let _currentActiveCubeFace = 0;
  128. let _currentActiveMipmapLevel = 0;
  129. let _currentRenderTarget = null;
  130. let _currentMaterialId = - 1;
  131. let _currentCamera = null;
  132. const _currentViewport = new Vector4();
  133. const _currentScissor = new Vector4();
  134. let _currentScissorTest = null;
  135. const _currentClearColor = new Color( 0x000000 );
  136. let _currentClearAlpha = 0;
  137. //
  138. let _width = canvas.width;
  139. let _height = canvas.height;
  140. let _pixelRatio = 1;
  141. let _opaqueSort = null;
  142. let _transparentSort = null;
  143. const _viewport = new Vector4( 0, 0, _width, _height );
  144. const _scissor = new Vector4( 0, 0, _width, _height );
  145. let _scissorTest = false;
  146. // frustum
  147. const _frustum = new Frustum();
  148. // clipping
  149. let _clippingEnabled = false;
  150. let _localClippingEnabled = false;
  151. // camera matrices cache
  152. const _projScreenMatrix = new Matrix4();
  153. const _vector3 = new Vector3();
  154. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  155. function getTargetPixelRatio() {
  156. return _currentRenderTarget === null ? _pixelRatio : 1;
  157. }
  158. // initialize
  159. let _gl = context;
  160. function getContext( contextName, contextAttributes ) {
  161. return canvas.getContext( contextName, contextAttributes );
  162. }
  163. try {
  164. const contextAttributes = {
  165. alpha: true,
  166. depth,
  167. stencil,
  168. antialias,
  169. premultipliedAlpha,
  170. preserveDrawingBuffer,
  171. powerPreference,
  172. failIfMajorPerformanceCaveat,
  173. };
  174. // OffscreenCanvas does not have setAttribute, see #22811
  175. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  176. // event listeners must be registered before WebGL context is created, see #12753
  177. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  178. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  179. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  180. if ( _gl === null ) {
  181. const contextName = 'webgl2';
  182. _gl = getContext( contextName, contextAttributes );
  183. if ( _gl === null ) {
  184. if ( getContext( contextName ) ) {
  185. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  186. } else {
  187. throw new Error( 'Error creating WebGL context.' );
  188. }
  189. }
  190. }
  191. } catch ( error ) {
  192. console.error( 'THREE.WebGLRenderer: ' + error.message );
  193. throw error;
  194. }
  195. let extensions, capabilities, state, info;
  196. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  197. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  198. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  199. let utils, bindingStates, uniformsGroups;
  200. function initGLContext() {
  201. extensions = new WebGLExtensions( _gl );
  202. extensions.init();
  203. utils = new WebGLUtils( _gl, extensions );
  204. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  205. state = new WebGLState( _gl );
  206. info = new WebGLInfo( _gl );
  207. properties = new WebGLProperties();
  208. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  209. cubemaps = new WebGLCubeMaps( _this );
  210. cubeuvmaps = new WebGLCubeUVMaps( _this );
  211. attributes = new WebGLAttributes( _gl );
  212. bindingStates = new WebGLBindingStates( _gl, attributes );
  213. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  214. objects = new WebGLObjects( _gl, geometries, attributes, info );
  215. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  216. clipping = new WebGLClipping( properties );
  217. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  218. materials = new WebGLMaterials( _this, properties );
  219. renderLists = new WebGLRenderLists();
  220. renderStates = new WebGLRenderStates( extensions );
  221. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  222. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  223. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  224. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  225. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  226. info.programs = programCache.programs;
  227. _this.capabilities = capabilities;
  228. _this.extensions = extensions;
  229. _this.properties = properties;
  230. _this.renderLists = renderLists;
  231. _this.shadowMap = shadowMap;
  232. _this.state = state;
  233. _this.info = info;
  234. }
  235. initGLContext();
  236. // xr
  237. const xr = new WebXRManager( _this, _gl );
  238. this.xr = xr;
  239. // API
  240. this.getContext = function () {
  241. return _gl;
  242. };
  243. this.getContextAttributes = function () {
  244. return _gl.getContextAttributes();
  245. };
  246. this.forceContextLoss = function () {
  247. const extension = extensions.get( 'WEBGL_lose_context' );
  248. if ( extension ) extension.loseContext();
  249. };
  250. this.forceContextRestore = function () {
  251. const extension = extensions.get( 'WEBGL_lose_context' );
  252. if ( extension ) extension.restoreContext();
  253. };
  254. this.getPixelRatio = function () {
  255. return _pixelRatio;
  256. };
  257. this.setPixelRatio = function ( value ) {
  258. if ( value === undefined ) return;
  259. _pixelRatio = value;
  260. this.setSize( _width, _height, false );
  261. };
  262. this.getSize = function ( target ) {
  263. return target.set( _width, _height );
  264. };
  265. this.setSize = function ( width, height, updateStyle = true ) {
  266. if ( xr.isPresenting ) {
  267. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  268. return;
  269. }
  270. _width = width;
  271. _height = height;
  272. canvas.width = Math.floor( width * _pixelRatio );
  273. canvas.height = Math.floor( height * _pixelRatio );
  274. if ( updateStyle === true ) {
  275. canvas.style.width = width + 'px';
  276. canvas.style.height = height + 'px';
  277. }
  278. this.setViewport( 0, 0, width, height );
  279. };
  280. this.getDrawingBufferSize = function ( target ) {
  281. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  282. };
  283. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  284. _width = width;
  285. _height = height;
  286. _pixelRatio = pixelRatio;
  287. canvas.width = Math.floor( width * pixelRatio );
  288. canvas.height = Math.floor( height * pixelRatio );
  289. this.setViewport( 0, 0, width, height );
  290. };
  291. this.getCurrentViewport = function ( target ) {
  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 ).round() );
  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 ).round() );
  315. };
  316. this.getScissorTest = function () {
  317. return _scissorTest;
  318. };
  319. this.setScissorTest = function ( boolean ) {
  320. state.setScissorTest( _scissorTest = boolean );
  321. };
  322. this.setOpaqueSort = function ( method ) {
  323. _opaqueSort = method;
  324. };
  325. this.setTransparentSort = function ( method ) {
  326. _transparentSort = method;
  327. };
  328. // Clearing
  329. this.getClearColor = function ( target ) {
  330. return target.copy( background.getClearColor() );
  331. };
  332. this.setClearColor = function () {
  333. background.setClearColor.apply( background, arguments );
  334. };
  335. this.getClearAlpha = function () {
  336. return background.getClearAlpha();
  337. };
  338. this.setClearAlpha = function () {
  339. background.setClearAlpha.apply( background, arguments );
  340. };
  341. this.clear = function ( color = true, depth = true, stencil = true ) {
  342. let bits = 0;
  343. if ( color ) {
  344. // check if we're trying to clear an integer target
  345. let isIntegerFormat = false;
  346. if ( _currentRenderTarget !== null ) {
  347. const targetFormat = _currentRenderTarget.texture.format;
  348. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  349. targetFormat === RGIntegerFormat ||
  350. targetFormat === RedIntegerFormat;
  351. }
  352. // use the appropriate clear functions to clear the target if it's a signed
  353. // or unsigned integer target
  354. if ( isIntegerFormat ) {
  355. const targetType = _currentRenderTarget.texture.type;
  356. const isUnsignedType = targetType === UnsignedByteType ||
  357. targetType === UnsignedIntType ||
  358. targetType === UnsignedShortType ||
  359. targetType === UnsignedInt248Type ||
  360. targetType === UnsignedShort4444Type ||
  361. targetType === UnsignedShort5551Type;
  362. const clearColor = background.getClearColor();
  363. const a = background.getClearAlpha();
  364. const r = clearColor.r;
  365. const g = clearColor.g;
  366. const b = clearColor.b;
  367. if ( isUnsignedType ) {
  368. uintClearColor[ 0 ] = r;
  369. uintClearColor[ 1 ] = g;
  370. uintClearColor[ 2 ] = b;
  371. uintClearColor[ 3 ] = a;
  372. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  373. } else {
  374. intClearColor[ 0 ] = r;
  375. intClearColor[ 1 ] = g;
  376. intClearColor[ 2 ] = b;
  377. intClearColor[ 3 ] = a;
  378. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  379. }
  380. } else {
  381. bits |= _gl.COLOR_BUFFER_BIT;
  382. }
  383. }
  384. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  385. if ( stencil ) {
  386. bits |= _gl.STENCIL_BUFFER_BIT;
  387. this.state.buffers.stencil.setMask( 0xffffffff );
  388. }
  389. _gl.clear( bits );
  390. };
  391. this.clearColor = function () {
  392. this.clear( true, false, false );
  393. };
  394. this.clearDepth = function () {
  395. this.clear( false, true, false );
  396. };
  397. this.clearStencil = function () {
  398. this.clear( false, false, true );
  399. };
  400. //
  401. this.dispose = function () {
  402. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  403. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  404. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  405. renderLists.dispose();
  406. renderStates.dispose();
  407. properties.dispose();
  408. cubemaps.dispose();
  409. cubeuvmaps.dispose();
  410. objects.dispose();
  411. bindingStates.dispose();
  412. uniformsGroups.dispose();
  413. programCache.dispose();
  414. xr.dispose();
  415. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  416. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  417. animation.stop();
  418. };
  419. // Events
  420. function onContextLost( event ) {
  421. event.preventDefault();
  422. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  423. _isContextLost = true;
  424. }
  425. function onContextRestore( /* event */ ) {
  426. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  427. _isContextLost = false;
  428. const infoAutoReset = info.autoReset;
  429. const shadowMapEnabled = shadowMap.enabled;
  430. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  431. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  432. const shadowMapType = shadowMap.type;
  433. initGLContext();
  434. info.autoReset = infoAutoReset;
  435. shadowMap.enabled = shadowMapEnabled;
  436. shadowMap.autoUpdate = shadowMapAutoUpdate;
  437. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  438. shadowMap.type = shadowMapType;
  439. }
  440. function onContextCreationError( event ) {
  441. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  442. }
  443. function onMaterialDispose( event ) {
  444. const material = event.target;
  445. material.removeEventListener( 'dispose', onMaterialDispose );
  446. deallocateMaterial( material );
  447. }
  448. // Buffer deallocation
  449. function deallocateMaterial( material ) {
  450. releaseMaterialProgramReferences( material );
  451. properties.remove( material );
  452. }
  453. function releaseMaterialProgramReferences( material ) {
  454. const programs = properties.get( material ).programs;
  455. if ( programs !== undefined ) {
  456. programs.forEach( function ( program ) {
  457. programCache.releaseProgram( program );
  458. } );
  459. if ( material.isShaderMaterial ) {
  460. programCache.releaseShaderCache( material );
  461. }
  462. }
  463. }
  464. // Buffer rendering
  465. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  466. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  467. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  468. const program = setProgram( camera, scene, geometry, material, object );
  469. state.setMaterial( material, frontFaceCW );
  470. //
  471. let index = geometry.index;
  472. let rangeFactor = 1;
  473. if ( material.wireframe === true ) {
  474. index = geometries.getWireframeAttribute( geometry );
  475. if ( index === undefined ) return;
  476. rangeFactor = 2;
  477. }
  478. //
  479. const drawRange = geometry.drawRange;
  480. const position = geometry.attributes.position;
  481. let drawStart = drawRange.start * rangeFactor;
  482. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  483. if ( group !== null ) {
  484. drawStart = Math.max( drawStart, group.start * rangeFactor );
  485. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  486. }
  487. if ( index !== null ) {
  488. drawStart = Math.max( drawStart, 0 );
  489. drawEnd = Math.min( drawEnd, index.count );
  490. } else if ( position !== undefined && position !== null ) {
  491. drawStart = Math.max( drawStart, 0 );
  492. drawEnd = Math.min( drawEnd, position.count );
  493. }
  494. const drawCount = drawEnd - drawStart;
  495. if ( drawCount < 0 || drawCount === Infinity ) return;
  496. //
  497. bindingStates.setup( object, material, program, geometry, index );
  498. let attribute;
  499. let renderer = bufferRenderer;
  500. if ( index !== null ) {
  501. attribute = attributes.get( index );
  502. renderer = indexedBufferRenderer;
  503. renderer.setIndex( attribute );
  504. }
  505. //
  506. if ( object.isMesh ) {
  507. if ( material.wireframe === true ) {
  508. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  509. renderer.setMode( _gl.LINES );
  510. } else {
  511. renderer.setMode( _gl.TRIANGLES );
  512. }
  513. } else if ( object.isLine ) {
  514. let lineWidth = material.linewidth;
  515. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  516. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  517. if ( object.isLineSegments ) {
  518. renderer.setMode( _gl.LINES );
  519. } else if ( object.isLineLoop ) {
  520. renderer.setMode( _gl.LINE_LOOP );
  521. } else {
  522. renderer.setMode( _gl.LINE_STRIP );
  523. }
  524. } else if ( object.isPoints ) {
  525. renderer.setMode( _gl.POINTS );
  526. } else if ( object.isSprite ) {
  527. renderer.setMode( _gl.TRIANGLES );
  528. }
  529. if ( object.isBatchedMesh ) {
  530. if ( object._multiDrawInstances !== null ) {
  531. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  532. } else {
  533. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  534. }
  535. } else if ( object.isInstancedMesh ) {
  536. renderer.renderInstances( drawStart, drawCount, object.count );
  537. } else if ( geometry.isInstancedBufferGeometry ) {
  538. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  539. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  540. renderer.renderInstances( drawStart, drawCount, instanceCount );
  541. } else {
  542. renderer.render( drawStart, drawCount );
  543. }
  544. };
  545. // Compile
  546. function prepareMaterial( material, scene, object ) {
  547. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  548. material.side = BackSide;
  549. material.needsUpdate = true;
  550. getProgram( material, scene, object );
  551. material.side = FrontSide;
  552. material.needsUpdate = true;
  553. getProgram( material, scene, object );
  554. material.side = DoubleSide;
  555. } else {
  556. getProgram( material, scene, object );
  557. }
  558. }
  559. this.compile = function ( scene, camera, targetScene = null ) {
  560. if ( targetScene === null ) targetScene = scene;
  561. currentRenderState = renderStates.get( targetScene );
  562. currentRenderState.init( camera );
  563. renderStateStack.push( currentRenderState );
  564. // gather lights from both the target scene and the new object that will be added to the scene.
  565. targetScene.traverseVisible( function ( object ) {
  566. if ( object.isLight && object.layers.test( camera.layers ) ) {
  567. currentRenderState.pushLight( object );
  568. if ( object.castShadow ) {
  569. currentRenderState.pushShadow( object );
  570. }
  571. }
  572. } );
  573. if ( scene !== targetScene ) {
  574. scene.traverseVisible( function ( object ) {
  575. if ( object.isLight && object.layers.test( camera.layers ) ) {
  576. currentRenderState.pushLight( object );
  577. if ( object.castShadow ) {
  578. currentRenderState.pushShadow( object );
  579. }
  580. }
  581. } );
  582. }
  583. currentRenderState.setupLights( _this._useLegacyLights );
  584. // Only initialize materials in the new scene, not the targetScene.
  585. const materials = new Set();
  586. scene.traverse( function ( object ) {
  587. const material = object.material;
  588. if ( material ) {
  589. if ( Array.isArray( material ) ) {
  590. for ( let i = 0; i < material.length; i ++ ) {
  591. const material2 = material[ i ];
  592. prepareMaterial( material2, targetScene, object );
  593. materials.add( material2 );
  594. }
  595. } else {
  596. prepareMaterial( material, targetScene, object );
  597. materials.add( material );
  598. }
  599. }
  600. } );
  601. renderStateStack.pop();
  602. currentRenderState = null;
  603. return materials;
  604. };
  605. // compileAsync
  606. this.compileAsync = function ( scene, camera, targetScene = null ) {
  607. const materials = this.compile( scene, camera, targetScene );
  608. // Wait for all the materials in the new object to indicate that they're
  609. // ready to be used before resolving the promise.
  610. return new Promise( ( resolve ) => {
  611. function checkMaterialsReady() {
  612. materials.forEach( function ( material ) {
  613. const materialProperties = properties.get( material );
  614. const program = materialProperties.currentProgram;
  615. if ( program.isReady() ) {
  616. // remove any programs that report they're ready to use from the list
  617. materials.delete( material );
  618. }
  619. } );
  620. // once the list of compiling materials is empty, call the callback
  621. if ( materials.size === 0 ) {
  622. resolve( scene );
  623. return;
  624. }
  625. // if some materials are still not ready, wait a bit and check again
  626. setTimeout( checkMaterialsReady, 10 );
  627. }
  628. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  629. // If we can check the compilation status of the materials without
  630. // blocking then do so right away.
  631. checkMaterialsReady();
  632. } else {
  633. // Otherwise start by waiting a bit to give the materials we just
  634. // initialized a chance to finish.
  635. setTimeout( checkMaterialsReady, 10 );
  636. }
  637. } );
  638. };
  639. // Animation Loop
  640. let onAnimationFrameCallback = null;
  641. function onAnimationFrame( time ) {
  642. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  643. }
  644. function onXRSessionStart() {
  645. animation.stop();
  646. }
  647. function onXRSessionEnd() {
  648. animation.start();
  649. }
  650. const animation = new WebGLAnimation();
  651. animation.setAnimationLoop( onAnimationFrame );
  652. if ( typeof self !== 'undefined' ) animation.setContext( self );
  653. this.setAnimationLoop = function ( callback ) {
  654. onAnimationFrameCallback = callback;
  655. xr.setAnimationLoop( callback );
  656. ( callback === null ) ? animation.stop() : animation.start();
  657. };
  658. xr.addEventListener( 'sessionstart', onXRSessionStart );
  659. xr.addEventListener( 'sessionend', onXRSessionEnd );
  660. // Rendering
  661. this.render = function ( scene, camera ) {
  662. if ( camera !== undefined && camera.isCamera !== true ) {
  663. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  664. return;
  665. }
  666. if ( _isContextLost === true ) return;
  667. // update scene graph
  668. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  669. // update camera matrices and frustum
  670. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  671. if ( xr.enabled === true && xr.isPresenting === true ) {
  672. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  673. camera = xr.getCamera(); // use XR camera for rendering
  674. }
  675. //
  676. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  677. currentRenderState = renderStates.get( scene, renderStateStack.length );
  678. currentRenderState.init( camera );
  679. renderStateStack.push( currentRenderState );
  680. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  681. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  682. _localClippingEnabled = this.localClippingEnabled;
  683. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  684. currentRenderList = renderLists.get( scene, renderListStack.length );
  685. currentRenderList.init();
  686. renderListStack.push( currentRenderList );
  687. projectObject( scene, camera, 0, _this.sortObjects );
  688. currentRenderList.finish();
  689. if ( _this.sortObjects === true ) {
  690. currentRenderList.sort( _opaqueSort, _transparentSort );
  691. }
  692. const renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  693. if ( renderBackground ) {
  694. background.addToRenderList( currentRenderList, scene );
  695. }
  696. //
  697. this.info.render.frame ++;
  698. if ( _clippingEnabled === true ) clipping.beginShadows();
  699. const shadowsArray = currentRenderState.state.shadowsArray;
  700. shadowMap.render( shadowsArray, scene, camera );
  701. if ( _clippingEnabled === true ) clipping.endShadows();
  702. //
  703. if ( this.info.autoReset === true ) this.info.reset();
  704. // render scene
  705. const opaqueObjects = currentRenderList.opaque;
  706. const transmissiveObjects = currentRenderList.transmissive;
  707. currentRenderState.setupLights( _this._useLegacyLights );
  708. if ( camera.isArrayCamera ) {
  709. const cameras = camera.cameras;
  710. if ( transmissiveObjects.length > 0 ) {
  711. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  712. const camera2 = cameras[ i ];
  713. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  714. }
  715. }
  716. if ( renderBackground ) background.render( scene );
  717. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  718. const camera2 = cameras[ i ];
  719. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  720. }
  721. } else {
  722. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  723. if ( renderBackground ) background.render( scene );
  724. renderScene( currentRenderList, scene, camera );
  725. }
  726. //
  727. if ( _currentRenderTarget !== null ) {
  728. // resolve multisample renderbuffers to a single-sample texture if necessary
  729. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  730. // Generate mipmap if we're using any kind of mipmap filtering
  731. textures.updateRenderTargetMipmap( _currentRenderTarget );
  732. }
  733. //
  734. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  735. // _gl.finish();
  736. bindingStates.resetDefaultState();
  737. _currentMaterialId = - 1;
  738. _currentCamera = null;
  739. renderStateStack.pop();
  740. if ( renderStateStack.length > 0 ) {
  741. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  742. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  743. } else {
  744. currentRenderState = null;
  745. }
  746. renderListStack.pop();
  747. if ( renderListStack.length > 0 ) {
  748. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  749. } else {
  750. currentRenderList = null;
  751. }
  752. };
  753. function projectObject( object, camera, groupOrder, sortObjects ) {
  754. if ( object.visible === false ) return;
  755. const visible = object.layers.test( camera.layers );
  756. if ( visible ) {
  757. if ( object.isGroup ) {
  758. groupOrder = object.renderOrder;
  759. } else if ( object.isLOD ) {
  760. if ( object.autoUpdate === true ) object.update( camera );
  761. } else if ( object.isLight ) {
  762. currentRenderState.pushLight( object );
  763. if ( object.castShadow ) {
  764. currentRenderState.pushShadow( object );
  765. }
  766. } else if ( object.isSprite ) {
  767. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  768. if ( sortObjects ) {
  769. _vector3.setFromMatrixPosition( object.matrixWorld )
  770. .applyMatrix4( _projScreenMatrix );
  771. }
  772. const geometry = objects.update( object );
  773. const material = object.material;
  774. if ( material.visible ) {
  775. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  776. }
  777. }
  778. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  779. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  780. const geometry = objects.update( object );
  781. const material = object.material;
  782. if ( sortObjects ) {
  783. if ( object.boundingSphere !== undefined ) {
  784. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  785. _vector3.copy( object.boundingSphere.center );
  786. } else {
  787. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  788. _vector3.copy( geometry.boundingSphere.center );
  789. }
  790. _vector3
  791. .applyMatrix4( object.matrixWorld )
  792. .applyMatrix4( _projScreenMatrix );
  793. }
  794. if ( Array.isArray( material ) ) {
  795. const groups = geometry.groups;
  796. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  797. const group = groups[ i ];
  798. const groupMaterial = material[ group.materialIndex ];
  799. if ( groupMaterial && groupMaterial.visible ) {
  800. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  801. }
  802. }
  803. } else if ( material.visible ) {
  804. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  805. }
  806. }
  807. }
  808. }
  809. const children = object.children;
  810. for ( let i = 0, l = children.length; i < l; i ++ ) {
  811. projectObject( children[ i ], camera, groupOrder, sortObjects );
  812. }
  813. }
  814. function renderScene( currentRenderList, scene, camera, viewport ) {
  815. const opaqueObjects = currentRenderList.opaque;
  816. const transmissiveObjects = currentRenderList.transmissive;
  817. const transparentObjects = currentRenderList.transparent;
  818. currentRenderState.setupLightsView( camera );
  819. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  820. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  821. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  822. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  823. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  824. // Ensure depth buffer writing is enabled so it can be cleared on next render
  825. state.buffers.depth.setTest( true );
  826. state.buffers.depth.setMask( true );
  827. state.buffers.color.setMask( true );
  828. state.setPolygonOffset( false );
  829. }
  830. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  831. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  832. if ( overrideMaterial !== null ) {
  833. return;
  834. }
  835. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  836. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  837. generateMipmaps: true,
  838. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  839. minFilter: LinearMipmapLinearFilter,
  840. samples: 4,
  841. stencilBuffer: stencil,
  842. resolveDepthBuffer: false,
  843. resolveStencilBuffer: false
  844. } );
  845. // debug
  846. /*
  847. const geometry = new PlaneGeometry();
  848. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  849. const mesh = new Mesh( geometry, material );
  850. scene.add( mesh );
  851. */
  852. }
  853. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  854. const activeViewport = camera.viewport || _currentViewport;
  855. transmissionRenderTarget.setSize( activeViewport.z, activeViewport.w );
  856. //
  857. const currentRenderTarget = _this.getRenderTarget();
  858. _this.setRenderTarget( transmissionRenderTarget );
  859. _this.getClearColor( _currentClearColor );
  860. _currentClearAlpha = _this.getClearAlpha();
  861. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  862. _this.clear();
  863. // Turn off the features which can affect the frag color for opaque objects pass.
  864. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  865. const currentToneMapping = _this.toneMapping;
  866. _this.toneMapping = NoToneMapping;
  867. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  868. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  869. const currentCameraViewport = camera.viewport;
  870. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  871. currentRenderState.setupLightsView( camera );
  872. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  873. renderObjects( opaqueObjects, scene, camera );
  874. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  875. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  876. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  877. let renderTargetNeedsUpdate = false;
  878. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  879. const renderItem = transmissiveObjects[ i ];
  880. const object = renderItem.object;
  881. const geometry = renderItem.geometry;
  882. const material = renderItem.material;
  883. const group = renderItem.group;
  884. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  885. const currentSide = material.side;
  886. material.side = BackSide;
  887. material.needsUpdate = true;
  888. renderObject( object, scene, camera, geometry, material, group );
  889. material.side = currentSide;
  890. material.needsUpdate = true;
  891. renderTargetNeedsUpdate = true;
  892. }
  893. }
  894. if ( renderTargetNeedsUpdate === true ) {
  895. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  896. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  897. }
  898. }
  899. _this.setRenderTarget( currentRenderTarget );
  900. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  901. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  902. _this.toneMapping = currentToneMapping;
  903. }
  904. function renderObjects( renderList, scene, camera ) {
  905. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  906. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  907. const renderItem = renderList[ i ];
  908. const object = renderItem.object;
  909. const geometry = renderItem.geometry;
  910. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  911. const group = renderItem.group;
  912. if ( object.layers.test( camera.layers ) ) {
  913. renderObject( object, scene, camera, geometry, material, group );
  914. }
  915. }
  916. }
  917. function renderObject( object, scene, camera, geometry, material, group ) {
  918. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  919. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  920. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  921. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  922. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  923. material.side = BackSide;
  924. material.needsUpdate = true;
  925. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  926. material.side = FrontSide;
  927. material.needsUpdate = true;
  928. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  929. material.side = DoubleSide;
  930. } else {
  931. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  932. }
  933. object.onAfterRender( _this, scene, camera, geometry, material, group );
  934. }
  935. function getProgram( material, scene, object ) {
  936. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  937. const materialProperties = properties.get( material );
  938. const lights = currentRenderState.state.lights;
  939. const shadowsArray = currentRenderState.state.shadowsArray;
  940. const lightsStateVersion = lights.state.version;
  941. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  942. const programCacheKey = programCache.getProgramCacheKey( parameters );
  943. let programs = materialProperties.programs;
  944. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  945. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  946. materialProperties.fog = scene.fog;
  947. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  948. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  949. if ( programs === undefined ) {
  950. // new material
  951. material.addEventListener( 'dispose', onMaterialDispose );
  952. programs = new Map();
  953. materialProperties.programs = programs;
  954. }
  955. let program = programs.get( programCacheKey );
  956. if ( program !== undefined ) {
  957. // early out if program and light state is identical
  958. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  959. updateCommonMaterialProperties( material, parameters );
  960. return program;
  961. }
  962. } else {
  963. parameters.uniforms = programCache.getUniforms( material );
  964. material.onBuild( object, parameters, _this );
  965. material.onBeforeCompile( parameters, _this );
  966. program = programCache.acquireProgram( parameters, programCacheKey );
  967. programs.set( programCacheKey, program );
  968. materialProperties.uniforms = parameters.uniforms;
  969. }
  970. const uniforms = materialProperties.uniforms;
  971. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  972. uniforms.clippingPlanes = clipping.uniform;
  973. }
  974. updateCommonMaterialProperties( material, parameters );
  975. // store the light setup it was created for
  976. materialProperties.needsLights = materialNeedsLights( material );
  977. materialProperties.lightsStateVersion = lightsStateVersion;
  978. if ( materialProperties.needsLights ) {
  979. // wire up the material to this renderer's lighting state
  980. uniforms.ambientLightColor.value = lights.state.ambient;
  981. uniforms.lightProbe.value = lights.state.probe;
  982. uniforms.directionalLights.value = lights.state.directional;
  983. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  984. uniforms.spotLights.value = lights.state.spot;
  985. uniforms.spotLightShadows.value = lights.state.spotShadow;
  986. uniforms.rectAreaLights.value = lights.state.rectArea;
  987. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  988. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  989. uniforms.pointLights.value = lights.state.point;
  990. uniforms.pointLightShadows.value = lights.state.pointShadow;
  991. uniforms.hemisphereLights.value = lights.state.hemi;
  992. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  993. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  994. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  995. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  996. uniforms.spotLightMap.value = lights.state.spotLightMap;
  997. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  998. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  999. // TODO (abelnation): add area lights shadow info to uniforms
  1000. }
  1001. materialProperties.currentProgram = program;
  1002. materialProperties.uniformsList = null;
  1003. return program;
  1004. }
  1005. function getUniformList( materialProperties ) {
  1006. if ( materialProperties.uniformsList === null ) {
  1007. const progUniforms = materialProperties.currentProgram.getUniforms();
  1008. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  1009. }
  1010. return materialProperties.uniformsList;
  1011. }
  1012. function updateCommonMaterialProperties( material, parameters ) {
  1013. const materialProperties = properties.get( material );
  1014. materialProperties.outputColorSpace = parameters.outputColorSpace;
  1015. materialProperties.batching = parameters.batching;
  1016. materialProperties.instancing = parameters.instancing;
  1017. materialProperties.instancingColor = parameters.instancingColor;
  1018. materialProperties.instancingMorph = parameters.instancingMorph;
  1019. materialProperties.skinning = parameters.skinning;
  1020. materialProperties.morphTargets = parameters.morphTargets;
  1021. materialProperties.morphNormals = parameters.morphNormals;
  1022. materialProperties.morphColors = parameters.morphColors;
  1023. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  1024. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  1025. materialProperties.numIntersection = parameters.numClipIntersection;
  1026. materialProperties.vertexAlphas = parameters.vertexAlphas;
  1027. materialProperties.vertexTangents = parameters.vertexTangents;
  1028. materialProperties.toneMapping = parameters.toneMapping;
  1029. }
  1030. function setProgram( camera, scene, geometry, material, object ) {
  1031. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  1032. textures.resetTextureUnits();
  1033. const fog = scene.fog;
  1034. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  1035. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  1036. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  1037. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  1038. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  1039. const morphTargets = !! geometry.morphAttributes.position;
  1040. const morphNormals = !! geometry.morphAttributes.normal;
  1041. const morphColors = !! geometry.morphAttributes.color;
  1042. let toneMapping = NoToneMapping;
  1043. if ( material.toneMapped ) {
  1044. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  1045. toneMapping = _this.toneMapping;
  1046. }
  1047. }
  1048. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  1049. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  1050. const materialProperties = properties.get( material );
  1051. const lights = currentRenderState.state.lights;
  1052. if ( _clippingEnabled === true ) {
  1053. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  1054. const useCache =
  1055. camera === _currentCamera &&
  1056. material.id === _currentMaterialId;
  1057. // we might want to call this function with some ClippingGroup
  1058. // object instead of the material, once it becomes feasible
  1059. // (#8465, #8379)
  1060. clipping.setState( material, camera, useCache );
  1061. }
  1062. }
  1063. //
  1064. let needsProgramChange = false;
  1065. if ( material.version === materialProperties.__version ) {
  1066. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  1067. needsProgramChange = true;
  1068. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  1069. needsProgramChange = true;
  1070. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  1071. needsProgramChange = true;
  1072. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  1073. needsProgramChange = true;
  1074. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  1075. needsProgramChange = true;
  1076. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  1077. needsProgramChange = true;
  1078. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  1079. needsProgramChange = true;
  1080. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  1081. needsProgramChange = true;
  1082. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  1083. needsProgramChange = true;
  1084. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  1085. needsProgramChange = true;
  1086. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  1087. needsProgramChange = true;
  1088. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  1089. needsProgramChange = true;
  1090. } else if ( materialProperties.envMap !== envMap ) {
  1091. needsProgramChange = true;
  1092. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  1093. needsProgramChange = true;
  1094. } else if ( materialProperties.numClippingPlanes !== undefined &&
  1095. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  1096. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  1097. needsProgramChange = true;
  1098. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  1099. needsProgramChange = true;
  1100. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  1101. needsProgramChange = true;
  1102. } else if ( materialProperties.morphTargets !== morphTargets ) {
  1103. needsProgramChange = true;
  1104. } else if ( materialProperties.morphNormals !== morphNormals ) {
  1105. needsProgramChange = true;
  1106. } else if ( materialProperties.morphColors !== morphColors ) {
  1107. needsProgramChange = true;
  1108. } else if ( materialProperties.toneMapping !== toneMapping ) {
  1109. needsProgramChange = true;
  1110. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  1111. needsProgramChange = true;
  1112. }
  1113. } else {
  1114. needsProgramChange = true;
  1115. materialProperties.__version = material.version;
  1116. }
  1117. //
  1118. let program = materialProperties.currentProgram;
  1119. if ( needsProgramChange === true ) {
  1120. program = getProgram( material, scene, object );
  1121. }
  1122. let refreshProgram = false;
  1123. let refreshMaterial = false;
  1124. let refreshLights = false;
  1125. const p_uniforms = program.getUniforms(),
  1126. m_uniforms = materialProperties.uniforms;
  1127. if ( state.useProgram( program.program ) ) {
  1128. refreshProgram = true;
  1129. refreshMaterial = true;
  1130. refreshLights = true;
  1131. }
  1132. if ( material.id !== _currentMaterialId ) {
  1133. _currentMaterialId = material.id;
  1134. refreshMaterial = true;
  1135. }
  1136. if ( refreshProgram || _currentCamera !== camera ) {
  1137. // common camera uniforms
  1138. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  1139. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1140. const uCamPos = p_uniforms.map.cameraPosition;
  1141. if ( uCamPos !== undefined ) {
  1142. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1143. }
  1144. if ( capabilities.logarithmicDepthBuffer ) {
  1145. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1146. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1147. }
  1148. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  1149. if ( material.isMeshPhongMaterial ||
  1150. material.isMeshToonMaterial ||
  1151. material.isMeshLambertMaterial ||
  1152. material.isMeshBasicMaterial ||
  1153. material.isMeshStandardMaterial ||
  1154. material.isShaderMaterial ) {
  1155. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  1156. }
  1157. if ( _currentCamera !== camera ) {
  1158. _currentCamera = camera;
  1159. // lighting uniforms depend on the camera so enforce an update
  1160. // now, in case this material supports lights - or later, when
  1161. // the next material that does gets activated:
  1162. refreshMaterial = true; // set to true on material change
  1163. refreshLights = true; // remains set until update done
  1164. }
  1165. }
  1166. // skinning and morph target uniforms must be set even if material didn't change
  1167. // auto-setting of texture unit for bone and morph texture must go before other textures
  1168. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  1169. if ( object.isSkinnedMesh ) {
  1170. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1171. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1172. const skeleton = object.skeleton;
  1173. if ( skeleton ) {
  1174. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  1175. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  1176. }
  1177. }
  1178. if ( object.isBatchedMesh ) {
  1179. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  1180. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  1181. }
  1182. const morphAttributes = geometry.morphAttributes;
  1183. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  1184. morphtargets.update( object, geometry, program );
  1185. }
  1186. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  1187. materialProperties.receiveShadow = object.receiveShadow;
  1188. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  1189. }
  1190. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  1191. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  1192. m_uniforms.envMap.value = envMap;
  1193. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  1194. }
  1195. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  1196. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  1197. }
  1198. if ( refreshMaterial ) {
  1199. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  1200. if ( materialProperties.needsLights ) {
  1201. // the current material requires lighting info
  1202. // note: all lighting uniforms are always set correctly
  1203. // they simply reference the renderer's state for their
  1204. // values
  1205. //
  1206. // use the current material's .needsUpdate flags to set
  1207. // the GL state when required
  1208. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1209. }
  1210. // refresh uniforms common to several materials
  1211. if ( fog && material.fog === true ) {
  1212. materials.refreshFogUniforms( m_uniforms, fog );
  1213. }
  1214. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  1215. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  1216. }
  1217. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  1218. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  1219. material.uniformsNeedUpdate = false;
  1220. }
  1221. if ( material.isSpriteMaterial ) {
  1222. p_uniforms.setValue( _gl, 'center', object.center );
  1223. }
  1224. // common matrices
  1225. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1226. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1227. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1228. // UBOs
  1229. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  1230. const groups = material.uniformsGroups;
  1231. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  1232. const group = groups[ i ];
  1233. uniformsGroups.update( group, program );
  1234. uniformsGroups.bind( group, program );
  1235. }
  1236. }
  1237. return program;
  1238. }
  1239. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1240. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1241. uniforms.ambientLightColor.needsUpdate = value;
  1242. uniforms.lightProbe.needsUpdate = value;
  1243. uniforms.directionalLights.needsUpdate = value;
  1244. uniforms.directionalLightShadows.needsUpdate = value;
  1245. uniforms.pointLights.needsUpdate = value;
  1246. uniforms.pointLightShadows.needsUpdate = value;
  1247. uniforms.spotLights.needsUpdate = value;
  1248. uniforms.spotLightShadows.needsUpdate = value;
  1249. uniforms.rectAreaLights.needsUpdate = value;
  1250. uniforms.hemisphereLights.needsUpdate = value;
  1251. }
  1252. function materialNeedsLights( material ) {
  1253. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  1254. material.isMeshStandardMaterial || material.isShadowMaterial ||
  1255. ( material.isShaderMaterial && material.lights === true );
  1256. }
  1257. this.getActiveCubeFace = function () {
  1258. return _currentActiveCubeFace;
  1259. };
  1260. this.getActiveMipmapLevel = function () {
  1261. return _currentActiveMipmapLevel;
  1262. };
  1263. this.getRenderTarget = function () {
  1264. return _currentRenderTarget;
  1265. };
  1266. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  1267. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  1268. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  1269. const renderTargetProperties = properties.get( renderTarget );
  1270. renderTargetProperties.__hasExternalTextures = true;
  1271. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  1272. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  1273. // The multisample_render_to_texture extension doesn't work properly if there
  1274. // are midframe flushes and an external depth buffer. Disable use of the extension.
  1275. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  1276. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  1277. renderTargetProperties.__useRenderToTexture = false;
  1278. }
  1279. }
  1280. };
  1281. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  1282. const renderTargetProperties = properties.get( renderTarget );
  1283. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  1284. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  1285. };
  1286. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  1287. _currentRenderTarget = renderTarget;
  1288. _currentActiveCubeFace = activeCubeFace;
  1289. _currentActiveMipmapLevel = activeMipmapLevel;
  1290. let useDefaultFramebuffer = true;
  1291. let framebuffer = null;
  1292. let isCube = false;
  1293. let isRenderTarget3D = false;
  1294. if ( renderTarget ) {
  1295. const renderTargetProperties = properties.get( renderTarget );
  1296. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  1297. // We need to make sure to rebind the framebuffer.
  1298. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1299. useDefaultFramebuffer = false;
  1300. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  1301. textures.setupRenderTarget( renderTarget );
  1302. } else if ( renderTargetProperties.__hasExternalTextures ) {
  1303. // Color and depth texture must be rebound in order for the swapchain to update.
  1304. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  1305. }
  1306. const texture = renderTarget.texture;
  1307. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  1308. isRenderTarget3D = true;
  1309. }
  1310. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1311. if ( renderTarget.isWebGLCubeRenderTarget ) {
  1312. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  1313. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  1314. } else {
  1315. framebuffer = __webglFramebuffer[ activeCubeFace ];
  1316. }
  1317. isCube = true;
  1318. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  1319. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  1320. } else {
  1321. if ( Array.isArray( __webglFramebuffer ) ) {
  1322. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  1323. } else {
  1324. framebuffer = __webglFramebuffer;
  1325. }
  1326. }
  1327. _currentViewport.copy( renderTarget.viewport );
  1328. _currentScissor.copy( renderTarget.scissor );
  1329. _currentScissorTest = renderTarget.scissorTest;
  1330. } else {
  1331. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  1332. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  1333. _currentScissorTest = _scissorTest;
  1334. }
  1335. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1336. if ( framebufferBound && useDefaultFramebuffer ) {
  1337. state.drawBuffers( renderTarget, framebuffer );
  1338. }
  1339. state.viewport( _currentViewport );
  1340. state.scissor( _currentScissor );
  1341. state.setScissorTest( _currentScissorTest );
  1342. if ( isCube ) {
  1343. const textureProperties = properties.get( renderTarget.texture );
  1344. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  1345. } else if ( isRenderTarget3D ) {
  1346. const textureProperties = properties.get( renderTarget.texture );
  1347. const layer = activeCubeFace || 0;
  1348. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  1349. }
  1350. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  1351. };
  1352. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1353. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1354. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1355. return;
  1356. }
  1357. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1358. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  1359. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1360. }
  1361. if ( framebuffer ) {
  1362. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1363. try {
  1364. const texture = renderTarget.texture;
  1365. const textureFormat = texture.format;
  1366. const textureType = texture.type;
  1367. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  1368. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1369. return;
  1370. }
  1371. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  1372. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1373. return;
  1374. }
  1375. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1376. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1377. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  1378. }
  1379. } finally {
  1380. // restore framebuffer of current render target if necessary
  1381. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  1382. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1383. }
  1384. }
  1385. };
  1386. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1387. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1388. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1389. }
  1390. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1391. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  1392. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1393. }
  1394. if ( framebuffer ) {
  1395. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1396. try {
  1397. const texture = renderTarget.texture;
  1398. const textureFormat = texture.format;
  1399. const textureType = texture.type;
  1400. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  1401. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  1402. }
  1403. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  1404. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1405. }
  1406. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1407. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1408. const glBuffer = _gl.createBuffer();
  1409. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  1410. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  1411. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  1412. _gl.flush();
  1413. // check if the commands have finished every 8 ms
  1414. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  1415. await probeAsync( _gl, sync, 4 );
  1416. try {
  1417. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  1418. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  1419. } finally {
  1420. _gl.deleteBuffer( glBuffer );
  1421. _gl.deleteSync( sync );
  1422. }
  1423. return buffer;
  1424. }
  1425. } finally {
  1426. // restore framebuffer of current render target if necessary
  1427. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  1428. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1429. }
  1430. }
  1431. };
  1432. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  1433. const levelScale = Math.pow( 2, - level );
  1434. const width = Math.floor( texture.image.width * levelScale );
  1435. const height = Math.floor( texture.image.height * levelScale );
  1436. textures.setTexture2D( texture, 0 );
  1437. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  1438. state.unbindTexture();
  1439. };
  1440. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  1441. // support previous signature with source box first
  1442. if ( srcTexture.isTexture !== true ) {
  1443. // @deprecated, r165
  1444. console.warn( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  1445. dstPosition = arguments[ 0 ] || null;
  1446. srcTexture = arguments[ 1 ];
  1447. dstTexture = arguments[ 2 ];
  1448. level = arguments[ 3 ] || 0;
  1449. srcRegion = null;
  1450. }
  1451. let width, height, minX, minY;
  1452. let dstX, dstY;
  1453. if ( srcRegion !== null ) {
  1454. width = srcRegion.max.x - srcRegion.min.x;
  1455. height = srcRegion.max.y - srcRegion.min.y;
  1456. minX = srcRegion.min.x;
  1457. minY = srcRegion.min.y;
  1458. } else {
  1459. width = srcTexture.image.width;
  1460. height = srcTexture.image.height;
  1461. minX = 0;
  1462. minY = 0;
  1463. }
  1464. if ( dstPosition !== null ) {
  1465. dstX = dstPosition.x;
  1466. dstY = dstPosition.y;
  1467. } else {
  1468. dstX = 0;
  1469. dstY = 0;
  1470. }
  1471. const glFormat = utils.convert( dstTexture.format );
  1472. const glType = utils.convert( dstTexture.type );
  1473. textures.setTexture2D( dstTexture, 0 );
  1474. // As another texture upload may have changed pixelStorei
  1475. // parameters, make sure they are correct for the dstTexture
  1476. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  1477. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  1478. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  1479. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  1480. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  1481. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  1482. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  1483. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  1484. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  1485. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  1486. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  1487. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  1488. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  1489. if ( srcTexture.isDataTexture ) {
  1490. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  1491. } else {
  1492. if ( srcTexture.isCompressedTexture ) {
  1493. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  1494. } else {
  1495. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, glFormat, glType, image );
  1496. }
  1497. }
  1498. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  1499. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  1500. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  1501. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  1502. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  1503. // Generate mipmaps only when copying level 0
  1504. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1505. state.unbindTexture();
  1506. };
  1507. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  1508. // support previous signature with source box first
  1509. if ( srcTexture.isTexture !== true ) {
  1510. // @deprecated, r165
  1511. console.warn( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  1512. srcRegion = arguments[ 0 ] || null;
  1513. dstPosition = arguments[ 1 ] || null;
  1514. srcTexture = arguments[ 2 ];
  1515. dstTexture = arguments[ 3 ];
  1516. level = arguments[ 4 ] || 0;
  1517. }
  1518. let width, height, depth, minX, minY, minZ;
  1519. let dstX, dstY, dstZ;
  1520. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  1521. if ( srcRegion !== null ) {
  1522. width = srcRegion.max.x - srcRegion.min.x;
  1523. height = srcRegion.max.y - srcRegion.min.y;
  1524. depth = srcRegion.max.z - srcRegion.min.z;
  1525. minX = srcRegion.min.x;
  1526. minY = srcRegion.min.y;
  1527. minZ = srcRegion.min.z;
  1528. } else {
  1529. width = image.width;
  1530. height = image.height;
  1531. depth = image.depth;
  1532. minX = 0;
  1533. minY = 0;
  1534. minZ = 0;
  1535. }
  1536. if ( dstPosition !== null ) {
  1537. dstX = dstPosition.x;
  1538. dstY = dstPosition.y;
  1539. dstZ = dstPosition.z;
  1540. } else {
  1541. dstX = 0;
  1542. dstY = 0;
  1543. dstZ = 0;
  1544. }
  1545. const glFormat = utils.convert( dstTexture.format );
  1546. const glType = utils.convert( dstTexture.type );
  1547. let glTarget;
  1548. if ( dstTexture.isData3DTexture ) {
  1549. textures.setTexture3D( dstTexture, 0 );
  1550. glTarget = _gl.TEXTURE_3D;
  1551. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  1552. textures.setTexture2DArray( dstTexture, 0 );
  1553. glTarget = _gl.TEXTURE_2D_ARRAY;
  1554. } else {
  1555. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  1556. return;
  1557. }
  1558. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  1559. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  1560. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  1561. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  1562. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  1563. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  1564. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  1565. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  1566. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  1567. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  1568. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  1569. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  1570. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  1571. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  1572. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  1573. } else {
  1574. if ( dstTexture.isCompressedArrayTexture ) {
  1575. _gl.compressedTexSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  1576. } else {
  1577. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  1578. }
  1579. }
  1580. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  1581. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  1582. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  1583. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  1584. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  1585. // Generate mipmaps only when copying level 0
  1586. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  1587. state.unbindTexture();
  1588. };
  1589. this.initRenderTarget = function ( target ) {
  1590. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  1591. textures.setupRenderTarget( target );
  1592. }
  1593. };
  1594. this.initTexture = function ( texture ) {
  1595. if ( texture.isCubeTexture ) {
  1596. textures.setTextureCube( texture, 0 );
  1597. } else if ( texture.isData3DTexture ) {
  1598. textures.setTexture3D( texture, 0 );
  1599. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  1600. textures.setTexture2DArray( texture, 0 );
  1601. } else {
  1602. textures.setTexture2D( texture, 0 );
  1603. }
  1604. state.unbindTexture();
  1605. };
  1606. this.resetState = function () {
  1607. _currentActiveCubeFace = 0;
  1608. _currentActiveMipmapLevel = 0;
  1609. _currentRenderTarget = null;
  1610. state.reset();
  1611. bindingStates.reset();
  1612. };
  1613. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  1614. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  1615. }
  1616. }
  1617. get coordinateSystem() {
  1618. return WebGLCoordinateSystem;
  1619. }
  1620. get outputColorSpace() {
  1621. return this._outputColorSpace;
  1622. }
  1623. set outputColorSpace( colorSpace ) {
  1624. this._outputColorSpace = colorSpace;
  1625. const gl = this.getContext();
  1626. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  1627. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  1628. }
  1629. get useLegacyLights() { // @deprecated, r155
  1630. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  1631. return this._useLegacyLights;
  1632. }
  1633. set useLegacyLights( value ) { // @deprecated, r155
  1634. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  1635. this._useLegacyLights = value;
  1636. }
  1637. }
  1638. export { WebGLRenderer };