WebGLRenderer.js 60 KB

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