WebGLRenderer.js 62 KB

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