1
0

WebGLRenderer.js 59 KB

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