WebGLRenderer.js 61 KB

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