WebGLRenderer.js 64 KB

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