WebGLRenderer.js 59 KB

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