WebGLRenderer.js 58 KB

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