WebGLRenderer.js 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855
  1. /**
  2. * @author supereggbert / http://www.paulbrunt.co.uk/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author alteredq / http://alteredqualia.com/
  5. * @author szimek / https://github.com/szimek/
  6. * @author tschw
  7. */
  8. THREE.WebGLRenderer = function ( parameters ) {
  9. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10. parameters = parameters || {};
  11. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12. _context = parameters.context !== undefined ? parameters.context : null,
  13. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  17. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  18. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  19. var lights = [];
  20. var opaqueObjects = [];
  21. var opaqueObjectsLastIndex = - 1;
  22. var transparentObjects = [];
  23. var transparentObjectsLastIndex = - 1;
  24. var morphInfluences = new Float32Array( 8 );
  25. var sprites = [];
  26. var lensFlares = [];
  27. // public properties
  28. this.domElement = _canvas;
  29. this.context = null;
  30. // clearing
  31. this.autoClear = true;
  32. this.autoClearColor = true;
  33. this.autoClearDepth = true;
  34. this.autoClearStencil = true;
  35. // scene graph
  36. this.sortObjects = true;
  37. // user-defined clipping
  38. this.clippingPlanes = [];
  39. this.localClippingEnabled = false;
  40. // physically based shading
  41. this.gammaFactor = 2.0; // for backwards compatibility
  42. this.gammaInput = false;
  43. this.gammaOutput = false;
  44. // physical lights
  45. this.physicallyCorrectLights = false;
  46. // tone mapping
  47. this.toneMapping = THREE.LinearToneMapping;
  48. this.toneMappingExposure = 1.0;
  49. this.toneMappingWhitePoint = 1.0;
  50. // morphs
  51. this.maxMorphTargets = 8;
  52. this.maxMorphNormals = 4;
  53. // flags
  54. this.autoScaleCubemaps = true;
  55. // internal properties
  56. var _this = this,
  57. // internal state cache
  58. _currentProgram = null,
  59. _currentRenderTarget = null,
  60. _currentFramebuffer = null,
  61. _currentMaterialId = - 1,
  62. _currentGeometryProgram = '',
  63. _currentCamera = null,
  64. _currentScissor = new THREE.Vector4(),
  65. _currentScissorTest = null,
  66. _currentViewport = new THREE.Vector4(),
  67. //
  68. _usedTextureUnits = 0,
  69. //
  70. _clearColor = new THREE.Color( 0x000000 ),
  71. _clearAlpha = 0,
  72. _width = _canvas.width,
  73. _height = _canvas.height,
  74. _pixelRatio = 1,
  75. _scissor = new THREE.Vector4( 0, 0, _width, _height ),
  76. _scissorTest = false,
  77. _viewport = new THREE.Vector4( 0, 0, _width, _height ),
  78. // frustum
  79. _frustum = new THREE.Frustum(),
  80. // clipping
  81. _clippingEnabled = false,
  82. _localClippingEnabled = false,
  83. _clipRenderingShadows = false,
  84. _numClippingPlanes = 0,
  85. _clippingPlanesUniform = {
  86. type: '4fv', value: null, needsUpdate: false },
  87. _globalClippingState = null,
  88. _numGlobalClippingPlanes = 0,
  89. _matrix3 = new THREE.Matrix3(),
  90. _sphere = new THREE.Sphere(),
  91. _plane = new THREE.Plane(),
  92. // camera matrices cache
  93. _projScreenMatrix = new THREE.Matrix4(),
  94. _vector3 = new THREE.Vector3(),
  95. // light arrays cache
  96. _lights = {
  97. hash: '',
  98. ambient: [ 0, 0, 0 ],
  99. directional: [],
  100. directionalShadowMap: [],
  101. directionalShadowMatrix: [],
  102. spot: [],
  103. spotShadowMap: [],
  104. spotShadowMatrix: [],
  105. point: [],
  106. pointShadowMap: [],
  107. pointShadowMatrix: [],
  108. hemi: [],
  109. shadows: []
  110. },
  111. // info
  112. _infoMemory = {
  113. geometries: 0,
  114. textures: 0
  115. },
  116. _infoRender = {
  117. calls: 0,
  118. vertices: 0,
  119. faces: 0,
  120. points: 0
  121. };
  122. this.info = {
  123. render: _infoRender,
  124. memory: _infoMemory,
  125. programs: null
  126. };
  127. // initialize
  128. var _gl;
  129. try {
  130. var attributes = {
  131. alpha: _alpha,
  132. depth: _depth,
  133. stencil: _stencil,
  134. antialias: _antialias,
  135. premultipliedAlpha: _premultipliedAlpha,
  136. preserveDrawingBuffer: _preserveDrawingBuffer
  137. };
  138. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  139. if ( _gl === null ) {
  140. if ( _canvas.getContext( 'webgl' ) !== null ) {
  141. throw 'Error creating WebGL context with your selected attributes.';
  142. } else {
  143. throw 'Error creating WebGL context.';
  144. }
  145. }
  146. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  147. if ( _gl.getShaderPrecisionFormat === undefined ) {
  148. _gl.getShaderPrecisionFormat = function () {
  149. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  150. };
  151. }
  152. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  153. } catch ( error ) {
  154. console.error( 'THREE.WebGLRenderer: ' + error );
  155. }
  156. var extensions = new THREE.WebGLExtensions( _gl );
  157. extensions.get( 'OES_texture_float' );
  158. extensions.get( 'OES_texture_float_linear' );
  159. extensions.get( 'OES_texture_half_float' );
  160. extensions.get( 'OES_texture_half_float_linear' );
  161. extensions.get( 'OES_standard_derivatives' );
  162. extensions.get( 'ANGLE_instanced_arrays' );
  163. if ( extensions.get( 'OES_element_index_uint' ) ) {
  164. THREE.BufferGeometry.MaxIndex = 4294967296;
  165. }
  166. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  167. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  168. var properties = new THREE.WebGLProperties();
  169. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  170. var programCache = new THREE.WebGLPrograms( this, capabilities );
  171. var lightCache = new THREE.WebGLLights();
  172. this.info.programs = programCache.programs;
  173. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  174. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  175. //
  176. function getTargetPixelRatio() {
  177. return _currentRenderTarget === null ? _pixelRatio : 1;
  178. }
  179. function glClearColor( r, g, b, a ) {
  180. if ( _premultipliedAlpha === true ) {
  181. r *= a; g *= a; b *= a;
  182. }
  183. state.clearColor( r, g, b, a );
  184. }
  185. function setDefaultGLState() {
  186. state.init();
  187. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  188. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  189. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  190. }
  191. function resetGLState() {
  192. _currentProgram = null;
  193. _currentCamera = null;
  194. _currentGeometryProgram = '';
  195. _currentMaterialId = - 1;
  196. state.reset();
  197. }
  198. setDefaultGLState();
  199. this.context = _gl;
  200. this.capabilities = capabilities;
  201. this.extensions = extensions;
  202. this.properties = properties;
  203. this.state = state;
  204. // shadow map
  205. var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
  206. this.shadowMap = shadowMap;
  207. // Plugins
  208. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  209. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  210. // API
  211. this.getContext = function () {
  212. return _gl;
  213. };
  214. this.getContextAttributes = function () {
  215. return _gl.getContextAttributes();
  216. };
  217. this.forceContextLoss = function () {
  218. extensions.get( 'WEBGL_lose_context' ).loseContext();
  219. };
  220. this.getMaxAnisotropy = ( function () {
  221. var value;
  222. return function getMaxAnisotropy() {
  223. if ( value !== undefined ) return value;
  224. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  225. if ( extension !== null ) {
  226. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  227. } else {
  228. value = 0;
  229. }
  230. return value;
  231. };
  232. } )();
  233. this.getPrecision = function () {
  234. return capabilities.precision;
  235. };
  236. this.getPixelRatio = function () {
  237. return _pixelRatio;
  238. };
  239. this.setPixelRatio = function ( value ) {
  240. if ( value === undefined ) return;
  241. _pixelRatio = value;
  242. this.setSize( _viewport.z, _viewport.w, false );
  243. };
  244. this.getSize = function () {
  245. return {
  246. width: _width,
  247. height: _height
  248. };
  249. };
  250. this.setSize = function ( width, height, updateStyle ) {
  251. _width = width;
  252. _height = height;
  253. _canvas.width = width * _pixelRatio;
  254. _canvas.height = height * _pixelRatio;
  255. if ( updateStyle !== false ) {
  256. _canvas.style.width = width + 'px';
  257. _canvas.style.height = height + 'px';
  258. }
  259. this.setViewport( 0, 0, width, height );
  260. };
  261. this.setViewport = function ( x, y, width, height ) {
  262. state.viewport( _viewport.set( x, y, width, height ) );
  263. };
  264. this.setScissor = function ( x, y, width, height ) {
  265. state.scissor( _scissor.set( x, y, width, height ) );
  266. };
  267. this.setScissorTest = function ( boolean ) {
  268. state.setScissorTest( _scissorTest = boolean );
  269. };
  270. // Clearing
  271. this.getClearColor = function () {
  272. return _clearColor;
  273. };
  274. this.setClearColor = function ( color, alpha ) {
  275. _clearColor.set( color );
  276. _clearAlpha = alpha !== undefined ? alpha : 1;
  277. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  278. };
  279. this.getClearAlpha = function () {
  280. return _clearAlpha;
  281. };
  282. this.setClearAlpha = function ( alpha ) {
  283. _clearAlpha = alpha;
  284. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  285. };
  286. this.clear = function ( color, depth, stencil ) {
  287. var bits = 0;
  288. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  289. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  290. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  291. _gl.clear( bits );
  292. };
  293. this.clearColor = function () {
  294. this.clear( true, false, false );
  295. };
  296. this.clearDepth = function () {
  297. this.clear( false, true, false );
  298. };
  299. this.clearStencil = function () {
  300. this.clear( false, false, true );
  301. };
  302. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  303. this.setRenderTarget( renderTarget );
  304. this.clear( color, depth, stencil );
  305. };
  306. // Reset
  307. this.resetGLState = resetGLState;
  308. this.dispose = function() {
  309. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  310. };
  311. // Events
  312. function onContextLost( event ) {
  313. event.preventDefault();
  314. resetGLState();
  315. setDefaultGLState();
  316. properties.clear();
  317. }
  318. function onTextureDispose( event ) {
  319. var texture = event.target;
  320. texture.removeEventListener( 'dispose', onTextureDispose );
  321. deallocateTexture( texture );
  322. _infoMemory.textures --;
  323. }
  324. function onRenderTargetDispose( event ) {
  325. var renderTarget = event.target;
  326. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  327. deallocateRenderTarget( renderTarget );
  328. _infoMemory.textures --;
  329. }
  330. function onMaterialDispose( event ) {
  331. var material = event.target;
  332. material.removeEventListener( 'dispose', onMaterialDispose );
  333. deallocateMaterial( material );
  334. }
  335. // Buffer deallocation
  336. function deallocateTexture( texture ) {
  337. var textureProperties = properties.get( texture );
  338. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  339. // cube texture
  340. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  341. } else {
  342. // 2D texture
  343. if ( textureProperties.__webglInit === undefined ) return;
  344. _gl.deleteTexture( textureProperties.__webglTexture );
  345. }
  346. // remove all webgl properties
  347. properties.delete( texture );
  348. }
  349. function deallocateRenderTarget( renderTarget ) {
  350. var renderTargetProperties = properties.get( renderTarget );
  351. var textureProperties = properties.get( renderTarget.texture );
  352. if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
  353. _gl.deleteTexture( textureProperties.__webglTexture );
  354. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  355. for ( var i = 0; i < 6; i ++ ) {
  356. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  357. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  358. }
  359. } else {
  360. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  361. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  362. }
  363. properties.delete( renderTarget.texture );
  364. properties.delete( renderTarget );
  365. }
  366. function deallocateMaterial( material ) {
  367. releaseMaterialProgramReference( material );
  368. properties.delete( material );
  369. }
  370. function releaseMaterialProgramReference( material ) {
  371. var programInfo = properties.get( material ).program;
  372. material.program = undefined;
  373. if ( programInfo !== undefined ) {
  374. programCache.releaseProgram( programInfo );
  375. }
  376. }
  377. // Buffer rendering
  378. this.renderBufferImmediate = function ( object, program, material ) {
  379. state.initAttributes();
  380. var buffers = properties.get( object );
  381. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  382. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  383. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  384. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  385. var attributes = program.getAttributes();
  386. if ( object.hasPositions ) {
  387. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  388. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  389. state.enableAttribute( attributes.position );
  390. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  391. }
  392. if ( object.hasNormals ) {
  393. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  394. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) {
  395. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  396. var array = object.normalArray;
  397. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  398. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  399. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  400. array[ i + 0 ] = nx;
  401. array[ i + 1 ] = ny;
  402. array[ i + 2 ] = nz;
  403. array[ i + 3 ] = nx;
  404. array[ i + 4 ] = ny;
  405. array[ i + 5 ] = nz;
  406. array[ i + 6 ] = nx;
  407. array[ i + 7 ] = ny;
  408. array[ i + 8 ] = nz;
  409. }
  410. }
  411. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  412. state.enableAttribute( attributes.normal );
  413. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  414. }
  415. if ( object.hasUvs && material.map ) {
  416. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  417. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  418. state.enableAttribute( attributes.uv );
  419. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  420. }
  421. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  422. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  423. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  424. state.enableAttribute( attributes.color );
  425. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  426. }
  427. state.disableUnusedAttributes();
  428. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  429. object.count = 0;
  430. };
  431. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  432. setMaterial( material );
  433. var program = setProgram( camera, fog, material, object );
  434. var updateBuffers = false;
  435. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  436. if ( geometryProgram !== _currentGeometryProgram ) {
  437. _currentGeometryProgram = geometryProgram;
  438. updateBuffers = true;
  439. }
  440. // morph targets
  441. var morphTargetInfluences = object.morphTargetInfluences;
  442. if ( morphTargetInfluences !== undefined ) {
  443. var activeInfluences = [];
  444. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  445. var influence = morphTargetInfluences[ i ];
  446. activeInfluences.push( [ influence, i ] );
  447. }
  448. activeInfluences.sort( absNumericalSort );
  449. if ( activeInfluences.length > 8 ) {
  450. activeInfluences.length = 8;
  451. }
  452. var morphAttributes = geometry.morphAttributes;
  453. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  454. var influence = activeInfluences[ i ];
  455. morphInfluences[ i ] = influence[ 0 ];
  456. if ( influence[ 0 ] !== 0 ) {
  457. var index = influence[ 1 ];
  458. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  459. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  460. } else {
  461. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  462. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  463. }
  464. }
  465. var uniforms = program.getUniforms();
  466. if ( uniforms.morphTargetInfluences !== null ) {
  467. _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  468. }
  469. updateBuffers = true;
  470. }
  471. //
  472. var index = geometry.index;
  473. var position = geometry.attributes.position;
  474. if ( material.wireframe === true ) {
  475. index = objects.getWireframeAttribute( geometry );
  476. }
  477. var renderer;
  478. if ( index !== null ) {
  479. renderer = indexedBufferRenderer;
  480. renderer.setIndex( index );
  481. } else {
  482. renderer = bufferRenderer;
  483. }
  484. if ( updateBuffers ) {
  485. setupVertexAttributes( material, program, geometry );
  486. if ( index !== null ) {
  487. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  488. }
  489. }
  490. //
  491. var dataStart = 0;
  492. var dataCount = Infinity;
  493. if ( index !== null ) {
  494. dataCount = index.count;
  495. } else if ( position !== undefined ) {
  496. dataCount = position.count;
  497. }
  498. var rangeStart = geometry.drawRange.start;
  499. var rangeCount = geometry.drawRange.count;
  500. var groupStart = group !== null ? group.start : 0;
  501. var groupCount = group !== null ? group.count : Infinity;
  502. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  503. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  504. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  505. //
  506. if ( object instanceof THREE.Mesh ) {
  507. if ( material.wireframe === true ) {
  508. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  509. renderer.setMode( _gl.LINES );
  510. } else {
  511. switch ( object.drawMode ) {
  512. case THREE.TrianglesDrawMode:
  513. renderer.setMode( _gl.TRIANGLES );
  514. break;
  515. case THREE.TriangleStripDrawMode:
  516. renderer.setMode( _gl.TRIANGLE_STRIP );
  517. break;
  518. case THREE.TriangleFanDrawMode:
  519. renderer.setMode( _gl.TRIANGLE_FAN );
  520. break;
  521. }
  522. }
  523. } else if ( object instanceof THREE.Line ) {
  524. var lineWidth = material.linewidth;
  525. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  526. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  527. if ( object instanceof THREE.LineSegments ) {
  528. renderer.setMode( _gl.LINES );
  529. } else {
  530. renderer.setMode( _gl.LINE_STRIP );
  531. }
  532. } else if ( object instanceof THREE.Points ) {
  533. renderer.setMode( _gl.POINTS );
  534. }
  535. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  536. if ( geometry.maxInstancedCount > 0 ) {
  537. renderer.renderInstances( geometry, drawStart, drawCount );
  538. }
  539. } else {
  540. renderer.render( drawStart, drawCount );
  541. }
  542. };
  543. function setupVertexAttributes( material, program, geometry, startIndex ) {
  544. var extension;
  545. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  546. extension = extensions.get( 'ANGLE_instanced_arrays' );
  547. if ( extension === null ) {
  548. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  549. return;
  550. }
  551. }
  552. if ( startIndex === undefined ) startIndex = 0;
  553. state.initAttributes();
  554. var geometryAttributes = geometry.attributes;
  555. var programAttributes = program.getAttributes();
  556. var materialDefaultAttributeValues = material.defaultAttributeValues;
  557. for ( var name in programAttributes ) {
  558. var programAttribute = programAttributes[ name ];
  559. if ( programAttribute >= 0 ) {
  560. var geometryAttribute = geometryAttributes[ name ];
  561. if ( geometryAttribute !== undefined ) {
  562. var size = geometryAttribute.itemSize;
  563. var buffer = objects.getAttributeBuffer( geometryAttribute );
  564. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  565. var data = geometryAttribute.data;
  566. var stride = data.stride;
  567. var offset = geometryAttribute.offset;
  568. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  569. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  570. if ( geometry.maxInstancedCount === undefined ) {
  571. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  572. }
  573. } else {
  574. state.enableAttribute( programAttribute );
  575. }
  576. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  577. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  578. } else {
  579. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  580. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  581. if ( geometry.maxInstancedCount === undefined ) {
  582. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  583. }
  584. } else {
  585. state.enableAttribute( programAttribute );
  586. }
  587. var type = _gl.FLOAT;
  588. var normalized = false;
  589. var array = geometryAttribute.array;
  590. if ( array instanceof Uint8Array ) {
  591. type = _gl.UNSIGNED_BYTE;
  592. normalized = true;
  593. }
  594. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  595. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * array.BYTES_PER_ELEMENT );
  596. }
  597. } else if ( materialDefaultAttributeValues !== undefined ) {
  598. var value = materialDefaultAttributeValues[ name ];
  599. if ( value !== undefined ) {
  600. switch ( value.length ) {
  601. case 2:
  602. _gl.vertexAttrib2fv( programAttribute, value );
  603. break;
  604. case 3:
  605. _gl.vertexAttrib3fv( programAttribute, value );
  606. break;
  607. case 4:
  608. _gl.vertexAttrib4fv( programAttribute, value );
  609. break;
  610. default:
  611. _gl.vertexAttrib1fv( programAttribute, value );
  612. }
  613. }
  614. }
  615. }
  616. }
  617. state.disableUnusedAttributes();
  618. }
  619. // Sorting
  620. function absNumericalSort( a, b ) {
  621. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  622. }
  623. function painterSortStable ( a, b ) {
  624. if ( a.object.renderOrder !== b.object.renderOrder ) {
  625. return a.object.renderOrder - b.object.renderOrder;
  626. } else if ( a.material.id !== b.material.id ) {
  627. return a.material.id - b.material.id;
  628. } else if ( a.z !== b.z ) {
  629. return a.z - b.z;
  630. } else {
  631. return a.id - b.id;
  632. }
  633. }
  634. function reversePainterSortStable ( a, b ) {
  635. if ( a.object.renderOrder !== b.object.renderOrder ) {
  636. return a.object.renderOrder - b.object.renderOrder;
  637. } if ( a.z !== b.z ) {
  638. return b.z - a.z;
  639. } else {
  640. return a.id - b.id;
  641. }
  642. }
  643. // Rendering
  644. this.render = function ( scene, camera, renderTarget, forceClear ) {
  645. if ( camera instanceof THREE.Camera === false ) {
  646. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  647. return;
  648. }
  649. var fog = scene.fog;
  650. // reset caching for this frame
  651. _currentGeometryProgram = '';
  652. _currentMaterialId = - 1;
  653. _currentCamera = null;
  654. // update scene graph
  655. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  656. // update camera matrices and frustum
  657. if ( camera.parent === null ) camera.updateMatrixWorld();
  658. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  659. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  660. _frustum.setFromMatrix( _projScreenMatrix );
  661. lights.length = 0;
  662. opaqueObjectsLastIndex = - 1;
  663. transparentObjectsLastIndex = - 1;
  664. sprites.length = 0;
  665. lensFlares.length = 0;
  666. setupGlobalClippingPlanes( this.clippingPlanes, camera );
  667. projectObject( scene, camera );
  668. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  669. transparentObjects.length = transparentObjectsLastIndex + 1;
  670. if ( _this.sortObjects === true ) {
  671. opaqueObjects.sort( painterSortStable );
  672. transparentObjects.sort( reversePainterSortStable );
  673. }
  674. //
  675. if ( _clippingEnabled ) {
  676. _clipRenderingShadows = true;
  677. setupClippingPlanes( null );
  678. }
  679. setupShadows( lights );
  680. shadowMap.render( scene, camera );
  681. setupLights( lights, camera );
  682. if ( _clippingEnabled ) {
  683. _clipRenderingShadows = false;
  684. resetGlobalClippingState();
  685. }
  686. //
  687. _infoRender.calls = 0;
  688. _infoRender.vertices = 0;
  689. _infoRender.faces = 0;
  690. _infoRender.points = 0;
  691. if ( renderTarget === undefined ) {
  692. renderTarget = null;
  693. }
  694. this.setRenderTarget( renderTarget );
  695. if ( this.autoClear || forceClear ) {
  696. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  697. }
  698. //
  699. if ( scene.overrideMaterial ) {
  700. var overrideMaterial = scene.overrideMaterial;
  701. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  702. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  703. } else {
  704. // opaque pass (front-to-back order)
  705. state.setBlending( THREE.NoBlending );
  706. renderObjects( opaqueObjects, camera, fog );
  707. // transparent pass (back-to-front order)
  708. renderObjects( transparentObjects, camera, fog );
  709. }
  710. // custom render plugins (post pass)
  711. spritePlugin.render( scene, camera );
  712. lensFlarePlugin.render( scene, camera, _currentViewport );
  713. // Generate mipmap if we're using any kind of mipmap filtering
  714. if ( renderTarget ) {
  715. var texture = renderTarget.texture;
  716. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  717. texture.minFilter !== THREE.NearestFilter &&
  718. texture.minFilter !== THREE.LinearFilter ) {
  719. updateRenderTargetMipmap( renderTarget );
  720. }
  721. }
  722. // Ensure depth buffer writing is enabled so it can be cleared on next render
  723. state.setDepthTest( true );
  724. state.setDepthWrite( true );
  725. state.setColorWrite( true );
  726. // _gl.finish();
  727. };
  728. function pushRenderItem( object, geometry, material, z, group ) {
  729. var array, index;
  730. // allocate the next position in the appropriate array
  731. if ( material.transparent ) {
  732. array = transparentObjects;
  733. index = ++ transparentObjectsLastIndex;
  734. } else {
  735. array = opaqueObjects;
  736. index = ++ opaqueObjectsLastIndex;
  737. }
  738. // recycle existing render item or grow the array
  739. var renderItem = array[ index ];
  740. if ( renderItem !== undefined ) {
  741. renderItem.id = object.id;
  742. renderItem.object = object;
  743. renderItem.geometry = geometry;
  744. renderItem.material = material;
  745. renderItem.z = _vector3.z;
  746. renderItem.group = group;
  747. } else {
  748. renderItem = {
  749. id: object.id,
  750. object: object,
  751. geometry: geometry,
  752. material: material,
  753. z: _vector3.z,
  754. group: group
  755. };
  756. // assert( index === array.length );
  757. array.push( renderItem );
  758. }
  759. }
  760. function isObjectViewable( object ) {
  761. var geometry = object.geometry;
  762. if ( geometry.boundingSphere === null )
  763. geometry.computeBoundingSphere();
  764. var sphere = _sphere.
  765. copy( geometry.boundingSphere ).
  766. applyMatrix4( object.matrixWorld );
  767. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  768. if ( _numClippingPlanes === 0 ) return true;
  769. var planes = _this.clippingPlanes,
  770. center = sphere.center,
  771. negRad = - sphere.radius,
  772. i = 0;
  773. do {
  774. // out when deeper than radius in the negative halfspace
  775. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  776. } while ( ++ i !== _numClippingPlanes );
  777. return true;
  778. }
  779. function projectObject( object, camera ) {
  780. if ( object.visible === false ) return;
  781. if ( object.layers.test( camera.layers ) ) {
  782. if ( object instanceof THREE.Light ) {
  783. lights.push( object );
  784. } else if ( object instanceof THREE.Sprite ) {
  785. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  786. sprites.push( object );
  787. }
  788. } else if ( object instanceof THREE.LensFlare ) {
  789. lensFlares.push( object );
  790. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  791. if ( _this.sortObjects === true ) {
  792. _vector3.setFromMatrixPosition( object.matrixWorld );
  793. _vector3.applyProjection( _projScreenMatrix );
  794. }
  795. pushRenderItem( object, null, object.material, _vector3.z, null );
  796. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  797. if ( object instanceof THREE.SkinnedMesh ) {
  798. object.skeleton.update();
  799. }
  800. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  801. var material = object.material;
  802. if ( material.visible === true ) {
  803. if ( _this.sortObjects === true ) {
  804. _vector3.setFromMatrixPosition( object.matrixWorld );
  805. _vector3.applyProjection( _projScreenMatrix );
  806. }
  807. var geometry = objects.update( object );
  808. if ( material instanceof THREE.MultiMaterial ) {
  809. var groups = geometry.groups;
  810. var materials = material.materials;
  811. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  812. var group = groups[ i ];
  813. var groupMaterial = materials[ group.materialIndex ];
  814. if ( groupMaterial.visible === true ) {
  815. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  816. }
  817. }
  818. } else {
  819. pushRenderItem( object, geometry, material, _vector3.z, null );
  820. }
  821. }
  822. }
  823. }
  824. }
  825. var children = object.children;
  826. for ( var i = 0, l = children.length; i < l; i ++ ) {
  827. projectObject( children[ i ], camera );
  828. }
  829. }
  830. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  831. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  832. var renderItem = renderList[ i ];
  833. var object = renderItem.object;
  834. var geometry = renderItem.geometry;
  835. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  836. var group = renderItem.group;
  837. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  838. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  839. if ( object instanceof THREE.ImmediateRenderObject ) {
  840. setMaterial( material );
  841. var program = setProgram( camera, fog, material, object );
  842. _currentGeometryProgram = '';
  843. object.render( function ( object ) {
  844. _this.renderBufferImmediate( object, program, material );
  845. } );
  846. } else {
  847. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  848. }
  849. }
  850. }
  851. function initMaterial( material, fog, object ) {
  852. var materialProperties = properties.get( material );
  853. var parameters = programCache.getParameters(
  854. material, _lights, fog, _numClippingPlanes, object );
  855. var code = programCache.getProgramCode( material, parameters );
  856. var program = materialProperties.program;
  857. var programChange = true;
  858. if ( program === undefined ) {
  859. // new material
  860. material.addEventListener( 'dispose', onMaterialDispose );
  861. } else if ( program.code !== code ) {
  862. // changed glsl or parameters
  863. releaseMaterialProgramReference( material );
  864. } else if ( parameters.shaderID !== undefined ) {
  865. // same glsl and uniform list
  866. return;
  867. } else {
  868. // only rebuild uniform list
  869. programChange = false;
  870. }
  871. if ( programChange ) {
  872. if ( parameters.shaderID ) {
  873. var shader = THREE.ShaderLib[ parameters.shaderID ];
  874. materialProperties.__webglShader = {
  875. name: material.type,
  876. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  877. vertexShader: shader.vertexShader,
  878. fragmentShader: shader.fragmentShader
  879. };
  880. } else {
  881. materialProperties.__webglShader = {
  882. name: material.type,
  883. uniforms: material.uniforms,
  884. vertexShader: material.vertexShader,
  885. fragmentShader: material.fragmentShader
  886. };
  887. }
  888. material.__webglShader = materialProperties.__webglShader;
  889. program = programCache.acquireProgram( material, parameters, code );
  890. materialProperties.program = program;
  891. material.program = program;
  892. }
  893. var attributes = program.getAttributes();
  894. if ( material.morphTargets ) {
  895. material.numSupportedMorphTargets = 0;
  896. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  897. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  898. material.numSupportedMorphTargets ++;
  899. }
  900. }
  901. }
  902. if ( material.morphNormals ) {
  903. material.numSupportedMorphNormals = 0;
  904. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  905. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  906. material.numSupportedMorphNormals ++;
  907. }
  908. }
  909. }
  910. var uniforms = materialProperties.__webglShader.uniforms;
  911. if ( ! ( material instanceof THREE.ShaderMaterial ) &&
  912. ! ( material instanceof THREE.RawShaderMaterial ) ||
  913. material.clipping === true ) {
  914. materialProperties.numClippingPlanes = _numClippingPlanes;
  915. uniforms.clippingPlanes = _clippingPlanesUniform;
  916. }
  917. var uniformLocations = materialProperties.program.getUniforms();
  918. materialProperties.uniformsList = [];
  919. for ( var u in uniforms ) {
  920. var location = uniformLocations[ u ];
  921. if ( location ) {
  922. materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
  923. }
  924. }
  925. if ( material instanceof THREE.MeshPhongMaterial ||
  926. material instanceof THREE.MeshLambertMaterial ||
  927. material instanceof THREE.MeshStandardMaterial ||
  928. material.lights ) {
  929. // store the light setup it was created for
  930. materialProperties.lightsHash = _lights.hash;
  931. // wire up the material to this renderer's lighting state
  932. uniforms.ambientLightColor.value = _lights.ambient;
  933. uniforms.directionalLights.value = _lights.directional;
  934. uniforms.spotLights.value = _lights.spot;
  935. uniforms.pointLights.value = _lights.point;
  936. uniforms.hemisphereLights.value = _lights.hemi;
  937. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  938. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  939. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  940. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  941. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  942. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  943. }
  944. // detect dynamic uniforms
  945. materialProperties.hasDynamicUniforms = false;
  946. for ( var j = 0, jl = materialProperties.uniformsList.length; j < jl; j ++ ) {
  947. var uniform = materialProperties.uniformsList[ j ][ 0 ];
  948. if ( uniform.dynamic === true ) {
  949. materialProperties.hasDynamicUniforms = true;
  950. break;
  951. }
  952. }
  953. }
  954. function setMaterial( material ) {
  955. setMaterialFaces( material );
  956. if ( material.transparent === true ) {
  957. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  958. } else {
  959. state.setBlending( THREE.NoBlending );
  960. }
  961. state.setDepthFunc( material.depthFunc );
  962. state.setDepthTest( material.depthTest );
  963. state.setDepthWrite( material.depthWrite );
  964. state.setColorWrite( material.colorWrite );
  965. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  966. }
  967. function setMaterialFaces( material ) {
  968. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  969. state.setFlipSided( material.side === THREE.BackSide );
  970. }
  971. function setProgram( camera, fog, material, object ) {
  972. _usedTextureUnits = 0;
  973. var materialProperties = properties.get( material );
  974. if ( _clippingEnabled ) {
  975. if ( _localClippingEnabled || camera !== _currentCamera ) {
  976. var useCache =
  977. camera === _currentCamera &&
  978. material.id === _currentMaterialId;
  979. // we might want to call this function with some ClippingGroup
  980. // object instead of the material, once it becomes feasible
  981. // (#8465, #8379)
  982. setClippingState(
  983. material.clippingPlanes, material.clipShadows,
  984. camera, materialProperties, useCache );
  985. }
  986. if ( materialProperties.numClippingPlanes !== undefined &&
  987. materialProperties.numClippingPlanes !== _numClippingPlanes ) {
  988. material.needsUpdate = true;
  989. }
  990. }
  991. if ( materialProperties.program === undefined ) {
  992. material.needsUpdate = true;
  993. }
  994. if ( materialProperties.lightsHash !== undefined &&
  995. materialProperties.lightsHash !== _lights.hash ) {
  996. material.needsUpdate = true;
  997. }
  998. if ( material.needsUpdate ) {
  999. initMaterial( material, fog, object );
  1000. material.needsUpdate = false;
  1001. }
  1002. var refreshProgram = false;
  1003. var refreshMaterial = false;
  1004. var refreshLights = false;
  1005. var program = materialProperties.program,
  1006. p_uniforms = program.getUniforms(),
  1007. m_uniforms = materialProperties.__webglShader.uniforms;
  1008. if ( program.id !== _currentProgram ) {
  1009. _gl.useProgram( program.program );
  1010. _currentProgram = program.id;
  1011. refreshProgram = true;
  1012. refreshMaterial = true;
  1013. refreshLights = true;
  1014. }
  1015. if ( material.id !== _currentMaterialId ) {
  1016. _currentMaterialId = material.id;
  1017. refreshMaterial = true;
  1018. }
  1019. if ( refreshProgram || camera !== _currentCamera ) {
  1020. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  1021. if ( capabilities.logarithmicDepthBuffer ) {
  1022. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1023. }
  1024. if ( camera !== _currentCamera ) {
  1025. _currentCamera = camera;
  1026. // lighting uniforms depend on the camera so enforce an update
  1027. // now, in case this material supports lights - or later, when
  1028. // the next material that does gets activated:
  1029. refreshMaterial = true; // set to true on material change
  1030. refreshLights = true; // remains set until update done
  1031. }
  1032. // load material specific uniforms
  1033. // (shader material also gets them for the sake of genericity)
  1034. if ( material instanceof THREE.ShaderMaterial ||
  1035. material instanceof THREE.MeshPhongMaterial ||
  1036. material instanceof THREE.MeshStandardMaterial ||
  1037. material.envMap ) {
  1038. if ( p_uniforms.cameraPosition !== undefined ) {
  1039. _vector3.setFromMatrixPosition( camera.matrixWorld );
  1040. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  1041. }
  1042. }
  1043. if ( material instanceof THREE.MeshPhongMaterial ||
  1044. material instanceof THREE.MeshLambertMaterial ||
  1045. material instanceof THREE.MeshBasicMaterial ||
  1046. material instanceof THREE.MeshStandardMaterial ||
  1047. material instanceof THREE.ShaderMaterial ||
  1048. material.skinning ) {
  1049. if ( p_uniforms.viewMatrix !== undefined ) {
  1050. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  1051. }
  1052. }
  1053. if ( p_uniforms.toneMappingExposure !== undefined ) {
  1054. _gl.uniform1f( p_uniforms.toneMappingExposure, _this.toneMappingExposure );
  1055. }
  1056. if ( p_uniforms.toneMappingWhitePoint !== undefined ) {
  1057. _gl.uniform1f( p_uniforms.toneMappingWhitePoint, _this.toneMappingWhitePoint );
  1058. }
  1059. }
  1060. // skinning uniforms must be set even if material didn't change
  1061. // auto-setting of texture unit for bone texture must go before other textures
  1062. // not sure why, but otherwise weird things happen
  1063. if ( material.skinning ) {
  1064. if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
  1065. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  1066. }
  1067. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
  1068. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  1069. }
  1070. if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  1071. if ( p_uniforms.boneTexture !== undefined ) {
  1072. var textureUnit = getTextureUnit();
  1073. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  1074. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  1075. }
  1076. if ( p_uniforms.boneTextureWidth !== undefined ) {
  1077. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  1078. }
  1079. if ( p_uniforms.boneTextureHeight !== undefined ) {
  1080. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  1081. }
  1082. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  1083. if ( p_uniforms.boneGlobalMatrices !== undefined ) {
  1084. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  1085. }
  1086. }
  1087. }
  1088. if ( refreshMaterial ) {
  1089. if ( material instanceof THREE.MeshPhongMaterial ||
  1090. material instanceof THREE.MeshLambertMaterial ||
  1091. material instanceof THREE.MeshStandardMaterial ||
  1092. material.lights ) {
  1093. // the current material requires lighting info
  1094. // note: all lighting uniforms are always set correctly
  1095. // they simply reference the renderer's state for their
  1096. // values
  1097. //
  1098. // use the current material's .needsUpdate flags to set
  1099. // the GL state when required
  1100. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1101. }
  1102. // refresh uniforms common to several materials
  1103. if ( fog && material.fog ) {
  1104. refreshUniformsFog( m_uniforms, fog );
  1105. }
  1106. if ( material instanceof THREE.MeshBasicMaterial ||
  1107. material instanceof THREE.MeshLambertMaterial ||
  1108. material instanceof THREE.MeshPhongMaterial ||
  1109. material instanceof THREE.MeshStandardMaterial ) {
  1110. refreshUniformsCommon( m_uniforms, material );
  1111. }
  1112. // refresh single material specific uniforms
  1113. if ( material instanceof THREE.LineBasicMaterial ) {
  1114. refreshUniformsLine( m_uniforms, material );
  1115. } else if ( material instanceof THREE.LineDashedMaterial ) {
  1116. refreshUniformsLine( m_uniforms, material );
  1117. refreshUniformsDash( m_uniforms, material );
  1118. } else if ( material instanceof THREE.PointsMaterial ) {
  1119. refreshUniformsPoints( m_uniforms, material );
  1120. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  1121. refreshUniformsLambert( m_uniforms, material );
  1122. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  1123. refreshUniformsPhong( m_uniforms, material );
  1124. } else if ( material instanceof THREE.MeshPhysicalMaterial ) {
  1125. refreshUniformsPhysical( m_uniforms, material );
  1126. } else if ( material instanceof THREE.MeshStandardMaterial ) {
  1127. refreshUniformsStandard( m_uniforms, material );
  1128. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  1129. m_uniforms.mNear.value = camera.near;
  1130. m_uniforms.mFar.value = camera.far;
  1131. m_uniforms.opacity.value = material.opacity;
  1132. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  1133. m_uniforms.opacity.value = material.opacity;
  1134. }
  1135. // load common uniforms
  1136. loadUniformsGeneric( materialProperties.uniformsList );
  1137. }
  1138. loadUniformsMatrices( p_uniforms, object );
  1139. if ( p_uniforms.modelMatrix !== undefined ) {
  1140. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  1141. }
  1142. if ( materialProperties.hasDynamicUniforms === true ) {
  1143. updateDynamicUniforms( materialProperties.uniformsList, object, camera );
  1144. }
  1145. return program;
  1146. }
  1147. function updateDynamicUniforms ( uniforms, object, camera ) {
  1148. var dynamicUniforms = [];
  1149. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  1150. var uniform = uniforms[ j ][ 0 ];
  1151. var onUpdateCallback = uniform.onUpdateCallback;
  1152. if ( onUpdateCallback !== undefined ) {
  1153. onUpdateCallback.bind( uniform )( object, camera );
  1154. dynamicUniforms.push( uniforms[ j ] );
  1155. }
  1156. }
  1157. loadUniformsGeneric( dynamicUniforms );
  1158. }
  1159. // Uniforms (refresh uniforms objects)
  1160. function refreshUniformsCommon ( uniforms, material ) {
  1161. uniforms.opacity.value = material.opacity;
  1162. uniforms.diffuse.value = material.color;
  1163. if ( material.emissive ) {
  1164. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1165. }
  1166. uniforms.map.value = material.map;
  1167. uniforms.specularMap.value = material.specularMap;
  1168. uniforms.alphaMap.value = material.alphaMap;
  1169. if ( material.aoMap ) {
  1170. uniforms.aoMap.value = material.aoMap;
  1171. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1172. }
  1173. // uv repeat and offset setting priorities
  1174. // 1. color map
  1175. // 2. specular map
  1176. // 3. normal map
  1177. // 4. bump map
  1178. // 5. alpha map
  1179. // 6. emissive map
  1180. var uvScaleMap;
  1181. if ( material.map ) {
  1182. uvScaleMap = material.map;
  1183. } else if ( material.specularMap ) {
  1184. uvScaleMap = material.specularMap;
  1185. } else if ( material.displacementMap ) {
  1186. uvScaleMap = material.displacementMap;
  1187. } else if ( material.normalMap ) {
  1188. uvScaleMap = material.normalMap;
  1189. } else if ( material.bumpMap ) {
  1190. uvScaleMap = material.bumpMap;
  1191. } else if ( material.roughnessMap ) {
  1192. uvScaleMap = material.roughnessMap;
  1193. } else if ( material.metalnessMap ) {
  1194. uvScaleMap = material.metalnessMap;
  1195. } else if ( material.alphaMap ) {
  1196. uvScaleMap = material.alphaMap;
  1197. } else if ( material.emissiveMap ) {
  1198. uvScaleMap = material.emissiveMap;
  1199. }
  1200. if ( uvScaleMap !== undefined ) {
  1201. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {
  1202. uvScaleMap = uvScaleMap.texture;
  1203. }
  1204. var offset = uvScaleMap.offset;
  1205. var repeat = uvScaleMap.repeat;
  1206. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1207. }
  1208. uniforms.envMap.value = material.envMap;
  1209. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  1210. uniforms.reflectivity.value = material.reflectivity;
  1211. uniforms.refractionRatio.value = material.refractionRatio;
  1212. }
  1213. function refreshUniformsLine ( uniforms, material ) {
  1214. uniforms.diffuse.value = material.color;
  1215. uniforms.opacity.value = material.opacity;
  1216. }
  1217. function refreshUniformsDash ( uniforms, material ) {
  1218. uniforms.dashSize.value = material.dashSize;
  1219. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1220. uniforms.scale.value = material.scale;
  1221. }
  1222. function refreshUniformsPoints ( uniforms, material ) {
  1223. uniforms.diffuse.value = material.color;
  1224. uniforms.opacity.value = material.opacity;
  1225. uniforms.size.value = material.size * _pixelRatio;
  1226. uniforms.scale.value = _canvas.clientHeight * 0.5;
  1227. uniforms.map.value = material.map;
  1228. if ( material.map !== null ) {
  1229. var offset = material.map.offset;
  1230. var repeat = material.map.repeat;
  1231. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1232. }
  1233. }
  1234. function refreshUniformsFog ( uniforms, fog ) {
  1235. uniforms.fogColor.value = fog.color;
  1236. if ( fog instanceof THREE.Fog ) {
  1237. uniforms.fogNear.value = fog.near;
  1238. uniforms.fogFar.value = fog.far;
  1239. } else if ( fog instanceof THREE.FogExp2 ) {
  1240. uniforms.fogDensity.value = fog.density;
  1241. }
  1242. }
  1243. function refreshUniformsLambert ( uniforms, material ) {
  1244. if ( material.lightMap ) {
  1245. uniforms.lightMap.value = material.lightMap;
  1246. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1247. }
  1248. if ( material.emissiveMap ) {
  1249. uniforms.emissiveMap.value = material.emissiveMap;
  1250. }
  1251. }
  1252. function refreshUniformsPhong ( uniforms, material ) {
  1253. uniforms.specular.value = material.specular;
  1254. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1255. if ( material.lightMap ) {
  1256. uniforms.lightMap.value = material.lightMap;
  1257. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1258. }
  1259. if ( material.emissiveMap ) {
  1260. uniforms.emissiveMap.value = material.emissiveMap;
  1261. }
  1262. if ( material.bumpMap ) {
  1263. uniforms.bumpMap.value = material.bumpMap;
  1264. uniforms.bumpScale.value = material.bumpScale;
  1265. }
  1266. if ( material.normalMap ) {
  1267. uniforms.normalMap.value = material.normalMap;
  1268. uniforms.normalScale.value.copy( material.normalScale );
  1269. }
  1270. if ( material.displacementMap ) {
  1271. uniforms.displacementMap.value = material.displacementMap;
  1272. uniforms.displacementScale.value = material.displacementScale;
  1273. uniforms.displacementBias.value = material.displacementBias;
  1274. }
  1275. }
  1276. function refreshUniformsStandard ( uniforms, material ) {
  1277. uniforms.roughness.value = material.roughness;
  1278. uniforms.metalness.value = material.metalness;
  1279. if ( material.roughnessMap ) {
  1280. uniforms.roughnessMap.value = material.roughnessMap;
  1281. }
  1282. if ( material.metalnessMap ) {
  1283. uniforms.metalnessMap.value = material.metalnessMap;
  1284. }
  1285. if ( material.lightMap ) {
  1286. uniforms.lightMap.value = material.lightMap;
  1287. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1288. }
  1289. if ( material.emissiveMap ) {
  1290. uniforms.emissiveMap.value = material.emissiveMap;
  1291. }
  1292. if ( material.bumpMap ) {
  1293. uniforms.bumpMap.value = material.bumpMap;
  1294. uniforms.bumpScale.value = material.bumpScale;
  1295. }
  1296. if ( material.normalMap ) {
  1297. uniforms.normalMap.value = material.normalMap;
  1298. uniforms.normalScale.value.copy( material.normalScale );
  1299. }
  1300. if ( material.displacementMap ) {
  1301. uniforms.displacementMap.value = material.displacementMap;
  1302. uniforms.displacementScale.value = material.displacementScale;
  1303. uniforms.displacementBias.value = material.displacementBias;
  1304. }
  1305. if ( material.envMap ) {
  1306. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1307. uniforms.envMapIntensity.value = material.envMapIntensity;
  1308. }
  1309. }
  1310. function refreshUniformsPhysical ( uniforms, material ) {
  1311. refreshUniformsStandard( uniforms, material );
  1312. }
  1313. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1314. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  1315. uniforms.ambientLightColor.needsUpdate = value;
  1316. uniforms.directionalLights.needsUpdate = value;
  1317. uniforms.pointLights.needsUpdate = value;
  1318. uniforms.spotLights.needsUpdate = value;
  1319. uniforms.hemisphereLights.needsUpdate = value;
  1320. }
  1321. // Uniforms (load to GPU)
  1322. function loadUniformsMatrices ( uniforms, object ) {
  1323. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
  1324. if ( uniforms.normalMatrix ) {
  1325. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
  1326. }
  1327. }
  1328. function getTextureUnit() {
  1329. var textureUnit = _usedTextureUnits;
  1330. if ( textureUnit >= capabilities.maxTextures ) {
  1331. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  1332. }
  1333. _usedTextureUnits += 1;
  1334. return textureUnit;
  1335. }
  1336. function loadUniform( uniform, type, location, value ) {
  1337. var texture, textureUnit;
  1338. if ( type === '1i' ) {
  1339. _gl.uniform1i( location, value );
  1340. } else if ( type === '1f' ) {
  1341. _gl.uniform1f( location, value );
  1342. } else if ( type === '2f' ) {
  1343. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  1344. } else if ( type === '3f' ) {
  1345. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  1346. } else if ( type === '4f' ) {
  1347. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  1348. } else if ( type === '1iv' ) {
  1349. _gl.uniform1iv( location, value );
  1350. } else if ( type === '3iv' ) {
  1351. _gl.uniform3iv( location, value );
  1352. } else if ( type === '1fv' ) {
  1353. _gl.uniform1fv( location, value );
  1354. } else if ( type === '2fv' ) {
  1355. _gl.uniform2fv( location, value );
  1356. } else if ( type === '3fv' ) {
  1357. _gl.uniform3fv( location, value );
  1358. } else if ( type === '4fv' ) {
  1359. _gl.uniform4fv( location, value );
  1360. } else if ( type === 'Matrix2fv' ) {
  1361. _gl.uniformMatrix2fv( location, false, value );
  1362. } else if ( type === 'Matrix3fv' ) {
  1363. _gl.uniformMatrix3fv( location, false, value );
  1364. } else if ( type === 'Matrix4fv' ) {
  1365. _gl.uniformMatrix4fv( location, false, value );
  1366. //
  1367. } else if ( type === 'i' ) {
  1368. // console.warn( 'THREE.WebGLRenderer: Uniform "i" is now "1i".' );
  1369. _gl.uniform1i( location, value );
  1370. } else if ( type === 'f' ) {
  1371. // console.warn( 'THREE.WebGLRenderer: Uniform "f" is now "1f".' );
  1372. _gl.uniform1f( location, value );
  1373. } else if ( type === 'iv1' ) {
  1374. // console.warn( 'THREE.WebGLRenderer: Uniform "iv1" is now "1iv".' );
  1375. _gl.uniform1iv( location, value );
  1376. } else if ( type === 'iv' ) {
  1377. // console.warn( 'THREE.WebGLRenderer: Uniform "iv" is now "3iv".' );
  1378. _gl.uniform3iv( location, value );
  1379. } else if ( type === 'fv1' ) {
  1380. // console.warn( 'THREE.WebGLRenderer: Uniform "fv1" is now "1fv".' );
  1381. _gl.uniform1fv( location, value );
  1382. } else if ( type === 'fv' ) {
  1383. // console.warn( 'THREE.WebGLRenderer: Uniform "fv" is now "3fv".' );
  1384. _gl.uniform3fv( location, value );
  1385. } else if ( type === 'v2' ) {
  1386. // single THREE.Vector2
  1387. _gl.uniform2f( location, value.x, value.y );
  1388. } else if ( type === 'v3' ) {
  1389. // single THREE.Vector3
  1390. _gl.uniform3f( location, value.x, value.y, value.z );
  1391. } else if ( type === 'v4' ) {
  1392. // single THREE.Vector4
  1393. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  1394. } else if ( type === 'c' ) {
  1395. // single THREE.Color
  1396. _gl.uniform3f( location, value.r, value.g, value.b );
  1397. } else if ( type === 's' ) {
  1398. // TODO: Optimize this
  1399. var properties = uniform.properties;
  1400. for ( var name in properties ) {
  1401. var property = properties[ name ];
  1402. var locationProperty = location[ name ];
  1403. var valueProperty = value[ name ];
  1404. loadUniform( property, property.type, locationProperty, valueProperty );
  1405. }
  1406. } else if ( type === 'sa' ) {
  1407. // TODO: Optimize this
  1408. var properties = uniform.properties;
  1409. for ( var i = 0, l = value.length; i < l; i ++ ) {
  1410. for ( var name in properties ) {
  1411. var property = properties[ name ];
  1412. var locationProperty = location[ i ][ name ];
  1413. var valueProperty = value[ i ][ name ];
  1414. loadUniform( property, property.type, locationProperty, valueProperty );
  1415. }
  1416. }
  1417. } else if ( type === 'v2v' ) {
  1418. // array of THREE.Vector2
  1419. if ( uniform._array === undefined ) {
  1420. uniform._array = new Float32Array( 2 * value.length );
  1421. }
  1422. for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
  1423. uniform._array[ i2 + 0 ] = value[ i ].x;
  1424. uniform._array[ i2 + 1 ] = value[ i ].y;
  1425. }
  1426. _gl.uniform2fv( location, uniform._array );
  1427. } else if ( type === 'v3v' ) {
  1428. // array of THREE.Vector3
  1429. if ( uniform._array === undefined ) {
  1430. uniform._array = new Float32Array( 3 * value.length );
  1431. }
  1432. for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
  1433. uniform._array[ i3 + 0 ] = value[ i ].x;
  1434. uniform._array[ i3 + 1 ] = value[ i ].y;
  1435. uniform._array[ i3 + 2 ] = value[ i ].z;
  1436. }
  1437. _gl.uniform3fv( location, uniform._array );
  1438. } else if ( type === 'v4v' ) {
  1439. // array of THREE.Vector4
  1440. if ( uniform._array === undefined ) {
  1441. uniform._array = new Float32Array( 4 * value.length );
  1442. }
  1443. for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
  1444. uniform._array[ i4 + 0 ] = value[ i ].x;
  1445. uniform._array[ i4 + 1 ] = value[ i ].y;
  1446. uniform._array[ i4 + 2 ] = value[ i ].z;
  1447. uniform._array[ i4 + 3 ] = value[ i ].w;
  1448. }
  1449. _gl.uniform4fv( location, uniform._array );
  1450. } else if ( type === 'm2' ) {
  1451. // single THREE.Matrix2
  1452. _gl.uniformMatrix2fv( location, false, value.elements );
  1453. } else if ( type === 'm3' ) {
  1454. // single THREE.Matrix3
  1455. _gl.uniformMatrix3fv( location, false, value.elements );
  1456. } else if ( type === 'm3v' ) {
  1457. // array of THREE.Matrix3
  1458. if ( uniform._array === undefined ) {
  1459. uniform._array = new Float32Array( 9 * value.length );
  1460. }
  1461. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1462. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  1463. }
  1464. _gl.uniformMatrix3fv( location, false, uniform._array );
  1465. } else if ( type === 'm4' ) {
  1466. // single THREE.Matrix4
  1467. _gl.uniformMatrix4fv( location, false, value.elements );
  1468. } else if ( type === 'm4v' ) {
  1469. // array of THREE.Matrix4
  1470. if ( uniform._array === undefined ) {
  1471. uniform._array = new Float32Array( 16 * value.length );
  1472. }
  1473. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1474. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  1475. }
  1476. _gl.uniformMatrix4fv( location, false, uniform._array );
  1477. } else if ( type === 't' ) {
  1478. // single THREE.Texture (2d or cube)
  1479. texture = value;
  1480. textureUnit = getTextureUnit();
  1481. _gl.uniform1i( location, textureUnit );
  1482. if ( ! texture ) return;
  1483. if ( texture instanceof THREE.CubeTexture ||
  1484. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  1485. // CompressedTexture can have Array in image :/
  1486. setCubeTexture( texture, textureUnit );
  1487. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  1488. setCubeTextureDynamic( texture.texture, textureUnit );
  1489. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  1490. _this.setTexture( texture.texture, textureUnit );
  1491. } else {
  1492. _this.setTexture( texture, textureUnit );
  1493. }
  1494. } else if ( type === 'tv' ) {
  1495. // array of THREE.Texture (2d or cube)
  1496. if ( uniform._array === undefined ) {
  1497. uniform._array = [];
  1498. }
  1499. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  1500. uniform._array[ i ] = getTextureUnit();
  1501. }
  1502. _gl.uniform1iv( location, uniform._array );
  1503. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  1504. texture = uniform.value[ i ];
  1505. textureUnit = uniform._array[ i ];
  1506. if ( ! texture ) continue;
  1507. if ( texture instanceof THREE.CubeTexture ||
  1508. ( texture.image instanceof Array && texture.image.length === 6 ) ) {
  1509. // CompressedTexture can have Array in image :/
  1510. setCubeTexture( texture, textureUnit );
  1511. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  1512. _this.setTexture( texture.texture, textureUnit );
  1513. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  1514. setCubeTextureDynamic( texture.texture, textureUnit );
  1515. } else {
  1516. _this.setTexture( texture, textureUnit );
  1517. }
  1518. }
  1519. } else {
  1520. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  1521. }
  1522. }
  1523. function loadUniformsGeneric( uniforms ) {
  1524. for ( var i = 0, l = uniforms.length; i < l; i ++ ) {
  1525. var uniform = uniforms[ i ][ 0 ];
  1526. // needsUpdate property is not added to all uniforms.
  1527. if ( uniform.needsUpdate === false ) continue;
  1528. var type = uniform.type;
  1529. var location = uniforms[ i ][ 1 ];
  1530. var value = uniform.value;
  1531. loadUniform( uniform, type, location, value );
  1532. }
  1533. }
  1534. function setupShadows ( lights ) {
  1535. var lightShadowsLength = 0;
  1536. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  1537. var light = lights[ i ];
  1538. if ( light.castShadow ) {
  1539. _lights.shadows[ lightShadowsLength ++ ] = light;
  1540. }
  1541. }
  1542. _lights.shadows.length = lightShadowsLength;
  1543. }
  1544. function setupLights ( lights, camera ) {
  1545. var l, ll, light,
  1546. r = 0, g = 0, b = 0,
  1547. color,
  1548. intensity,
  1549. distance,
  1550. viewMatrix = camera.matrixWorldInverse,
  1551. directionalLength = 0,
  1552. pointLength = 0,
  1553. spotLength = 0,
  1554. hemiLength = 0;
  1555. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  1556. light = lights[ l ];
  1557. color = light.color;
  1558. intensity = light.intensity;
  1559. distance = light.distance;
  1560. if ( light instanceof THREE.AmbientLight ) {
  1561. r += color.r * intensity;
  1562. g += color.g * intensity;
  1563. b += color.b * intensity;
  1564. } else if ( light instanceof THREE.DirectionalLight ) {
  1565. var uniforms = lightCache.get( light );
  1566. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1567. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1568. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1569. uniforms.direction.sub( _vector3 );
  1570. uniforms.direction.transformDirection( viewMatrix );
  1571. uniforms.shadow = light.castShadow;
  1572. if ( light.castShadow ) {
  1573. uniforms.shadowBias = light.shadow.bias;
  1574. uniforms.shadowRadius = light.shadow.radius;
  1575. uniforms.shadowMapSize = light.shadow.mapSize;
  1576. }
  1577. _lights.directionalShadowMap[ directionalLength ] = light.shadow.map;
  1578. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  1579. _lights.directional[ directionalLength ++ ] = uniforms;
  1580. } else if ( light instanceof THREE.SpotLight ) {
  1581. var uniforms = lightCache.get( light );
  1582. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1583. uniforms.position.applyMatrix4( viewMatrix );
  1584. uniforms.color.copy( color ).multiplyScalar( intensity );
  1585. uniforms.distance = distance;
  1586. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1587. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1588. uniforms.direction.sub( _vector3 );
  1589. uniforms.direction.transformDirection( viewMatrix );
  1590. uniforms.coneCos = Math.cos( light.angle );
  1591. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  1592. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1593. uniforms.shadow = light.castShadow;
  1594. if ( light.castShadow ) {
  1595. uniforms.shadowBias = light.shadow.bias;
  1596. uniforms.shadowRadius = light.shadow.radius;
  1597. uniforms.shadowMapSize = light.shadow.mapSize;
  1598. }
  1599. _lights.spotShadowMap[ spotLength ] = light.shadow.map;
  1600. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  1601. _lights.spot[ spotLength ++ ] = uniforms;
  1602. } else if ( light instanceof THREE.PointLight ) {
  1603. var uniforms = lightCache.get( light );
  1604. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1605. uniforms.position.applyMatrix4( viewMatrix );
  1606. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1607. uniforms.distance = light.distance;
  1608. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1609. uniforms.shadow = light.castShadow;
  1610. if ( light.castShadow ) {
  1611. uniforms.shadowBias = light.shadow.bias;
  1612. uniforms.shadowRadius = light.shadow.radius;
  1613. uniforms.shadowMapSize = light.shadow.mapSize;
  1614. }
  1615. _lights.pointShadowMap[ pointLength ] = light.shadow.map;
  1616. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  1617. _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4();
  1618. }
  1619. // for point lights we set the shadow matrix to be a translation-only matrix
  1620. // equal to inverse of the light's position
  1621. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  1622. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  1623. _lights.point[ pointLength ++ ] = uniforms;
  1624. } else if ( light instanceof THREE.HemisphereLight ) {
  1625. var uniforms = lightCache.get( light );
  1626. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1627. uniforms.direction.transformDirection( viewMatrix );
  1628. uniforms.direction.normalize();
  1629. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  1630. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  1631. _lights.hemi[ hemiLength ++ ] = uniforms;
  1632. }
  1633. }
  1634. _lights.ambient[ 0 ] = r;
  1635. _lights.ambient[ 1 ] = g;
  1636. _lights.ambient[ 2 ] = b;
  1637. _lights.directional.length = directionalLength;
  1638. _lights.spot.length = spotLength;
  1639. _lights.point.length = pointLength;
  1640. _lights.hemi.length = hemiLength;
  1641. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
  1642. }
  1643. function setupGlobalClippingPlanes( planes, camera ) {
  1644. _clippingEnabled =
  1645. _this.clippingPlanes.length !== 0 ||
  1646. _this.localClippingEnabled ||
  1647. // enable state of previous frame - the clipping code has to
  1648. // run another frame in order to reset the state:
  1649. _numGlobalClippingPlanes !== 0 ||
  1650. _localClippingEnabled;
  1651. _localClippingEnabled = _this.localClippingEnabled;
  1652. _globalClippingState = setupClippingPlanes( planes, camera, 0 );
  1653. _numGlobalClippingPlanes = planes !== null ? planes.length : 0;
  1654. }
  1655. function setupClippingPlanes( planes, camera, dstOffset, skipTransform ) {
  1656. var nPlanes = planes !== null ? planes.length : 0,
  1657. dstArray = null;
  1658. if ( nPlanes !== 0 ) {
  1659. dstArray = _clippingPlanesUniform.value;
  1660. if ( skipTransform !== true || dstArray === null ) {
  1661. var flatSize = dstOffset + nPlanes * 4,
  1662. viewMatrix = camera.matrixWorldInverse,
  1663. viewNormalMatrix = _matrix3.getNormalMatrix( viewMatrix );
  1664. if ( dstArray === null || dstArray.length < flatSize ) {
  1665. dstArray = new Float32Array( flatSize );
  1666. }
  1667. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  1668. var plane = _plane.copy( planes[ i ] ).
  1669. applyMatrix4( viewMatrix, viewNormalMatrix );
  1670. plane.normal.toArray( dstArray, i4 );
  1671. dstArray[ i4 + 3 ] = plane.constant;
  1672. }
  1673. }
  1674. _clippingPlanesUniform.value = dstArray;
  1675. _clippingPlanesUniform.needsUpdate = true;
  1676. }
  1677. _numClippingPlanes = nPlanes;
  1678. return dstArray;
  1679. }
  1680. function resetGlobalClippingState() {
  1681. if ( _clippingPlanesUniform.value !== _globalClippingState ) {
  1682. _clippingPlanesUniform.value = _globalClippingState;
  1683. _clippingPlanesUniform.needsUpdate = _numGlobalClippingPlanes > 0;
  1684. }
  1685. _numClippingPlanes = _numGlobalClippingPlanes;
  1686. }
  1687. function setClippingState( planes, clipShadows, camera, cache, fromCache ) {
  1688. if ( ! _localClippingEnabled ||
  1689. planes === null || planes.length === 0 ||
  1690. _clipRenderingShadows && ! clipShadows ) {
  1691. // there's no local clipping
  1692. if ( _clipRenderingShadows ) {
  1693. // there's no global clipping
  1694. setupClippingPlanes( null );
  1695. } else {
  1696. resetGlobalClippingState();
  1697. }
  1698. } else {
  1699. var nGlobal = _clipRenderingShadows ? 0 : _numGlobalClippingPlanes,
  1700. lGlobal = nGlobal * 4,
  1701. dstArray = cache.clippingState || null;
  1702. _clippingPlanesUniform.value = dstArray; // ensure unique state
  1703. dstArray = setupClippingPlanes(
  1704. planes, camera, lGlobal, fromCache );
  1705. for ( var i = 0; i !== lGlobal; ++ i ) {
  1706. dstArray[ i ] = _globalClippingState[ i ];
  1707. }
  1708. cache.clippingState = dstArray;
  1709. _numClippingPlanes += nGlobal;
  1710. }
  1711. }
  1712. // GL state setting
  1713. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  1714. if ( cullFace === THREE.CullFaceNone ) {
  1715. state.disable( _gl.CULL_FACE );
  1716. } else {
  1717. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  1718. _gl.frontFace( _gl.CW );
  1719. } else {
  1720. _gl.frontFace( _gl.CCW );
  1721. }
  1722. if ( cullFace === THREE.CullFaceBack ) {
  1723. _gl.cullFace( _gl.BACK );
  1724. } else if ( cullFace === THREE.CullFaceFront ) {
  1725. _gl.cullFace( _gl.FRONT );
  1726. } else {
  1727. _gl.cullFace( _gl.FRONT_AND_BACK );
  1728. }
  1729. state.enable( _gl.CULL_FACE );
  1730. }
  1731. };
  1732. // Textures
  1733. function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) {
  1734. var extension;
  1735. if ( isPowerOfTwoImage ) {
  1736. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  1737. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  1738. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  1739. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  1740. } else {
  1741. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  1742. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  1743. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  1744. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  1745. }
  1746. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  1747. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  1748. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  1749. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  1750. }
  1751. }
  1752. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  1753. if ( extension ) {
  1754. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  1755. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  1756. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  1757. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  1758. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  1759. }
  1760. }
  1761. }
  1762. function uploadTexture( textureProperties, texture, slot ) {
  1763. if ( textureProperties.__webglInit === undefined ) {
  1764. textureProperties.__webglInit = true;
  1765. texture.addEventListener( 'dispose', onTextureDispose );
  1766. textureProperties.__webglTexture = _gl.createTexture();
  1767. _infoMemory.textures ++;
  1768. }
  1769. state.activeTexture( _gl.TEXTURE0 + slot );
  1770. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  1771. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  1772. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  1773. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  1774. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  1775. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  1776. image = makePowerOfTwo( image );
  1777. }
  1778. var isPowerOfTwoImage = isPowerOfTwo( image ),
  1779. glFormat = paramThreeToGL( texture.format ),
  1780. glType = paramThreeToGL( texture.type );
  1781. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  1782. var mipmap, mipmaps = texture.mipmaps;
  1783. if ( texture instanceof THREE.DataTexture ) {
  1784. // use manually created mipmaps if available
  1785. // if there are no manual mipmaps
  1786. // set 0 level mipmap and then use GL to generate other mipmap levels
  1787. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  1788. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1789. mipmap = mipmaps[ i ];
  1790. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1791. }
  1792. texture.generateMipmaps = false;
  1793. } else {
  1794. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  1795. }
  1796. } else if ( texture instanceof THREE.CompressedTexture ) {
  1797. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1798. mipmap = mipmaps[ i ];
  1799. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  1800. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  1801. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  1802. } else {
  1803. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  1804. }
  1805. } else {
  1806. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1807. }
  1808. }
  1809. } else {
  1810. // regular Texture (image, video, canvas)
  1811. // use manually created mipmaps if available
  1812. // if there are no manual mipmaps
  1813. // set 0 level mipmap and then use GL to generate other mipmap levels
  1814. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  1815. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1816. mipmap = mipmaps[ i ];
  1817. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  1818. }
  1819. texture.generateMipmaps = false;
  1820. } else {
  1821. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  1822. }
  1823. }
  1824. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1825. textureProperties.__version = texture.version;
  1826. if ( texture.onUpdate ) texture.onUpdate( texture );
  1827. }
  1828. this.setTexture = function ( texture, slot ) {
  1829. var textureProperties = properties.get( texture );
  1830. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  1831. var image = texture.image;
  1832. if ( image === undefined ) {
  1833. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  1834. return;
  1835. }
  1836. if ( image.complete === false ) {
  1837. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  1838. return;
  1839. }
  1840. uploadTexture( textureProperties, texture, slot );
  1841. return;
  1842. }
  1843. state.activeTexture( _gl.TEXTURE0 + slot );
  1844. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  1845. };
  1846. function clampToMaxSize ( image, maxSize ) {
  1847. if ( image.width > maxSize || image.height > maxSize ) {
  1848. // Warning: Scaling through the canvas will only work with images that use
  1849. // premultiplied alpha.
  1850. var scale = maxSize / Math.max( image.width, image.height );
  1851. var canvas = document.createElement( 'canvas' );
  1852. canvas.width = Math.floor( image.width * scale );
  1853. canvas.height = Math.floor( image.height * scale );
  1854. var context = canvas.getContext( '2d' );
  1855. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  1856. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  1857. return canvas;
  1858. }
  1859. return image;
  1860. }
  1861. function isPowerOfTwo( image ) {
  1862. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  1863. }
  1864. function textureNeedsPowerOfTwo( texture ) {
  1865. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  1866. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  1867. return false;
  1868. }
  1869. function makePowerOfTwo( image ) {
  1870. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  1871. var canvas = document.createElement( 'canvas' );
  1872. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  1873. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  1874. var context = canvas.getContext( '2d' );
  1875. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  1876. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  1877. return canvas;
  1878. }
  1879. return image;
  1880. }
  1881. function setCubeTexture ( texture, slot ) {
  1882. var textureProperties = properties.get( texture );
  1883. if ( texture.image.length === 6 ) {
  1884. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  1885. if ( ! textureProperties.__image__webglTextureCube ) {
  1886. texture.addEventListener( 'dispose', onTextureDispose );
  1887. textureProperties.__image__webglTextureCube = _gl.createTexture();
  1888. _infoMemory.textures ++;
  1889. }
  1890. state.activeTexture( _gl.TEXTURE0 + slot );
  1891. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  1892. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  1893. var isCompressed = texture instanceof THREE.CompressedTexture;
  1894. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  1895. var cubeImage = [];
  1896. for ( var i = 0; i < 6; i ++ ) {
  1897. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  1898. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  1899. } else {
  1900. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  1901. }
  1902. }
  1903. var image = cubeImage[ 0 ],
  1904. isPowerOfTwoImage = isPowerOfTwo( image ),
  1905. glFormat = paramThreeToGL( texture.format ),
  1906. glType = paramThreeToGL( texture.type );
  1907. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  1908. for ( var i = 0; i < 6; i ++ ) {
  1909. if ( ! isCompressed ) {
  1910. if ( isDataTexture ) {
  1911. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  1912. } else {
  1913. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  1914. }
  1915. } else {
  1916. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  1917. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  1918. mipmap = mipmaps[ j ];
  1919. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  1920. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  1921. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  1922. } else {
  1923. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  1924. }
  1925. } else {
  1926. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1927. }
  1928. }
  1929. }
  1930. }
  1931. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  1932. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  1933. }
  1934. textureProperties.__version = texture.version;
  1935. if ( texture.onUpdate ) texture.onUpdate( texture );
  1936. } else {
  1937. state.activeTexture( _gl.TEXTURE0 + slot );
  1938. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  1939. }
  1940. }
  1941. }
  1942. function setCubeTextureDynamic ( texture, slot ) {
  1943. state.activeTexture( _gl.TEXTURE0 + slot );
  1944. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  1945. }
  1946. // Render targets
  1947. // Setup storage for target texture and bind it to correct framebuffer
  1948. function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
  1949. var glFormat = paramThreeToGL( renderTarget.texture.format );
  1950. var glType = paramThreeToGL( renderTarget.texture.type );
  1951. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  1952. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1953. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  1954. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1955. }
  1956. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  1957. function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
  1958. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  1959. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  1960. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  1961. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  1962. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  1963. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  1964. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  1965. } else {
  1966. // FIXME: We don't support !depth !stencil
  1967. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  1968. }
  1969. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  1970. }
  1971. // Setup GL resources for a non-texture depth buffer
  1972. function setupDepthRenderbuffer( renderTarget ) {
  1973. var renderTargetProperties = properties.get( renderTarget );
  1974. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  1975. if ( isCube ) {
  1976. renderTargetProperties.__webglDepthbuffer = [];
  1977. for ( var i = 0; i < 6; i ++ ) {
  1978. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  1979. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  1980. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  1981. }
  1982. } else {
  1983. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  1984. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  1985. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  1986. }
  1987. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1988. }
  1989. // Set up GL resources for the render target
  1990. function setupRenderTarget( renderTarget ) {
  1991. var renderTargetProperties = properties.get( renderTarget );
  1992. var textureProperties = properties.get( renderTarget.texture );
  1993. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  1994. textureProperties.__webglTexture = _gl.createTexture();
  1995. _infoMemory.textures ++;
  1996. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  1997. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
  1998. // Setup framebuffer
  1999. if ( isCube ) {
  2000. renderTargetProperties.__webglFramebuffer = [];
  2001. for ( var i = 0; i < 6; i ++ ) {
  2002. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  2003. }
  2004. } else {
  2005. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  2006. }
  2007. // Setup color buffer
  2008. if ( isCube ) {
  2009. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  2010. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  2011. for ( var i = 0; i < 6; i ++ ) {
  2012. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  2013. }
  2014. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  2015. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  2016. } else {
  2017. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  2018. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  2019. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  2020. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  2021. state.bindTexture( _gl.TEXTURE_2D, null );
  2022. }
  2023. // Setup depth and stencil buffers
  2024. if ( renderTarget.depthBuffer ) {
  2025. setupDepthRenderbuffer( renderTarget );
  2026. }
  2027. }
  2028. this.getCurrentRenderTarget = function() {
  2029. return _currentRenderTarget;
  2030. }
  2031. this.setRenderTarget = function ( renderTarget ) {
  2032. _currentRenderTarget = renderTarget;
  2033. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  2034. setupRenderTarget( renderTarget );
  2035. }
  2036. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  2037. var framebuffer;
  2038. if ( renderTarget ) {
  2039. var renderTargetProperties = properties.get( renderTarget );
  2040. if ( isCube ) {
  2041. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  2042. } else {
  2043. framebuffer = renderTargetProperties.__webglFramebuffer;
  2044. }
  2045. _currentScissor.copy( renderTarget.scissor );
  2046. _currentScissorTest = renderTarget.scissorTest;
  2047. _currentViewport.copy( renderTarget.viewport );
  2048. } else {
  2049. framebuffer = null;
  2050. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  2051. _currentScissorTest = _scissorTest;
  2052. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  2053. }
  2054. if ( _currentFramebuffer !== framebuffer ) {
  2055. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  2056. _currentFramebuffer = framebuffer;
  2057. }
  2058. state.scissor( _currentScissor );
  2059. state.setScissorTest( _currentScissorTest );
  2060. state.viewport( _currentViewport );
  2061. if ( isCube ) {
  2062. var textureProperties = properties.get( renderTarget.texture );
  2063. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  2064. }
  2065. };
  2066. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  2067. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  2068. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  2069. return;
  2070. }
  2071. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  2072. if ( framebuffer ) {
  2073. var restore = false;
  2074. if ( framebuffer !== _currentFramebuffer ) {
  2075. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  2076. restore = true;
  2077. }
  2078. try {
  2079. var texture = renderTarget.texture;
  2080. if ( texture.format !== THREE.RGBAFormat
  2081. && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  2082. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  2083. return;
  2084. }
  2085. if ( texture.type !== THREE.UnsignedByteType
  2086. && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
  2087. && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
  2088. && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  2089. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  2090. return;
  2091. }
  2092. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  2093. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  2094. } else {
  2095. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  2096. }
  2097. } finally {
  2098. if ( restore ) {
  2099. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  2100. }
  2101. }
  2102. }
  2103. };
  2104. function updateRenderTargetMipmap( renderTarget ) {
  2105. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  2106. var texture = properties.get( renderTarget.texture ).__webglTexture;
  2107. state.bindTexture( target, texture );
  2108. _gl.generateMipmap( target );
  2109. state.bindTexture( target, null );
  2110. }
  2111. // Fallback filters for non-power-of-2 textures
  2112. function filterFallback ( f ) {
  2113. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  2114. return _gl.NEAREST;
  2115. }
  2116. return _gl.LINEAR;
  2117. }
  2118. // Map three.js constants to WebGL constants
  2119. function paramThreeToGL ( p ) {
  2120. var extension;
  2121. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  2122. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  2123. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  2124. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  2125. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  2126. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  2127. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  2128. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  2129. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  2130. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  2131. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  2132. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  2133. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  2134. if ( p === THREE.ByteType ) return _gl.BYTE;
  2135. if ( p === THREE.ShortType ) return _gl.SHORT;
  2136. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  2137. if ( p === THREE.IntType ) return _gl.INT;
  2138. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  2139. if ( p === THREE.FloatType ) return _gl.FLOAT;
  2140. extension = extensions.get( 'OES_texture_half_float' );
  2141. if ( extension !== null ) {
  2142. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  2143. }
  2144. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  2145. if ( p === THREE.RGBFormat ) return _gl.RGB;
  2146. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  2147. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  2148. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  2149. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  2150. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  2151. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  2152. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  2153. if ( p === THREE.OneFactor ) return _gl.ONE;
  2154. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  2155. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  2156. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  2157. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  2158. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  2159. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  2160. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  2161. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  2162. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  2163. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  2164. if ( extension !== null ) {
  2165. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  2166. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  2167. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  2168. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  2169. }
  2170. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  2171. if ( extension !== null ) {
  2172. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  2173. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  2174. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  2175. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  2176. }
  2177. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  2178. if ( extension !== null ) {
  2179. if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  2180. }
  2181. extension = extensions.get( 'EXT_blend_minmax' );
  2182. if ( extension !== null ) {
  2183. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  2184. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  2185. }
  2186. return 0;
  2187. }
  2188. };