WebGLRenderer.js 65 KB

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