WebGLRenderer.js 61 KB

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