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