WebGLRenderer.js 73 KB

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