WebGLRenderer.js 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829
  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. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  535. const starts = object._multiDrawStarts;
  536. const counts = object._multiDrawCounts;
  537. const drawCount = object._multiDrawCount;
  538. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  539. const uniforms = properties.get( material ).currentProgram.getUniforms();
  540. for ( let i = 0; i < drawCount; i ++ ) {
  541. uniforms.setValue( _gl, '_gl_DrawID', i );
  542. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  543. }
  544. } else {
  545. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  546. }
  547. }
  548. } else if ( object.isInstancedMesh ) {
  549. renderer.renderInstances( drawStart, drawCount, object.count );
  550. } else if ( geometry.isInstancedBufferGeometry ) {
  551. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  552. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  553. renderer.renderInstances( drawStart, drawCount, instanceCount );
  554. } else {
  555. renderer.render( drawStart, drawCount );
  556. }
  557. };
  558. // Compile
  559. function prepareMaterial( material, scene, object ) {
  560. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  561. material.side = BackSide;
  562. material.needsUpdate = true;
  563. getProgram( material, scene, object );
  564. material.side = FrontSide;
  565. material.needsUpdate = true;
  566. getProgram( material, scene, object );
  567. material.side = DoubleSide;
  568. } else {
  569. getProgram( material, scene, object );
  570. }
  571. }
  572. this.compile = function ( scene, camera, targetScene = null ) {
  573. if ( targetScene === null ) targetScene = scene;
  574. currentRenderState = renderStates.get( targetScene );
  575. currentRenderState.init( camera );
  576. renderStateStack.push( currentRenderState );
  577. // gather lights from both the target scene and the new object that will be added to the scene.
  578. targetScene.traverseVisible( function ( object ) {
  579. if ( object.isLight && object.layers.test( camera.layers ) ) {
  580. currentRenderState.pushLight( object );
  581. if ( object.castShadow ) {
  582. currentRenderState.pushShadow( object );
  583. }
  584. }
  585. } );
  586. if ( scene !== targetScene ) {
  587. scene.traverseVisible( function ( object ) {
  588. if ( object.isLight && object.layers.test( camera.layers ) ) {
  589. currentRenderState.pushLight( object );
  590. if ( object.castShadow ) {
  591. currentRenderState.pushShadow( object );
  592. }
  593. }
  594. } );
  595. }
  596. currentRenderState.setupLights( _this._useLegacyLights );
  597. // Only initialize materials in the new scene, not the targetScene.
  598. const materials = new Set();
  599. scene.traverse( function ( object ) {
  600. const material = object.material;
  601. if ( material ) {
  602. if ( Array.isArray( material ) ) {
  603. for ( let i = 0; i < material.length; i ++ ) {
  604. const material2 = material[ i ];
  605. prepareMaterial( material2, targetScene, object );
  606. materials.add( material2 );
  607. }
  608. } else {
  609. prepareMaterial( material, targetScene, object );
  610. materials.add( material );
  611. }
  612. }
  613. } );
  614. renderStateStack.pop();
  615. currentRenderState = null;
  616. return materials;
  617. };
  618. // compileAsync
  619. this.compileAsync = function ( scene, camera, targetScene = null ) {
  620. const materials = this.compile( scene, camera, targetScene );
  621. // Wait for all the materials in the new object to indicate that they're
  622. // ready to be used before resolving the promise.
  623. return new Promise( ( resolve ) => {
  624. function checkMaterialsReady() {
  625. materials.forEach( function ( material ) {
  626. const materialProperties = properties.get( material );
  627. const program = materialProperties.currentProgram;
  628. if ( program.isReady() ) {
  629. // remove any programs that report they're ready to use from the list
  630. materials.delete( material );
  631. }
  632. } );
  633. // once the list of compiling materials is empty, call the callback
  634. if ( materials.size === 0 ) {
  635. resolve( scene );
  636. return;
  637. }
  638. // if some materials are still not ready, wait a bit and check again
  639. setTimeout( checkMaterialsReady, 10 );
  640. }
  641. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  642. // If we can check the compilation status of the materials without
  643. // blocking then do so right away.
  644. checkMaterialsReady();
  645. } else {
  646. // Otherwise start by waiting a bit to give the materials we just
  647. // initialized a chance to finish.
  648. setTimeout( checkMaterialsReady, 10 );
  649. }
  650. } );
  651. };
  652. // Animation Loop
  653. let onAnimationFrameCallback = null;
  654. function onAnimationFrame( time ) {
  655. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  656. }
  657. function onXRSessionStart() {
  658. animation.stop();
  659. }
  660. function onXRSessionEnd() {
  661. animation.start();
  662. }
  663. const animation = new WebGLAnimation();
  664. animation.setAnimationLoop( onAnimationFrame );
  665. if ( typeof self !== 'undefined' ) animation.setContext( self );
  666. this.setAnimationLoop = function ( callback ) {
  667. onAnimationFrameCallback = callback;
  668. xr.setAnimationLoop( callback );
  669. ( callback === null ) ? animation.stop() : animation.start();
  670. };
  671. xr.addEventListener( 'sessionstart', onXRSessionStart );
  672. xr.addEventListener( 'sessionend', onXRSessionEnd );
  673. // Rendering
  674. this.render = function ( scene, camera ) {
  675. if ( camera !== undefined && camera.isCamera !== true ) {
  676. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  677. return;
  678. }
  679. if ( _isContextLost === true ) return;
  680. // update scene graph
  681. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  682. // update camera matrices and frustum
  683. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  684. if ( xr.enabled === true && xr.isPresenting === true ) {
  685. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  686. camera = xr.getCamera(); // use XR camera for rendering
  687. }
  688. //
  689. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  690. currentRenderState = renderStates.get( scene, renderStateStack.length );
  691. currentRenderState.init( camera );
  692. renderStateStack.push( currentRenderState );
  693. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  694. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  695. _localClippingEnabled = this.localClippingEnabled;
  696. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  697. currentRenderList = renderLists.get( scene, renderListStack.length );
  698. currentRenderList.init();
  699. renderListStack.push( currentRenderList );
  700. projectObject( scene, camera, 0, _this.sortObjects );
  701. currentRenderList.finish();
  702. if ( _this.sortObjects === true ) {
  703. currentRenderList.sort( _opaqueSort, _transparentSort );
  704. }
  705. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  706. if ( _renderBackground ) {
  707. background.addToRenderList( currentRenderList, scene );
  708. }
  709. //
  710. this.info.render.frame ++;
  711. if ( _clippingEnabled === true ) clipping.beginShadows();
  712. const shadowsArray = currentRenderState.state.shadowsArray;
  713. shadowMap.render( shadowsArray, scene, camera );
  714. if ( _clippingEnabled === true ) clipping.endShadows();
  715. //
  716. if ( this.info.autoReset === true ) this.info.reset();
  717. // render scene
  718. const opaqueObjects = currentRenderList.opaque;
  719. const transmissiveObjects = currentRenderList.transmissive;
  720. currentRenderState.setupLights( _this._useLegacyLights );
  721. if ( camera.isArrayCamera ) {
  722. const cameras = camera.cameras;
  723. if ( transmissiveObjects.length > 0 ) {
  724. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  725. const camera2 = cameras[ i ];
  726. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  727. }
  728. }
  729. if ( _renderBackground ) background.render( scene );
  730. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  731. const camera2 = cameras[ i ];
  732. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  733. }
  734. } else {
  735. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  736. if ( _renderBackground ) background.render( scene );
  737. renderScene( currentRenderList, scene, camera );
  738. }
  739. //
  740. if ( _currentRenderTarget !== null ) {
  741. // resolve multisample renderbuffers to a single-sample texture if necessary
  742. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  743. // Generate mipmap if we're using any kind of mipmap filtering
  744. textures.updateRenderTargetMipmap( _currentRenderTarget );
  745. }
  746. //
  747. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  748. // _gl.finish();
  749. bindingStates.resetDefaultState();
  750. _currentMaterialId = - 1;
  751. _currentCamera = null;
  752. renderStateStack.pop();
  753. if ( renderStateStack.length > 0 ) {
  754. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  755. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  756. } else {
  757. currentRenderState = null;
  758. }
  759. renderListStack.pop();
  760. if ( renderListStack.length > 0 ) {
  761. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  762. } else {
  763. currentRenderList = null;
  764. }
  765. };
  766. function projectObject( object, camera, groupOrder, sortObjects ) {
  767. if ( object.visible === false ) return;
  768. const visible = object.layers.test( camera.layers );
  769. if ( visible ) {
  770. if ( object.isGroup ) {
  771. groupOrder = object.renderOrder;
  772. } else if ( object.isLOD ) {
  773. if ( object.autoUpdate === true ) object.update( camera );
  774. } else if ( object.isLight ) {
  775. currentRenderState.pushLight( object );
  776. if ( object.castShadow ) {
  777. currentRenderState.pushShadow( object );
  778. }
  779. } else if ( object.isSprite ) {
  780. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  781. if ( sortObjects ) {
  782. _vector3.setFromMatrixPosition( object.matrixWorld )
  783. .applyMatrix4( _projScreenMatrix );
  784. }
  785. const geometry = objects.update( object );
  786. const material = object.material;
  787. if ( material.visible ) {
  788. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  789. }
  790. }
  791. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  792. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  793. const geometry = objects.update( object );
  794. const material = object.material;
  795. if ( sortObjects ) {
  796. if ( object.boundingSphere !== undefined ) {
  797. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  798. _vector3.copy( object.boundingSphere.center );
  799. } else {
  800. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  801. _vector3.copy( geometry.boundingSphere.center );
  802. }
  803. _vector3
  804. .applyMatrix4( object.matrixWorld )
  805. .applyMatrix4( _projScreenMatrix );
  806. }
  807. if ( Array.isArray( material ) ) {
  808. const groups = geometry.groups;
  809. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  810. const group = groups[ i ];
  811. const groupMaterial = material[ group.materialIndex ];
  812. if ( groupMaterial && groupMaterial.visible ) {
  813. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  814. }
  815. }
  816. } else if ( material.visible ) {
  817. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  818. }
  819. }
  820. }
  821. }
  822. const children = object.children;
  823. for ( let i = 0, l = children.length; i < l; i ++ ) {
  824. projectObject( children[ i ], camera, groupOrder, sortObjects );
  825. }
  826. }
  827. function renderScene( currentRenderList, scene, camera, viewport ) {
  828. const opaqueObjects = currentRenderList.opaque;
  829. const transmissiveObjects = currentRenderList.transmissive;
  830. const transparentObjects = currentRenderList.transparent;
  831. currentRenderState.setupLightsView( camera );
  832. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  833. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  834. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  835. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  836. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  837. // Ensure depth buffer writing is enabled so it can be cleared on next render
  838. state.buffers.depth.setTest( true );
  839. state.buffers.depth.setMask( true );
  840. state.buffers.color.setMask( true );
  841. state.setPolygonOffset( false );
  842. }
  843. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  844. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  845. if ( overrideMaterial !== null ) {
  846. return;
  847. }
  848. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  849. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  850. generateMipmaps: true,
  851. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  852. minFilter: LinearMipmapLinearFilter,
  853. samples: 4,
  854. stencilBuffer: stencil,
  855. resolveDepthBuffer: false,
  856. resolveStencilBuffer: false,
  857. colorSpace: ColorManagement.workingColorSpace,
  858. } );
  859. // debug
  860. /*
  861. const geometry = new PlaneGeometry();
  862. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  863. const mesh = new Mesh( geometry, material );
  864. scene.add( mesh );
  865. */
  866. }
  867. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  868. const activeViewport = camera.viewport || _currentViewport;
  869. transmissionRenderTarget.setSize( activeViewport.z, activeViewport.w );
  870. //
  871. const currentRenderTarget = _this.getRenderTarget();
  872. _this.setRenderTarget( transmissionRenderTarget );
  873. _this.getClearColor( _currentClearColor );
  874. _currentClearAlpha = _this.getClearAlpha();
  875. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  876. if ( _renderBackground ) {
  877. background.render( scene );
  878. } else {
  879. _this.clear();
  880. }
  881. // Turn off the features which can affect the frag color for opaque objects pass.
  882. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  883. const currentToneMapping = _this.toneMapping;
  884. _this.toneMapping = NoToneMapping;
  885. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  886. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  887. const currentCameraViewport = camera.viewport;
  888. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  889. currentRenderState.setupLightsView( camera );
  890. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  891. renderObjects( opaqueObjects, scene, camera );
  892. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  893. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  894. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  895. let renderTargetNeedsUpdate = false;
  896. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  897. const renderItem = transmissiveObjects[ i ];
  898. const object = renderItem.object;
  899. const geometry = renderItem.geometry;
  900. const material = renderItem.material;
  901. const group = renderItem.group;
  902. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  903. const currentSide = material.side;
  904. material.side = BackSide;
  905. material.needsUpdate = true;
  906. renderObject( object, scene, camera, geometry, material, group );
  907. material.side = currentSide;
  908. material.needsUpdate = true;
  909. renderTargetNeedsUpdate = true;
  910. }
  911. }
  912. if ( renderTargetNeedsUpdate === true ) {
  913. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  914. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  915. }
  916. }
  917. _this.setRenderTarget( currentRenderTarget );
  918. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  919. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  920. _this.toneMapping = currentToneMapping;
  921. }
  922. function renderObjects( renderList, scene, camera ) {
  923. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  924. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  925. const renderItem = renderList[ i ];
  926. const object = renderItem.object;
  927. const geometry = renderItem.geometry;
  928. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  929. const group = renderItem.group;
  930. if ( object.layers.test( camera.layers ) ) {
  931. renderObject( object, scene, camera, geometry, material, group );
  932. }
  933. }
  934. }
  935. function renderObject( object, scene, camera, geometry, material, group ) {
  936. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  937. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  938. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  939. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  940. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  941. material.side = BackSide;
  942. material.needsUpdate = true;
  943. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  944. material.side = FrontSide;
  945. material.needsUpdate = true;
  946. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  947. material.side = DoubleSide;
  948. } else {
  949. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  950. }
  951. object.onAfterRender( _this, scene, camera, geometry, material, group );
  952. }
  953. function getProgram( material, scene, object ) {
  954. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  955. const materialProperties = properties.get( material );
  956. const lights = currentRenderState.state.lights;
  957. const shadowsArray = currentRenderState.state.shadowsArray;
  958. const lightsStateVersion = lights.state.version;
  959. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  960. const programCacheKey = programCache.getProgramCacheKey( parameters );
  961. let programs = materialProperties.programs;
  962. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  963. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  964. materialProperties.fog = scene.fog;
  965. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  966. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  967. if ( programs === undefined ) {
  968. // new material
  969. material.addEventListener( 'dispose', onMaterialDispose );
  970. programs = new Map();
  971. materialProperties.programs = programs;
  972. }
  973. let program = programs.get( programCacheKey );
  974. if ( program !== undefined ) {
  975. // early out if program and light state is identical
  976. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  977. updateCommonMaterialProperties( material, parameters );
  978. return program;
  979. }
  980. } else {
  981. parameters.uniforms = programCache.getUniforms( material );
  982. material.onBuild( object, parameters, _this );
  983. material.onBeforeCompile( parameters, _this );
  984. program = programCache.acquireProgram( parameters, programCacheKey );
  985. programs.set( programCacheKey, program );
  986. materialProperties.uniforms = parameters.uniforms;
  987. }
  988. const uniforms = materialProperties.uniforms;
  989. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  990. uniforms.clippingPlanes = clipping.uniform;
  991. }
  992. updateCommonMaterialProperties( material, parameters );
  993. // store the light setup it was created for
  994. materialProperties.needsLights = materialNeedsLights( material );
  995. materialProperties.lightsStateVersion = lightsStateVersion;
  996. if ( materialProperties.needsLights ) {
  997. // wire up the material to this renderer's lighting state
  998. uniforms.ambientLightColor.value = lights.state.ambient;
  999. uniforms.lightProbe.value = lights.state.probe;
  1000. uniforms.directionalLights.value = lights.state.directional;
  1001. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  1002. uniforms.spotLights.value = lights.state.spot;
  1003. uniforms.spotLightShadows.value = lights.state.spotShadow;
  1004. uniforms.rectAreaLights.value = lights.state.rectArea;
  1005. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  1006. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  1007. uniforms.pointLights.value = lights.state.point;
  1008. uniforms.pointLightShadows.value = lights.state.pointShadow;
  1009. uniforms.hemisphereLights.value = lights.state.hemi;
  1010. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  1011. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  1012. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  1013. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  1014. uniforms.spotLightMap.value = lights.state.spotLightMap;
  1015. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  1016. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  1017. // TODO (abelnation): add area lights shadow info to uniforms
  1018. }
  1019. materialProperties.currentProgram = program;
  1020. materialProperties.uniformsList = null;
  1021. return program;
  1022. }
  1023. function getUniformList( materialProperties ) {
  1024. if ( materialProperties.uniformsList === null ) {
  1025. const progUniforms = materialProperties.currentProgram.getUniforms();
  1026. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  1027. }
  1028. return materialProperties.uniformsList;
  1029. }
  1030. function updateCommonMaterialProperties( material, parameters ) {
  1031. const materialProperties = properties.get( material );
  1032. materialProperties.outputColorSpace = parameters.outputColorSpace;
  1033. materialProperties.batching = parameters.batching;
  1034. materialProperties.batchingColor = parameters.batchingColor;
  1035. materialProperties.instancing = parameters.instancing;
  1036. materialProperties.instancingColor = parameters.instancingColor;
  1037. materialProperties.instancingMorph = parameters.instancingMorph;
  1038. materialProperties.skinning = parameters.skinning;
  1039. materialProperties.morphTargets = parameters.morphTargets;
  1040. materialProperties.morphNormals = parameters.morphNormals;
  1041. materialProperties.morphColors = parameters.morphColors;
  1042. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  1043. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  1044. materialProperties.numIntersection = parameters.numClipIntersection;
  1045. materialProperties.vertexAlphas = parameters.vertexAlphas;
  1046. materialProperties.vertexTangents = parameters.vertexTangents;
  1047. materialProperties.toneMapping = parameters.toneMapping;
  1048. }
  1049. function setProgram( camera, scene, geometry, material, object ) {
  1050. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  1051. textures.resetTextureUnits();
  1052. const fog = scene.fog;
  1053. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  1054. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  1055. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  1056. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  1057. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  1058. const morphTargets = !! geometry.morphAttributes.position;
  1059. const morphNormals = !! geometry.morphAttributes.normal;
  1060. const morphColors = !! geometry.morphAttributes.color;
  1061. let toneMapping = NoToneMapping;
  1062. if ( material.toneMapped ) {
  1063. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  1064. toneMapping = _this.toneMapping;
  1065. }
  1066. }
  1067. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  1068. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  1069. const materialProperties = properties.get( material );
  1070. const lights = currentRenderState.state.lights;
  1071. if ( _clippingEnabled === true ) {
  1072. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  1073. const useCache =
  1074. camera === _currentCamera &&
  1075. material.id === _currentMaterialId;
  1076. // we might want to call this function with some ClippingGroup
  1077. // object instead of the material, once it becomes feasible
  1078. // (#8465, #8379)
  1079. clipping.setState( material, camera, useCache );
  1080. }
  1081. }
  1082. //
  1083. let needsProgramChange = false;
  1084. if ( material.version === materialProperties.__version ) {
  1085. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  1086. needsProgramChange = true;
  1087. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  1088. needsProgramChange = true;
  1089. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  1090. needsProgramChange = true;
  1091. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  1092. needsProgramChange = true;
  1093. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  1094. needsProgramChange = true;
  1095. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  1096. needsProgramChange = true;
  1097. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  1098. needsProgramChange = true;
  1099. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  1100. needsProgramChange = true;
  1101. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  1102. needsProgramChange = true;
  1103. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  1104. needsProgramChange = true;
  1105. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  1106. needsProgramChange = true;
  1107. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  1108. needsProgramChange = true;
  1109. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  1110. needsProgramChange = true;
  1111. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  1112. needsProgramChange = true;
  1113. } else if ( materialProperties.envMap !== envMap ) {
  1114. needsProgramChange = true;
  1115. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  1116. needsProgramChange = true;
  1117. } else if ( materialProperties.numClippingPlanes !== undefined &&
  1118. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  1119. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  1120. needsProgramChange = true;
  1121. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  1122. needsProgramChange = true;
  1123. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  1124. needsProgramChange = true;
  1125. } else if ( materialProperties.morphTargets !== morphTargets ) {
  1126. needsProgramChange = true;
  1127. } else if ( materialProperties.morphNormals !== morphNormals ) {
  1128. needsProgramChange = true;
  1129. } else if ( materialProperties.morphColors !== morphColors ) {
  1130. needsProgramChange = true;
  1131. } else if ( materialProperties.toneMapping !== toneMapping ) {
  1132. needsProgramChange = true;
  1133. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  1134. needsProgramChange = true;
  1135. }
  1136. } else {
  1137. needsProgramChange = true;
  1138. materialProperties.__version = material.version;
  1139. }
  1140. //
  1141. let program = materialProperties.currentProgram;
  1142. if ( needsProgramChange === true ) {
  1143. program = getProgram( material, scene, object );
  1144. }
  1145. let refreshProgram = false;
  1146. let refreshMaterial = false;
  1147. let refreshLights = false;
  1148. const p_uniforms = program.getUniforms(),
  1149. m_uniforms = materialProperties.uniforms;
  1150. if ( state.useProgram( program.program ) ) {
  1151. refreshProgram = true;
  1152. refreshMaterial = true;
  1153. refreshLights = true;
  1154. }
  1155. if ( material.id !== _currentMaterialId ) {
  1156. _currentMaterialId = material.id;
  1157. refreshMaterial = true;
  1158. }
  1159. if ( refreshProgram || _currentCamera !== camera ) {
  1160. // common camera uniforms
  1161. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  1162. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1163. const uCamPos = p_uniforms.map.cameraPosition;
  1164. if ( uCamPos !== undefined ) {
  1165. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1166. }
  1167. if ( capabilities.logarithmicDepthBuffer ) {
  1168. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1169. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1170. }
  1171. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  1172. if ( material.isMeshPhongMaterial ||
  1173. material.isMeshToonMaterial ||
  1174. material.isMeshLambertMaterial ||
  1175. material.isMeshBasicMaterial ||
  1176. material.isMeshStandardMaterial ||
  1177. material.isShaderMaterial ) {
  1178. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  1179. }
  1180. if ( _currentCamera !== camera ) {
  1181. _currentCamera = camera;
  1182. // lighting uniforms depend on the camera so enforce an update
  1183. // now, in case this material supports lights - or later, when
  1184. // the next material that does gets activated:
  1185. refreshMaterial = true; // set to true on material change
  1186. refreshLights = true; // remains set until update done
  1187. }
  1188. }
  1189. // skinning and morph target uniforms must be set even if material didn't change
  1190. // auto-setting of texture unit for bone and morph texture must go before other textures
  1191. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  1192. if ( object.isSkinnedMesh ) {
  1193. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1194. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1195. const skeleton = object.skeleton;
  1196. if ( skeleton ) {
  1197. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  1198. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  1199. }
  1200. }
  1201. if ( object.isBatchedMesh ) {
  1202. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  1203. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  1204. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  1205. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  1206. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  1207. if ( object._colorsTexture !== null ) {
  1208. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  1209. }
  1210. }
  1211. const morphAttributes = geometry.morphAttributes;
  1212. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  1213. morphtargets.update( object, geometry, program );
  1214. }
  1215. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  1216. materialProperties.receiveShadow = object.receiveShadow;
  1217. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  1218. }
  1219. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  1220. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  1221. m_uniforms.envMap.value = envMap;
  1222. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  1223. }
  1224. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  1225. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  1226. }
  1227. if ( refreshMaterial ) {
  1228. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  1229. if ( materialProperties.needsLights ) {
  1230. // the current material requires lighting info
  1231. // note: all lighting uniforms are always set correctly
  1232. // they simply reference the renderer's state for their
  1233. // values
  1234. //
  1235. // use the current material's .needsUpdate flags to set
  1236. // the GL state when required
  1237. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1238. }
  1239. // refresh uniforms common to several materials
  1240. if ( fog && material.fog === true ) {
  1241. materials.refreshFogUniforms( m_uniforms, fog );
  1242. }
  1243. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  1244. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  1245. }
  1246. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  1247. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  1248. material.uniformsNeedUpdate = false;
  1249. }
  1250. if ( material.isSpriteMaterial ) {
  1251. p_uniforms.setValue( _gl, 'center', object.center );
  1252. }
  1253. // common matrices
  1254. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1255. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1256. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1257. // UBOs
  1258. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  1259. const groups = material.uniformsGroups;
  1260. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  1261. const group = groups[ i ];
  1262. uniformsGroups.update( group, program );
  1263. uniformsGroups.bind( group, program );
  1264. }
  1265. }
  1266. return program;
  1267. }
  1268. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1269. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1270. uniforms.ambientLightColor.needsUpdate = value;
  1271. uniforms.lightProbe.needsUpdate = value;
  1272. uniforms.directionalLights.needsUpdate = value;
  1273. uniforms.directionalLightShadows.needsUpdate = value;
  1274. uniforms.pointLights.needsUpdate = value;
  1275. uniforms.pointLightShadows.needsUpdate = value;
  1276. uniforms.spotLights.needsUpdate = value;
  1277. uniforms.spotLightShadows.needsUpdate = value;
  1278. uniforms.rectAreaLights.needsUpdate = value;
  1279. uniforms.hemisphereLights.needsUpdate = value;
  1280. }
  1281. function materialNeedsLights( material ) {
  1282. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  1283. material.isMeshStandardMaterial || material.isShadowMaterial ||
  1284. ( material.isShaderMaterial && material.lights === true );
  1285. }
  1286. this.getActiveCubeFace = function () {
  1287. return _currentActiveCubeFace;
  1288. };
  1289. this.getActiveMipmapLevel = function () {
  1290. return _currentActiveMipmapLevel;
  1291. };
  1292. this.getRenderTarget = function () {
  1293. return _currentRenderTarget;
  1294. };
  1295. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  1296. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  1297. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  1298. const renderTargetProperties = properties.get( renderTarget );
  1299. renderTargetProperties.__hasExternalTextures = true;
  1300. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  1301. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  1302. // The multisample_render_to_texture extension doesn't work properly if there
  1303. // are midframe flushes and an external depth buffer. Disable use of the extension.
  1304. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  1305. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  1306. renderTargetProperties.__useRenderToTexture = false;
  1307. }
  1308. }
  1309. };
  1310. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  1311. const renderTargetProperties = properties.get( renderTarget );
  1312. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  1313. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  1314. };
  1315. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  1316. _currentRenderTarget = renderTarget;
  1317. _currentActiveCubeFace = activeCubeFace;
  1318. _currentActiveMipmapLevel = activeMipmapLevel;
  1319. let useDefaultFramebuffer = true;
  1320. let framebuffer = null;
  1321. let isCube = false;
  1322. let isRenderTarget3D = false;
  1323. if ( renderTarget ) {
  1324. const renderTargetProperties = properties.get( renderTarget );
  1325. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  1326. // We need to make sure to rebind the framebuffer.
  1327. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1328. useDefaultFramebuffer = false;
  1329. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  1330. textures.setupRenderTarget( renderTarget );
  1331. } else if ( renderTargetProperties.__hasExternalTextures ) {
  1332. // Color and depth texture must be rebound in order for the swapchain to update.
  1333. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  1334. }
  1335. const texture = renderTarget.texture;
  1336. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  1337. isRenderTarget3D = true;
  1338. }
  1339. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1340. if ( renderTarget.isWebGLCubeRenderTarget ) {
  1341. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  1342. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  1343. } else {
  1344. framebuffer = __webglFramebuffer[ activeCubeFace ];
  1345. }
  1346. isCube = true;
  1347. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  1348. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  1349. } else {
  1350. if ( Array.isArray( __webglFramebuffer ) ) {
  1351. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  1352. } else {
  1353. framebuffer = __webglFramebuffer;
  1354. }
  1355. }
  1356. _currentViewport.copy( renderTarget.viewport );
  1357. _currentScissor.copy( renderTarget.scissor );
  1358. _currentScissorTest = renderTarget.scissorTest;
  1359. } else {
  1360. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  1361. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  1362. _currentScissorTest = _scissorTest;
  1363. }
  1364. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1365. if ( framebufferBound && useDefaultFramebuffer ) {
  1366. state.drawBuffers( renderTarget, framebuffer );
  1367. }
  1368. state.viewport( _currentViewport );
  1369. state.scissor( _currentScissor );
  1370. state.setScissorTest( _currentScissorTest );
  1371. if ( isCube ) {
  1372. const textureProperties = properties.get( renderTarget.texture );
  1373. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  1374. } else if ( isRenderTarget3D ) {
  1375. const textureProperties = properties.get( renderTarget.texture );
  1376. const layer = activeCubeFace || 0;
  1377. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  1378. }
  1379. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  1380. };
  1381. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1382. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1383. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1384. return;
  1385. }
  1386. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1387. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  1388. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1389. }
  1390. if ( framebuffer ) {
  1391. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1392. try {
  1393. const texture = renderTarget.texture;
  1394. const textureFormat = texture.format;
  1395. const textureType = texture.type;
  1396. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  1397. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1398. return;
  1399. }
  1400. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  1401. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1402. return;
  1403. }
  1404. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1405. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1406. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  1407. }
  1408. } finally {
  1409. // restore framebuffer of current render target if necessary
  1410. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  1411. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1412. }
  1413. }
  1414. };
  1415. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1416. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1417. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1418. }
  1419. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1420. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  1421. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1422. }
  1423. if ( framebuffer ) {
  1424. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1425. try {
  1426. const texture = renderTarget.texture;
  1427. const textureFormat = texture.format;
  1428. const textureType = texture.type;
  1429. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  1430. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  1431. }
  1432. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  1433. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1434. }
  1435. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1436. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1437. const glBuffer = _gl.createBuffer();
  1438. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  1439. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  1440. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  1441. _gl.flush();
  1442. // check if the commands have finished every 8 ms
  1443. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  1444. await probeAsync( _gl, sync, 4 );
  1445. try {
  1446. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  1447. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  1448. } finally {
  1449. _gl.deleteBuffer( glBuffer );
  1450. _gl.deleteSync( sync );
  1451. }
  1452. return buffer;
  1453. }
  1454. } finally {
  1455. // restore framebuffer of current render target if necessary
  1456. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  1457. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1458. }
  1459. }
  1460. };
  1461. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  1462. // support previous signature with position first
  1463. if ( texture.isTexture !== true ) {
  1464. // @deprecated, r165
  1465. console.warn( 'WebGLRenderer: copyFramebufferToTexture function signature has changed.' );
  1466. position = arguments[ 0 ] || null;
  1467. texture = arguments[ 1 ];
  1468. }
  1469. const levelScale = Math.pow( 2, - level );
  1470. const width = Math.floor( texture.image.width * levelScale );
  1471. const height = Math.floor( texture.image.height * levelScale );
  1472. const x = position !== null ? position.x : 0;
  1473. const y = position !== null ? position.y : 0;
  1474. textures.setTexture2D( texture, 0 );
  1475. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  1476. state.unbindTexture();
  1477. };
  1478. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  1479. // support previous signature with dstPosition first
  1480. if ( srcTexture.isTexture !== true ) {
  1481. // @deprecated, r165
  1482. console.warn( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  1483. dstPosition = arguments[ 0 ] || null;
  1484. srcTexture = arguments[ 1 ];
  1485. dstTexture = arguments[ 2 ];
  1486. level = arguments[ 3 ] || 0;
  1487. srcRegion = null;
  1488. }
  1489. let width, height, minX, minY;
  1490. let dstX, dstY;
  1491. if ( srcRegion !== null ) {
  1492. width = srcRegion.max.x - srcRegion.min.x;
  1493. height = srcRegion.max.y - srcRegion.min.y;
  1494. minX = srcRegion.min.x;
  1495. minY = srcRegion.min.y;
  1496. } else {
  1497. width = srcTexture.image.width;
  1498. height = srcTexture.image.height;
  1499. minX = 0;
  1500. minY = 0;
  1501. }
  1502. if ( dstPosition !== null ) {
  1503. dstX = dstPosition.x;
  1504. dstY = dstPosition.y;
  1505. } else {
  1506. dstX = 0;
  1507. dstY = 0;
  1508. }
  1509. const glFormat = utils.convert( dstTexture.format );
  1510. const glType = utils.convert( dstTexture.type );
  1511. textures.setTexture2D( dstTexture, 0 );
  1512. // As another texture upload may have changed pixelStorei
  1513. // parameters, make sure they are correct for the dstTexture
  1514. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  1515. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  1516. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  1517. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  1518. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  1519. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  1520. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  1521. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  1522. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  1523. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  1524. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  1525. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  1526. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  1527. if ( srcTexture.isDataTexture ) {
  1528. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  1529. } else {
  1530. if ( srcTexture.isCompressedTexture ) {
  1531. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  1532. } else {
  1533. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, glFormat, glType, image );
  1534. }
  1535. }
  1536. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  1537. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  1538. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  1539. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  1540. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  1541. // Generate mipmaps only when copying level 0
  1542. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1543. state.unbindTexture();
  1544. };
  1545. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  1546. // support previous signature with source box first
  1547. if ( srcTexture.isTexture !== true ) {
  1548. // @deprecated, r165
  1549. console.warn( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  1550. srcRegion = arguments[ 0 ] || null;
  1551. dstPosition = arguments[ 1 ] || null;
  1552. srcTexture = arguments[ 2 ];
  1553. dstTexture = arguments[ 3 ];
  1554. level = arguments[ 4 ] || 0;
  1555. }
  1556. let width, height, depth, minX, minY, minZ;
  1557. let dstX, dstY, dstZ;
  1558. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  1559. if ( srcRegion !== null ) {
  1560. width = srcRegion.max.x - srcRegion.min.x;
  1561. height = srcRegion.max.y - srcRegion.min.y;
  1562. depth = srcRegion.max.z - srcRegion.min.z;
  1563. minX = srcRegion.min.x;
  1564. minY = srcRegion.min.y;
  1565. minZ = srcRegion.min.z;
  1566. } else {
  1567. width = image.width;
  1568. height = image.height;
  1569. depth = image.depth;
  1570. minX = 0;
  1571. minY = 0;
  1572. minZ = 0;
  1573. }
  1574. if ( dstPosition !== null ) {
  1575. dstX = dstPosition.x;
  1576. dstY = dstPosition.y;
  1577. dstZ = dstPosition.z;
  1578. } else {
  1579. dstX = 0;
  1580. dstY = 0;
  1581. dstZ = 0;
  1582. }
  1583. const glFormat = utils.convert( dstTexture.format );
  1584. const glType = utils.convert( dstTexture.type );
  1585. let glTarget;
  1586. if ( dstTexture.isData3DTexture ) {
  1587. textures.setTexture3D( dstTexture, 0 );
  1588. glTarget = _gl.TEXTURE_3D;
  1589. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  1590. textures.setTexture2DArray( dstTexture, 0 );
  1591. glTarget = _gl.TEXTURE_2D_ARRAY;
  1592. } else {
  1593. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  1594. return;
  1595. }
  1596. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  1597. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  1598. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  1599. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  1600. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  1601. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  1602. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  1603. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  1604. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  1605. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  1606. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  1607. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  1608. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  1609. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  1610. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  1611. } else {
  1612. if ( dstTexture.isCompressedArrayTexture ) {
  1613. _gl.compressedTexSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  1614. } else {
  1615. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  1616. }
  1617. }
  1618. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  1619. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  1620. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  1621. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  1622. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  1623. // Generate mipmaps only when copying level 0
  1624. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  1625. state.unbindTexture();
  1626. };
  1627. this.initRenderTarget = function ( target ) {
  1628. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  1629. textures.setupRenderTarget( target );
  1630. }
  1631. };
  1632. this.initTexture = function ( texture ) {
  1633. if ( texture.isCubeTexture ) {
  1634. textures.setTextureCube( texture, 0 );
  1635. } else if ( texture.isData3DTexture ) {
  1636. textures.setTexture3D( texture, 0 );
  1637. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  1638. textures.setTexture2DArray( texture, 0 );
  1639. } else {
  1640. textures.setTexture2D( texture, 0 );
  1641. }
  1642. state.unbindTexture();
  1643. };
  1644. this.resetState = function () {
  1645. _currentActiveCubeFace = 0;
  1646. _currentActiveMipmapLevel = 0;
  1647. _currentRenderTarget = null;
  1648. state.reset();
  1649. bindingStates.reset();
  1650. };
  1651. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  1652. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  1653. }
  1654. }
  1655. get coordinateSystem() {
  1656. return WebGLCoordinateSystem;
  1657. }
  1658. get outputColorSpace() {
  1659. return this._outputColorSpace;
  1660. }
  1661. set outputColorSpace( colorSpace ) {
  1662. this._outputColorSpace = colorSpace;
  1663. const gl = this.getContext();
  1664. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  1665. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  1666. }
  1667. get useLegacyLights() { // @deprecated, r155
  1668. 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.' );
  1669. return this._useLegacyLights;
  1670. }
  1671. set useLegacyLights( value ) { // @deprecated, r155
  1672. 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.' );
  1673. this._useLegacyLights = value;
  1674. }
  1675. }
  1676. export { WebGLRenderer };
粤ICP备19079148号