WebGLRenderer.js 62 KB

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