WebGLRenderer.js 60 KB

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