WebGLRenderer.js 58 KB

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