WebGLRenderer.js 67 KB

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