WebGLRenderer.js 59 KB

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