WebGLRenderer.js 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137
  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. */
  7. THREE.WebGLRenderer = function ( parameters ) {
  8. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9. parameters = parameters || {};
  10. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11. _context = parameters.context !== undefined ? parameters.context : null,
  12. _width = _canvas.width,
  13. _height = _canvas.height,
  14. pixelRatio = 1,
  15. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  16. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  17. _depth = parameters.depth !== undefined ? parameters.depth : true,
  18. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  19. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  20. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  21. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  22. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  23. _clearColor = new THREE.Color( 0x000000 ),
  24. _clearAlpha = 0;
  25. var lights = [];
  26. var opaqueObjects = [];
  27. var transparentObjects = [];
  28. var sprites = [];
  29. var lensFlares = [];
  30. // public properties
  31. this.domElement = _canvas;
  32. this.context = null;
  33. // clearing
  34. this.autoClear = true;
  35. this.autoClearColor = true;
  36. this.autoClearDepth = true;
  37. this.autoClearStencil = true;
  38. // scene graph
  39. this.sortObjects = true;
  40. // physically based shading
  41. this.gammaFactor = 2.0; // for backwards compatibility
  42. this.gammaInput = false;
  43. this.gammaOutput = false;
  44. // morphs
  45. this.maxMorphTargets = 8;
  46. this.maxMorphNormals = 4;
  47. // flags
  48. this.autoScaleCubemaps = true;
  49. // info
  50. this.info = {
  51. memory: {
  52. programs: 0,
  53. geometries: 0,
  54. textures: 0
  55. },
  56. render: {
  57. calls: 0,
  58. vertices: 0,
  59. faces: 0,
  60. points: 0
  61. }
  62. };
  63. // internal properties
  64. var _this = this,
  65. _programs = [],
  66. // internal state cache
  67. _currentProgram = null,
  68. _currentFramebuffer = null,
  69. _currentMaterialId = - 1,
  70. _currentGeometryProgram = '',
  71. _currentCamera = null,
  72. _usedTextureUnits = 0,
  73. _viewportX = 0,
  74. _viewportY = 0,
  75. _viewportWidth = _canvas.width,
  76. _viewportHeight = _canvas.height,
  77. _currentWidth = 0,
  78. _currentHeight = 0,
  79. // frustum
  80. _frustum = new THREE.Frustum(),
  81. // camera matrices cache
  82. _projScreenMatrix = new THREE.Matrix4(),
  83. _vector3 = new THREE.Vector3(),
  84. // light arrays cache
  85. _direction = new THREE.Vector3(),
  86. _lightsNeedUpdate = true,
  87. _lights = {
  88. ambient: [ 0, 0, 0 ],
  89. directional: { length: 0, colors:[], positions: [] },
  90. point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
  91. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
  92. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  93. };
  94. // initialize
  95. var _gl;
  96. try {
  97. var attributes = {
  98. alpha: _alpha,
  99. depth: _depth,
  100. stencil: _stencil,
  101. antialias: _antialias,
  102. premultipliedAlpha: _premultipliedAlpha,
  103. preserveDrawingBuffer: _preserveDrawingBuffer
  104. };
  105. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  106. if ( _gl === null ) {
  107. if ( _canvas.getContext( 'webgl') !== null ) {
  108. throw 'Error creating WebGL context with your selected attributes.';
  109. } else {
  110. throw 'Error creating WebGL context.';
  111. }
  112. }
  113. _canvas.addEventListener( 'webglcontextlost', function ( event ) {
  114. event.preventDefault();
  115. resetGLState();
  116. setDefaultGLState();
  117. objects.objects = {};
  118. }, false);
  119. } catch ( error ) {
  120. THREE.error( 'THREE.WebGLRenderer: ' + error );
  121. }
  122. var state = new THREE.WebGLState( _gl, paramThreeToGL );
  123. if ( _gl.getShaderPrecisionFormat === undefined ) {
  124. _gl.getShaderPrecisionFormat = function () {
  125. return {
  126. 'rangeMin': 1,
  127. 'rangeMax': 1,
  128. 'precision': 1
  129. };
  130. }
  131. }
  132. var extensions = new THREE.WebGLExtensions( _gl );
  133. var objects = new THREE.WebGLObjects( _gl, this.info );
  134. extensions.get( 'OES_texture_float' );
  135. extensions.get( 'OES_texture_float_linear' );
  136. extensions.get( 'OES_texture_half_float' );
  137. extensions.get( 'OES_texture_half_float_linear' );
  138. extensions.get( 'OES_standard_derivatives' );
  139. extensions.get( 'ANGLE_instanced_arrays' );
  140. if ( _logarithmicDepthBuffer ) {
  141. extensions.get( 'EXT_frag_depth' );
  142. }
  143. //
  144. var glClearColor = function ( r, g, b, a ) {
  145. if ( _premultipliedAlpha === true ) {
  146. r *= a; g *= a; b *= a;
  147. }
  148. _gl.clearColor( r, g, b, a );
  149. };
  150. var setDefaultGLState = function () {
  151. _gl.clearColor( 0, 0, 0, 1 );
  152. _gl.clearDepth( 1 );
  153. _gl.clearStencil( 0 );
  154. _gl.enable( _gl.DEPTH_TEST );
  155. _gl.depthFunc( _gl.LEQUAL );
  156. _gl.frontFace( _gl.CCW );
  157. _gl.cullFace( _gl.BACK );
  158. _gl.enable( _gl.CULL_FACE );
  159. _gl.enable( _gl.BLEND );
  160. _gl.blendEquation( _gl.FUNC_ADD );
  161. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  162. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  163. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  164. };
  165. var resetGLState = function () {
  166. _currentProgram = null;
  167. _currentCamera = null;
  168. _currentGeometryProgram = '';
  169. _currentMaterialId = - 1;
  170. _lightsNeedUpdate = true;
  171. state.reset();
  172. };
  173. setDefaultGLState();
  174. this.context = _gl;
  175. this.extensions = extensions;
  176. this.state = state;
  177. // shadow map
  178. var shadowMap = new THREE.WebGLShadowMap( this, lights, objects );
  179. this.shadowMap = shadowMap;
  180. // GPU capabilities
  181. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  182. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  183. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  184. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  185. var _supportsVertexTextures = _maxVertexTextures > 0;
  186. var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' );
  187. var _supportsInstancedArrays = extensions.get( 'ANGLE_instanced_arrays' );
  188. //
  189. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  190. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  191. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  192. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  193. var getCompressedTextureFormats = ( function () {
  194. var array;
  195. return function () {
  196. if ( array !== undefined ) {
  197. return array;
  198. }
  199. array = [];
  200. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  201. var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS );
  202. for ( var i = 0; i < formats.length; i ++ ) {
  203. array.push( formats[ i ] );
  204. }
  205. }
  206. return array;
  207. };
  208. } )();
  209. // clamp precision to maximum available
  210. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  211. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  212. if ( _precision === 'highp' && ! highpAvailable ) {
  213. if ( mediumpAvailable ) {
  214. _precision = 'mediump';
  215. THREE.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  216. } else {
  217. _precision = 'lowp';
  218. THREE.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  219. }
  220. }
  221. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  222. _precision = 'lowp';
  223. THREE.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  224. }
  225. // Plugins
  226. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  227. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  228. // API
  229. this.getContext = function () {
  230. return _gl;
  231. };
  232. this.forceContextLoss = function () {
  233. extensions.get( 'WEBGL_lose_context' ).loseContext();
  234. };
  235. this.supportsVertexTextures = function () {
  236. return _supportsVertexTextures;
  237. };
  238. this.supportsInstancedArrays = function () {
  239. return _supportsInstancedArrays;
  240. };
  241. this.supportsFloatTextures = function () {
  242. return extensions.get( 'OES_texture_float' );
  243. };
  244. this.supportsHalfFloatTextures = function () {
  245. return extensions.get( 'OES_texture_half_float' );
  246. };
  247. this.supportsStandardDerivatives = function () {
  248. return extensions.get( 'OES_standard_derivatives' );
  249. };
  250. this.supportsCompressedTextureS3TC = function () {
  251. return extensions.get( 'WEBGL_compressed_texture_s3tc' );
  252. };
  253. this.supportsCompressedTexturePVRTC = function () {
  254. return extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  255. };
  256. this.supportsBlendMinMax = function () {
  257. return extensions.get( 'EXT_blend_minmax' );
  258. };
  259. this.getMaxAnisotropy = ( function () {
  260. var value;
  261. return function () {
  262. if ( value !== undefined ) {
  263. return value;
  264. }
  265. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  266. value = extension !== null ? _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  267. return value;
  268. }
  269. } )();
  270. this.getPrecision = function () {
  271. return _precision;
  272. };
  273. this.getPixelRatio = function () {
  274. return pixelRatio;
  275. };
  276. this.setPixelRatio = function ( value ) {
  277. pixelRatio = value;
  278. };
  279. this.getSize = function () {
  280. return {
  281. width: _width,
  282. height: _height
  283. };
  284. };
  285. this.setSize = function ( width, height, updateStyle ) {
  286. _width = width;
  287. _height = height;
  288. _canvas.width = width * pixelRatio;
  289. _canvas.height = height * pixelRatio;
  290. if ( updateStyle !== false ) {
  291. _canvas.style.width = width + 'px';
  292. _canvas.style.height = height + 'px';
  293. }
  294. this.setViewport( 0, 0, width, height );
  295. };
  296. this.setViewport = function ( x, y, width, height ) {
  297. _viewportX = x * pixelRatio;
  298. _viewportY = y * pixelRatio;
  299. _viewportWidth = width * pixelRatio;
  300. _viewportHeight = height * pixelRatio;
  301. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  302. };
  303. this.setScissor = function ( x, y, width, height ) {
  304. _gl.scissor(
  305. x * pixelRatio,
  306. y * pixelRatio,
  307. width * pixelRatio,
  308. height * pixelRatio
  309. );
  310. };
  311. this.enableScissorTest = function ( enable ) {
  312. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  313. };
  314. // Clearing
  315. this.getClearColor = function () {
  316. return _clearColor;
  317. };
  318. this.setClearColor = function ( color, alpha ) {
  319. _clearColor.set( color );
  320. _clearAlpha = alpha !== undefined ? alpha : 1;
  321. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  322. };
  323. this.getClearAlpha = function () {
  324. return _clearAlpha;
  325. };
  326. this.setClearAlpha = function ( alpha ) {
  327. _clearAlpha = alpha;
  328. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  329. };
  330. this.clear = function ( color, depth, stencil ) {
  331. var bits = 0;
  332. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  333. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  334. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  335. _gl.clear( bits );
  336. };
  337. this.clearColor = function () {
  338. _gl.clear( _gl.COLOR_BUFFER_BIT );
  339. };
  340. this.clearDepth = function () {
  341. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  342. };
  343. this.clearStencil = function () {
  344. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  345. };
  346. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  347. this.setRenderTarget( renderTarget );
  348. this.clear( color, depth, stencil );
  349. };
  350. // Reset
  351. this.resetGLState = resetGLState;
  352. // Events
  353. var onTextureDispose = function ( event ) {
  354. var texture = event.target;
  355. texture.removeEventListener( 'dispose', onTextureDispose );
  356. deallocateTexture( texture );
  357. _this.info.memory.textures --;
  358. };
  359. var onRenderTargetDispose = function ( event ) {
  360. var renderTarget = event.target;
  361. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  362. deallocateRenderTarget( renderTarget );
  363. _this.info.memory.textures --;
  364. };
  365. var onMaterialDispose = function ( event ) {
  366. var material = event.target;
  367. material.removeEventListener( 'dispose', onMaterialDispose );
  368. deallocateMaterial( material );
  369. };
  370. // Buffer deallocation
  371. var deallocateTexture = function ( texture ) {
  372. if ( texture.image && texture.image.__webglTextureCube ) {
  373. // cube texture
  374. _gl.deleteTexture( texture.image.__webglTextureCube );
  375. delete texture.image.__webglTextureCube;
  376. } else {
  377. // 2D texture
  378. if ( texture.__webglInit === undefined ) return;
  379. _gl.deleteTexture( texture.__webglTexture );
  380. delete texture.__webglTexture;
  381. delete texture.__webglInit;
  382. }
  383. };
  384. var deallocateRenderTarget = function ( renderTarget ) {
  385. if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return;
  386. _gl.deleteTexture( renderTarget.__webglTexture );
  387. delete renderTarget.__webglTexture;
  388. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  389. for ( var i = 0; i < 6; i ++ ) {
  390. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  391. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  392. }
  393. } else {
  394. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  395. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  396. }
  397. delete renderTarget.__webglFramebuffer;
  398. delete renderTarget.__webglRenderbuffer;
  399. };
  400. var deallocateMaterial = function ( material ) {
  401. var program = material.program.program;
  402. if ( program === undefined ) return;
  403. material.program = undefined;
  404. // only deallocate GL program if this was the last use of shared program
  405. // assumed there is only single copy of any program in the _programs list
  406. // (that's how it's constructed)
  407. var i, il, programInfo;
  408. var deleteProgram = false;
  409. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  410. programInfo = _programs[ i ];
  411. if ( programInfo.program === program ) {
  412. programInfo.usedTimes --;
  413. if ( programInfo.usedTimes === 0 ) {
  414. deleteProgram = true;
  415. }
  416. break;
  417. }
  418. }
  419. if ( deleteProgram === true ) {
  420. // avoid using array.splice, this is costlier than creating new array from scratch
  421. var newPrograms = [];
  422. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  423. programInfo = _programs[ i ];
  424. if ( programInfo.program !== program ) {
  425. newPrograms.push( programInfo );
  426. }
  427. }
  428. _programs = newPrograms;
  429. _gl.deleteProgram( program );
  430. _this.info.memory.programs --;
  431. }
  432. };
  433. // Buffer rendering
  434. this.renderBufferImmediate = function ( object, program, material ) {
  435. state.initAttributes();
  436. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  437. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  438. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  439. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  440. if ( object.hasPositions ) {
  441. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  442. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  443. state.enableAttribute( program.attributes.position );
  444. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  445. }
  446. if ( object.hasNormals ) {
  447. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  448. if ( material instanceof THREE.MeshPhongMaterial === false && material.shading === THREE.FlatShading ) {
  449. var nx, ny, nz,
  450. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  451. normalArray,
  452. i, il = object.count * 3;
  453. for ( i = 0; i < il; i += 9 ) {
  454. normalArray = object.normalArray;
  455. nax = normalArray[ i ];
  456. nay = normalArray[ i + 1 ];
  457. naz = normalArray[ i + 2 ];
  458. nbx = normalArray[ i + 3 ];
  459. nby = normalArray[ i + 4 ];
  460. nbz = normalArray[ i + 5 ];
  461. ncx = normalArray[ i + 6 ];
  462. ncy = normalArray[ i + 7 ];
  463. ncz = normalArray[ i + 8 ];
  464. nx = ( nax + nbx + ncx ) / 3;
  465. ny = ( nay + nby + ncy ) / 3;
  466. nz = ( naz + nbz + ncz ) / 3;
  467. normalArray[ i ] = nx;
  468. normalArray[ i + 1 ] = ny;
  469. normalArray[ i + 2 ] = nz;
  470. normalArray[ i + 3 ] = nx;
  471. normalArray[ i + 4 ] = ny;
  472. normalArray[ i + 5 ] = nz;
  473. normalArray[ i + 6 ] = nx;
  474. normalArray[ i + 7 ] = ny;
  475. normalArray[ i + 8 ] = nz;
  476. }
  477. }
  478. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  479. state.enableAttribute( program.attributes.normal );
  480. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  481. }
  482. if ( object.hasUvs && material.map ) {
  483. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  484. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  485. state.enableAttribute( program.attributes.uv );
  486. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  487. }
  488. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  489. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  490. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  491. state.enableAttribute( program.attributes.color );
  492. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  493. }
  494. state.disableUnusedAttributes();
  495. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  496. object.count = 0;
  497. };
  498. function setupVertexAttributes( material, program, geometry, startIndex ) {
  499. var extension;
  500. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  501. extension = extensions.get( 'ANGLE_instanced_arrays' );
  502. if ( extension === null ) {
  503. THREE.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  504. return;
  505. }
  506. }
  507. var geometryAttributes = geometry.attributes;
  508. var programAttributes = program.attributes;
  509. var programAttributesKeys = program.attributesKeys;
  510. for ( var i = 0, l = programAttributesKeys.length; i < l; i ++ ) {
  511. var key = programAttributesKeys[ i ];
  512. var programAttribute = programAttributes[ key ];
  513. if ( programAttribute >= 0 ) {
  514. var geometryAttribute = geometryAttributes[ key ];
  515. if ( geometryAttribute !== undefined ) {
  516. var size = geometryAttribute.itemSize;
  517. state.enableAttribute( programAttribute );
  518. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  519. var data = geometryAttribute.data;
  520. var stride = data.stride;
  521. var offset = geometryAttribute.offset;
  522. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.data.buffer );
  523. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  524. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  525. if ( extension === null ) {
  526. THREE.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferAttribute but hardware does not support extension ANGLE_instanced_arrays.' );
  527. return;
  528. }
  529. extension.vertexAttribDivisorANGLE( programAttribute, data.meshPerAttribute );
  530. if ( geometry.maxInstancedCount === undefined ) {
  531. geometry.maxInstancedCount = data.meshPerAttribute * ( data.array.length / data.stride );
  532. }
  533. }
  534. } else {
  535. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer );
  536. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  537. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  538. if ( extension === null ) {
  539. THREE.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferAttribute but hardware does not support extension ANGLE_instanced_arrays.' );
  540. return;
  541. }
  542. extension.vertexAttribDivisorANGLE( programAttribute, geometryAttribute.meshPerAttribute );
  543. if ( geometry.maxInstancedCount === undefined ) {
  544. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * ( geometryAttribute.array.length / geometryAttribute.itemSize );
  545. }
  546. }
  547. }
  548. } else if ( material.defaultAttributeValues !== undefined ) {
  549. if ( material.defaultAttributeValues[ key ].length === 2 ) {
  550. _gl.vertexAttrib2fv( programAttribute, material.defaultAttributeValues[ key ] );
  551. } else if ( material.defaultAttributeValues[ key ].length === 3 ) {
  552. _gl.vertexAttrib3fv( programAttribute, material.defaultAttributeValues[ key ] );
  553. }
  554. }
  555. }
  556. }
  557. state.disableUnusedAttributes();
  558. }
  559. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  560. if ( material.visible === false ) return;
  561. objects.update( object );
  562. var program = setProgram( camera, lights, fog, material, object );
  563. var updateBuffers = false,
  564. wireframeBit = material.wireframe ? 1 : 0,
  565. geometryProgram = 'direct_' + geometry.id + '_' + program.id + '_' + wireframeBit;
  566. if ( geometryProgram !== _currentGeometryProgram ) {
  567. _currentGeometryProgram = geometryProgram;
  568. updateBuffers = true;
  569. }
  570. if ( updateBuffers ) {
  571. state.initAttributes();
  572. }
  573. // render mesh
  574. if ( object instanceof THREE.Mesh ) {
  575. var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES;
  576. var index = geometry.attributes.index;
  577. if ( index ) {
  578. // indexed triangles
  579. var type, size;
  580. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  581. type = _gl.UNSIGNED_INT;
  582. size = 4;
  583. } else {
  584. type = _gl.UNSIGNED_SHORT;
  585. size = 2;
  586. }
  587. var offsets = geometry.offsets;
  588. if ( offsets.length === 0 ) {
  589. if ( updateBuffers ) {
  590. setupVertexAttributes( material, program, geometry, 0 );
  591. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  592. }
  593. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  594. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  595. if ( extension === null ) {
  596. THREE.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  597. return;
  598. }
  599. extension.drawElementsInstancedANGLE( mode, index.array.length, type, 0, geometry.maxInstancedCount ); // Draw the instanced meshes
  600. } else {
  601. _gl.drawElements( mode, index.array.length, type, 0 );
  602. }
  603. _this.info.render.calls ++;
  604. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  605. _this.info.render.faces += index.array.length / 3;
  606. } else {
  607. // if there is more than 1 chunk
  608. // must set attribute pointers to use new offsets for each chunk
  609. // even if geometry and materials didn't change
  610. updateBuffers = true;
  611. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  612. var startIndex = offsets[ i ].index;
  613. if ( updateBuffers ) {
  614. setupVertexAttributes( material, program, geometry, startIndex );
  615. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  616. }
  617. // render indexed triangles
  618. if ( geometry instanceof THREE.InstancedBufferGeometry && offsets[i].instances > 0 ) {
  619. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  620. if ( extension === null ) {
  621. THREE.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  622. return;
  623. }
  624. extension.drawElementsInstancedANGLE( mode, offsets[i].count, type, offsets[i].start * size, offsets[i].count, type, offsets[i].instances ); // Draw the instanced meshes
  625. } else {
  626. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  627. }
  628. _this.info.render.calls ++;
  629. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  630. _this.info.render.faces += offsets[ i ].count / 3;
  631. }
  632. }
  633. } else {
  634. // non-indexed triangles
  635. if ( updateBuffers ) {
  636. setupVertexAttributes( material, program, geometry, 0 );
  637. }
  638. var position = geometry.attributes[ 'position' ];
  639. // render non-indexed triangles
  640. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  641. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  642. if ( extension === null ) {
  643. THREE.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  644. return;
  645. }
  646. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  647. extension.drawArraysInstancedANGLE( mode, 0, position.data.array.length / position.data.stride, geometry.maxInstancedCount ); // Draw the instanced meshes
  648. } else {
  649. extension.drawArraysInstancedANGLE( mode, 0, position.array.length / position.itemSize, geometry.maxInstancedCount ); // Draw the instanced meshes
  650. }
  651. } else {
  652. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  653. _gl.drawArrays( mode, 0, position.data.array.length / position.data.stride );
  654. } else {
  655. _gl.drawArrays( mode, 0, position.array.length / position.itemSize );
  656. }
  657. }
  658. _this.info.render.calls ++;
  659. _this.info.render.vertices += position.array.length / position.itemSize;
  660. _this.info.render.faces += position.array.length / ( 3 * position.itemSize );
  661. }
  662. } else if ( object instanceof THREE.PointCloud ) {
  663. // render particles
  664. var mode = _gl.POINTS;
  665. var index = geometry.attributes.index;
  666. if ( index ) {
  667. // indexed points
  668. var type, size;
  669. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  670. type = _gl.UNSIGNED_INT;
  671. size = 4;
  672. } else {
  673. type = _gl.UNSIGNED_SHORT;
  674. size = 2;
  675. }
  676. var offsets = geometry.offsets;
  677. if ( offsets.length === 0 ) {
  678. if ( updateBuffers ) {
  679. setupVertexAttributes( material, program, geometry, 0 );
  680. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  681. }
  682. _gl.drawElements( mode, index.array.length, type, 0);
  683. _this.info.render.calls ++;
  684. _this.info.render.points += index.array.length;
  685. } else {
  686. // if there is more than 1 chunk
  687. // must set attribute pointers to use new offsets for each chunk
  688. // even if geometry and materials didn't change
  689. if ( offsets.length > 1 ) updateBuffers = true;
  690. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  691. var startIndex = offsets[ i ].index;
  692. if ( updateBuffers ) {
  693. setupVertexAttributes( material, program, geometry, startIndex );
  694. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  695. }
  696. // render indexed points
  697. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  698. _this.info.render.calls ++;
  699. _this.info.render.points += offsets[ i ].count;
  700. }
  701. }
  702. } else {
  703. // non-indexed points
  704. if ( updateBuffers ) {
  705. setupVertexAttributes( material, program, geometry, 0 );
  706. }
  707. var position = geometry.attributes.position;
  708. var offsets = geometry.offsets;
  709. if ( offsets.length === 0 ) {
  710. _gl.drawArrays( mode, 0, position.array.length / 3 );
  711. _this.info.render.calls ++;
  712. _this.info.render.points += position.array.length / 3;
  713. } else {
  714. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  715. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  716. _this.info.render.calls ++;
  717. _this.info.render.points += offsets[ i ].count;
  718. }
  719. }
  720. }
  721. } else if ( object instanceof THREE.Line ) {
  722. var mode = ( object.mode === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  723. // In case user is not using Line*Material by mistake
  724. var lineWidth = material.linewidth !== undefined ? material.linewidth : 1;
  725. state.setLineWidth( lineWidth * pixelRatio );
  726. var index = geometry.attributes.index;
  727. if ( index ) {
  728. // indexed lines
  729. var type, size;
  730. if ( index.array instanceof Uint32Array ) {
  731. type = _gl.UNSIGNED_INT;
  732. size = 4;
  733. } else {
  734. type = _gl.UNSIGNED_SHORT;
  735. size = 2;
  736. }
  737. var offsets = geometry.offsets;
  738. if ( offsets.length === 0 ) {
  739. if ( updateBuffers ) {
  740. setupVertexAttributes( material, program, geometry, 0 );
  741. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  742. }
  743. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  744. _this.info.render.calls ++;
  745. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  746. } else {
  747. // if there is more than 1 chunk
  748. // must set attribute pointers to use new offsets for each chunk
  749. // even if geometry and materials didn't change
  750. if ( offsets.length > 1 ) updateBuffers = true;
  751. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  752. var startIndex = offsets[ i ].index;
  753. if ( updateBuffers ) {
  754. setupVertexAttributes( material, program, geometry, startIndex );
  755. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  756. }
  757. // render indexed lines
  758. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  759. _this.info.render.calls ++;
  760. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  761. }
  762. }
  763. } else {
  764. // non-indexed lines
  765. if ( updateBuffers ) {
  766. setupVertexAttributes( material, program, geometry, 0 );
  767. }
  768. var position = geometry.attributes.position;
  769. var offsets = geometry.offsets;
  770. if ( offsets.length === 0 ) {
  771. _gl.drawArrays( mode, 0, position.array.length / 3 );
  772. _this.info.render.calls ++;
  773. _this.info.render.vertices += position.array.length / 3;
  774. } else {
  775. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  776. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  777. _this.info.render.calls ++;
  778. _this.info.render.vertices += offsets[ i ].count;
  779. }
  780. }
  781. }
  782. }
  783. };
  784. function setupMorphTargets ( material, geometryGroup, object ) {
  785. // set base
  786. var attributes = material.program.attributes;
  787. if ( object.morphTargetBase !== - 1 && attributes.position >= 0 ) {
  788. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  789. state.enableAttribute( attributes.position );
  790. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  791. } else if ( attributes.position >= 0 ) {
  792. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  793. state.enableAttribute( attributes.position );
  794. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  795. }
  796. if ( object.morphTargetForcedOrder.length ) {
  797. // set forced order
  798. var m = 0;
  799. var order = object.morphTargetForcedOrder;
  800. var influences = object.morphTargetInfluences;
  801. var attribute;
  802. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  803. attribute = attributes[ 'morphTarget' + m ];
  804. if ( attribute >= 0 ) {
  805. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  806. state.enableAttribute( attribute );
  807. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  808. }
  809. attribute = attributes[ 'morphNormal' + m ];
  810. if ( attribute >= 0 && material.morphNormals ) {
  811. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  812. state.enableAttribute( attribute );
  813. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  814. }
  815. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  816. m ++;
  817. }
  818. } else {
  819. // find the most influencing
  820. var activeInfluenceIndices = [];
  821. var influences = object.morphTargetInfluences;
  822. var morphTargets = object.geometry.morphTargets;
  823. if ( influences.length > morphTargets.length ) {
  824. THREE.warn( 'THREE.WebGLRenderer: Influences array is bigger than morphTargets array.' );
  825. influences.length = morphTargets.length;
  826. }
  827. for ( var i = 0, il = influences.length; i < il; i ++ ) {
  828. var influence = influences[ i ];
  829. activeInfluenceIndices.push( [ influence, i ] );
  830. }
  831. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  832. activeInfluenceIndices.sort( numericalSort );
  833. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  834. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  835. activeInfluenceIndices.sort( numericalSort );
  836. } else if ( activeInfluenceIndices.length === 0 ) {
  837. activeInfluenceIndices.push( [ 0, 0 ] );
  838. }
  839. var attribute;
  840. for ( var m = 0, ml = material.numSupportedMorphTargets; m < ml; m ++ ) {
  841. if ( activeInfluenceIndices[ m ] ) {
  842. var influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  843. attribute = attributes[ 'morphTarget' + m ];
  844. if ( attribute >= 0 ) {
  845. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  846. state.enableAttribute( attribute );
  847. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  848. }
  849. attribute = attributes[ 'morphNormal' + m ];
  850. if ( attribute >= 0 && material.morphNormals ) {
  851. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  852. state.enableAttribute( attribute );
  853. _gl.vertexAttribPointer( attribute, 3, _gl.FLOAT, false, 0, 0 );
  854. }
  855. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  856. } else {
  857. /*
  858. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  859. if ( material.morphNormals ) {
  860. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  861. }
  862. */
  863. object.__webglMorphTargetInfluences[ m ] = 0;
  864. }
  865. }
  866. }
  867. // load updated influences uniform
  868. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  869. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  870. }
  871. }
  872. // Sorting
  873. function painterSortStable ( a, b ) {
  874. if ( a.object.renderOrder !== b.object.renderOrder ) {
  875. return a.object.renderOrder - b.object.renderOrder;
  876. } else if ( a.material.id !== b.material.id ) {
  877. return a.material.id - b.material.id;
  878. } else if ( a.z !== b.z ) {
  879. return a.z - b.z;
  880. } else {
  881. return a.id - b.id;
  882. }
  883. }
  884. function reversePainterSortStable ( a, b ) {
  885. if ( a.object.renderOrder !== b.object.renderOrder ) {
  886. return a.object.renderOrder - b.object.renderOrder;
  887. } if ( a.z !== b.z ) {
  888. return b.z - a.z;
  889. } else {
  890. return a.id - b.id;
  891. }
  892. }
  893. function numericalSort ( a, b ) {
  894. return b[ 0 ] - a[ 0 ];
  895. }
  896. // Rendering
  897. this.render = function ( scene, camera, renderTarget, forceClear ) {
  898. if ( camera instanceof THREE.Camera === false ) {
  899. THREE.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  900. return;
  901. }
  902. var fog = scene.fog;
  903. // reset caching for this frame
  904. _currentGeometryProgram = '';
  905. _currentMaterialId = - 1;
  906. _currentCamera = null;
  907. _lightsNeedUpdate = true;
  908. // update scene graph
  909. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  910. // update camera matrices and frustum
  911. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  912. // update Skeleton objects
  913. scene.traverse( function ( object ) {
  914. if ( object instanceof THREE.SkinnedMesh ) {
  915. object.skeleton.update();
  916. }
  917. } );
  918. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  919. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  920. _frustum.setFromMatrix( _projScreenMatrix );
  921. lights.length = 0;
  922. opaqueObjects.length = 0;
  923. transparentObjects.length = 0;
  924. sprites.length = 0;
  925. lensFlares.length = 0;
  926. projectObject( scene );
  927. if ( _this.sortObjects === true ) {
  928. opaqueObjects.sort( painterSortStable );
  929. transparentObjects.sort( reversePainterSortStable );
  930. }
  931. //
  932. shadowMap.render( scene, camera );
  933. //
  934. _this.info.render.calls = 0;
  935. _this.info.render.vertices = 0;
  936. _this.info.render.faces = 0;
  937. _this.info.render.points = 0;
  938. this.setRenderTarget( renderTarget );
  939. if ( this.autoClear || forceClear ) {
  940. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  941. }
  942. // set matrices for immediate objects
  943. for ( var i = 0, il = objects.objectsImmediate.length; i < il; i ++ ) {
  944. var webglObject = objects.objectsImmediate[ i ];
  945. var object = webglObject.object;
  946. if ( object.visible ) {
  947. setupMatrices( object, camera );
  948. unrollImmediateBufferMaterial( webglObject );
  949. }
  950. }
  951. if ( scene.overrideMaterial ) {
  952. var overrideMaterial = scene.overrideMaterial;
  953. setMaterial( overrideMaterial );
  954. renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
  955. renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
  956. renderObjectsImmediate( objects.objectsImmediate, '', camera, lights, fog, overrideMaterial );
  957. } else {
  958. // opaque pass (front-to-back order)
  959. state.setBlending( THREE.NoBlending );
  960. renderObjects( opaqueObjects, camera, lights, fog, null );
  961. renderObjectsImmediate( objects.objectsImmediate, 'opaque', camera, lights, fog, null );
  962. // transparent pass (back-to-front order)
  963. renderObjects( transparentObjects, camera, lights, fog, null );
  964. renderObjectsImmediate( objects.objectsImmediate, 'transparent', camera, lights, fog, null );
  965. }
  966. // custom render plugins (post pass)
  967. spritePlugin.render( scene, camera );
  968. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  969. // Generate mipmap if we're using any kind of mipmap filtering
  970. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  971. updateRenderTargetMipmap( renderTarget );
  972. }
  973. // Ensure depth buffer writing is enabled so it can be cleared on next render
  974. state.setDepthTest( true );
  975. state.setDepthWrite( true );
  976. state.setColorWrite( true );
  977. // _gl.finish();
  978. };
  979. function projectObject( object ) {
  980. if ( object.visible === false ) return;
  981. if ( object instanceof THREE.Scene || object instanceof THREE.Group ) {
  982. // skip
  983. } else {
  984. objects.init( object );
  985. if ( object instanceof THREE.Light ) {
  986. lights.push( object );
  987. } else if ( object instanceof THREE.Sprite ) {
  988. sprites.push( object );
  989. } else if ( object instanceof THREE.LensFlare ) {
  990. lensFlares.push( object );
  991. } else {
  992. var webglObject = objects.objects[ object.id ];
  993. if ( webglObject && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  994. unrollBufferMaterial( webglObject );
  995. webglObject.render = true;
  996. if ( _this.sortObjects === true ) {
  997. _vector3.setFromMatrixPosition( object.matrixWorld );
  998. _vector3.applyProjection( _projScreenMatrix );
  999. webglObject.z = _vector3.z;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  1005. projectObject( object.children[ i ] );
  1006. }
  1007. }
  1008. function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
  1009. var material;
  1010. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  1011. var webglObject = renderList[ i ];
  1012. var object = webglObject.object;
  1013. var buffer = objects.geometries[ object.geometry.id ];
  1014. setupMatrices( object, camera );
  1015. if ( overrideMaterial ) {
  1016. material = overrideMaterial;
  1017. } else {
  1018. material = webglObject.material;
  1019. if ( ! material ) continue;
  1020. setMaterial( material );
  1021. }
  1022. _this.setMaterialFaces( material );
  1023. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  1024. }
  1025. }
  1026. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, overrideMaterial ) {
  1027. var material;
  1028. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  1029. var webglObject = renderList[ i ];
  1030. var object = webglObject.object;
  1031. if ( object.visible ) {
  1032. if ( overrideMaterial ) {
  1033. material = overrideMaterial;
  1034. } else {
  1035. material = webglObject[ materialType ];
  1036. if ( ! material ) continue;
  1037. setMaterial( material );
  1038. }
  1039. _this.renderImmediateObject( camera, lights, fog, material, object );
  1040. }
  1041. }
  1042. }
  1043. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  1044. var program = setProgram( camera, lights, fog, material, object );
  1045. _currentGeometryProgram = '';
  1046. _this.setMaterialFaces( material );
  1047. if ( object.immediateRenderCallback ) {
  1048. object.immediateRenderCallback( program, _gl, _frustum );
  1049. } else {
  1050. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  1051. }
  1052. };
  1053. function unrollImmediateBufferMaterial ( globject ) {
  1054. var object = globject.object,
  1055. material = object.material;
  1056. if ( material.transparent ) {
  1057. globject.transparent = material;
  1058. globject.opaque = null;
  1059. } else {
  1060. globject.opaque = material;
  1061. globject.transparent = null;
  1062. }
  1063. }
  1064. function unrollBufferMaterial ( globject ) {
  1065. var object = globject.object;
  1066. var material = object.material;
  1067. if ( material ) {
  1068. globject.material = material;
  1069. if ( material.transparent ) {
  1070. transparentObjects.push( globject );
  1071. } else {
  1072. opaqueObjects.push( globject );
  1073. }
  1074. }
  1075. }
  1076. // Materials
  1077. var shaderIDs = {
  1078. MeshDepthMaterial: 'depth',
  1079. MeshNormalMaterial: 'normal',
  1080. MeshBasicMaterial: 'basic',
  1081. MeshLambertMaterial: 'lambert',
  1082. MeshPhongMaterial: 'phong',
  1083. LineBasicMaterial: 'basic',
  1084. LineDashedMaterial: 'dashed',
  1085. PointCloudMaterial: 'particle_basic'
  1086. };
  1087. function initMaterial( material, lights, fog, object ) {
  1088. var shaderID = shaderIDs[ material.type ];
  1089. // heuristics to create shader parameters according to lights in the scene
  1090. // (not to blow over maxLights budget)
  1091. var maxLightCount = allocateLights( lights );
  1092. var maxShadows = allocateShadows( lights );
  1093. var maxBones = allocateBones( object );
  1094. var parameters = {
  1095. precision: _precision,
  1096. supportsVertexTextures: _supportsVertexTextures,
  1097. map: !! material.map,
  1098. envMap: !! material.envMap,
  1099. envMapMode: material.envMap && material.envMap.mapping,
  1100. lightMap: !! material.lightMap,
  1101. aoMap: !! material.aoMap,
  1102. bumpMap: !! material.bumpMap,
  1103. normalMap: !! material.normalMap,
  1104. specularMap: !! material.specularMap,
  1105. alphaMap: !! material.alphaMap,
  1106. combine: material.combine,
  1107. vertexColors: material.vertexColors,
  1108. fog: fog,
  1109. useFog: material.fog,
  1110. fogExp: fog instanceof THREE.FogExp2,
  1111. flatShading: material.shading === THREE.FlatShading,
  1112. sizeAttenuation: material.sizeAttenuation,
  1113. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  1114. skinning: material.skinning,
  1115. maxBones: maxBones,
  1116. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  1117. morphTargets: material.morphTargets,
  1118. morphNormals: material.morphNormals,
  1119. maxMorphTargets: _this.maxMorphTargets,
  1120. maxMorphNormals: _this.maxMorphNormals,
  1121. maxDirLights: maxLightCount.directional,
  1122. maxPointLights: maxLightCount.point,
  1123. maxSpotLights: maxLightCount.spot,
  1124. maxHemiLights: maxLightCount.hemi,
  1125. maxShadows: maxShadows,
  1126. shadowMapEnabled: shadowMap.enabled && object.receiveShadow && maxShadows > 0,
  1127. shadowMapType: shadowMap.type,
  1128. shadowMapDebug: shadowMap.debug,
  1129. shadowMapCascade: shadowMap.cascade,
  1130. alphaTest: material.alphaTest,
  1131. metal: material.metal,
  1132. doubleSided: material.side === THREE.DoubleSide,
  1133. flipSided: material.side === THREE.BackSide
  1134. };
  1135. // Generate code
  1136. var chunks = [];
  1137. if ( shaderID ) {
  1138. chunks.push( shaderID );
  1139. } else {
  1140. chunks.push( material.fragmentShader );
  1141. chunks.push( material.vertexShader );
  1142. }
  1143. if ( material.defines !== undefined ) {
  1144. for ( var name in material.defines ) {
  1145. chunks.push( name );
  1146. chunks.push( material.defines[ name ] );
  1147. }
  1148. }
  1149. for ( var name in parameters ) {
  1150. chunks.push( name );
  1151. chunks.push( parameters[ name ] );
  1152. }
  1153. var code = chunks.join();
  1154. if ( !material.program ) {
  1155. // new material
  1156. material.addEventListener( 'dispose', onMaterialDispose );
  1157. } else if ( material.program.code !== code ) {
  1158. // changed glsl or parameters
  1159. deallocateMaterial( material );
  1160. } else {
  1161. // same glsl and parameters
  1162. return;
  1163. }
  1164. if ( shaderID ) {
  1165. var shader = THREE.ShaderLib[ shaderID ];
  1166. material.__webglShader = {
  1167. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  1168. vertexShader: shader.vertexShader,
  1169. fragmentShader: shader.fragmentShader
  1170. }
  1171. } else {
  1172. material.__webglShader = {
  1173. uniforms: material.uniforms,
  1174. vertexShader: material.vertexShader,
  1175. fragmentShader: material.fragmentShader
  1176. }
  1177. }
  1178. var program;
  1179. // Check if code has been already compiled
  1180. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  1181. var programInfo = _programs[ p ];
  1182. if ( programInfo.code === code ) {
  1183. program = programInfo;
  1184. program.usedTimes ++;
  1185. break;
  1186. }
  1187. }
  1188. if ( program === undefined ) {
  1189. program = new THREE.WebGLProgram( _this, code, material, parameters );
  1190. _programs.push( program );
  1191. _this.info.memory.programs = _programs.length;
  1192. }
  1193. material.program = program;
  1194. var attributes = program.attributes;
  1195. if ( material.morphTargets ) {
  1196. material.numSupportedMorphTargets = 0;
  1197. var id, base = 'morphTarget';
  1198. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  1199. id = base + i;
  1200. if ( attributes[ id ] >= 0 ) {
  1201. material.numSupportedMorphTargets ++;
  1202. }
  1203. }
  1204. }
  1205. if ( material.morphNormals ) {
  1206. material.numSupportedMorphNormals = 0;
  1207. var id, base = 'morphNormal';
  1208. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  1209. id = base + i;
  1210. if ( attributes[ id ] >= 0 ) {
  1211. material.numSupportedMorphNormals ++;
  1212. }
  1213. }
  1214. }
  1215. material.uniformsList = [];
  1216. for ( var u in material.__webglShader.uniforms ) {
  1217. var location = material.program.uniforms[ u ];
  1218. if ( location ) {
  1219. material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] );
  1220. }
  1221. }
  1222. }
  1223. function setMaterial( material ) {
  1224. if ( material.transparent === true ) {
  1225. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  1226. } else {
  1227. state.setBlending( THREE.NoBlending );
  1228. }
  1229. state.setDepthFunc( material.depthFunc );
  1230. state.setDepthTest( material.depthTest );
  1231. state.setDepthWrite( material.depthWrite );
  1232. state.setColorWrite( material.colorWrite );
  1233. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  1234. }
  1235. function setProgram( camera, lights, fog, material, object ) {
  1236. _usedTextureUnits = 0;
  1237. if ( material.needsUpdate ) {
  1238. initMaterial( material, lights, fog, object );
  1239. material.needsUpdate = false;
  1240. }
  1241. if ( material.morphTargets ) {
  1242. if ( ! object.__webglMorphTargetInfluences ) {
  1243. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  1244. }
  1245. }
  1246. var refreshProgram = false;
  1247. var refreshMaterial = false;
  1248. var refreshLights = false;
  1249. var program = material.program,
  1250. p_uniforms = program.uniforms,
  1251. m_uniforms = material.__webglShader.uniforms;
  1252. if ( program.id !== _currentProgram ) {
  1253. _gl.useProgram( program.program );
  1254. _currentProgram = program.id;
  1255. refreshProgram = true;
  1256. refreshMaterial = true;
  1257. refreshLights = true;
  1258. }
  1259. if ( material.id !== _currentMaterialId ) {
  1260. if ( _currentMaterialId === -1 ) refreshLights = true;
  1261. _currentMaterialId = material.id;
  1262. refreshMaterial = true;
  1263. }
  1264. if ( refreshProgram || camera !== _currentCamera ) {
  1265. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  1266. if ( _logarithmicDepthBuffer ) {
  1267. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1268. }
  1269. if ( camera !== _currentCamera ) _currentCamera = camera;
  1270. // load material specific uniforms
  1271. // (shader material also gets them for the sake of genericity)
  1272. if ( material instanceof THREE.ShaderMaterial ||
  1273. material instanceof THREE.MeshPhongMaterial ||
  1274. material.envMap ) {
  1275. if ( p_uniforms.cameraPosition !== null ) {
  1276. _vector3.setFromMatrixPosition( camera.matrixWorld );
  1277. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  1278. }
  1279. }
  1280. if ( material instanceof THREE.MeshPhongMaterial ||
  1281. material instanceof THREE.MeshLambertMaterial ||
  1282. material instanceof THREE.MeshBasicMaterial ||
  1283. material instanceof THREE.ShaderMaterial ||
  1284. material.skinning ) {
  1285. if ( p_uniforms.viewMatrix !== null ) {
  1286. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  1287. }
  1288. }
  1289. }
  1290. // skinning uniforms must be set even if material didn't change
  1291. // auto-setting of texture unit for bone texture must go before other textures
  1292. // not sure why, but otherwise weird things happen
  1293. if ( material.skinning ) {
  1294. if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) {
  1295. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  1296. }
  1297. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) {
  1298. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  1299. }
  1300. if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  1301. if ( p_uniforms.boneTexture !== null ) {
  1302. var textureUnit = getTextureUnit();
  1303. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  1304. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  1305. }
  1306. if ( p_uniforms.boneTextureWidth !== null ) {
  1307. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  1308. }
  1309. if ( p_uniforms.boneTextureHeight !== null ) {
  1310. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  1311. }
  1312. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  1313. if ( p_uniforms.boneGlobalMatrices !== null ) {
  1314. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  1315. }
  1316. }
  1317. }
  1318. if ( refreshMaterial ) {
  1319. // refresh uniforms common to several materials
  1320. if ( fog && material.fog ) {
  1321. refreshUniformsFog( m_uniforms, fog );
  1322. }
  1323. if ( material instanceof THREE.MeshPhongMaterial ||
  1324. material instanceof THREE.MeshLambertMaterial ||
  1325. material.lights ) {
  1326. if ( _lightsNeedUpdate ) {
  1327. refreshLights = true;
  1328. setupLights( lights );
  1329. _lightsNeedUpdate = false;
  1330. }
  1331. if ( refreshLights ) {
  1332. refreshUniformsLights( m_uniforms, _lights );
  1333. markUniformsLightsNeedsUpdate( m_uniforms, true );
  1334. } else {
  1335. markUniformsLightsNeedsUpdate( m_uniforms, false );
  1336. }
  1337. }
  1338. if ( material instanceof THREE.MeshBasicMaterial ||
  1339. material instanceof THREE.MeshLambertMaterial ||
  1340. material instanceof THREE.MeshPhongMaterial ) {
  1341. refreshUniformsCommon( m_uniforms, material );
  1342. }
  1343. // refresh single material specific uniforms
  1344. if ( material instanceof THREE.LineBasicMaterial ) {
  1345. refreshUniformsLine( m_uniforms, material );
  1346. } else if ( material instanceof THREE.LineDashedMaterial ) {
  1347. refreshUniformsLine( m_uniforms, material );
  1348. refreshUniformsDash( m_uniforms, material );
  1349. } else if ( material instanceof THREE.PointCloudMaterial ) {
  1350. refreshUniformsParticle( m_uniforms, material );
  1351. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  1352. refreshUniformsPhong( m_uniforms, material );
  1353. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  1354. refreshUniformsLambert( m_uniforms, material );
  1355. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  1356. m_uniforms.mNear.value = camera.near;
  1357. m_uniforms.mFar.value = camera.far;
  1358. m_uniforms.opacity.value = material.opacity;
  1359. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  1360. m_uniforms.opacity.value = material.opacity;
  1361. }
  1362. if ( object.receiveShadow && ! material._shadowPass ) {
  1363. refreshUniformsShadow( m_uniforms, lights );
  1364. }
  1365. // load common uniforms
  1366. loadUniformsGeneric( material.uniformsList );
  1367. }
  1368. loadUniformsMatrices( p_uniforms, object );
  1369. if ( p_uniforms.modelMatrix !== null ) {
  1370. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  1371. }
  1372. return program;
  1373. }
  1374. // Uniforms (refresh uniforms objects)
  1375. function refreshUniformsCommon ( uniforms, material ) {
  1376. uniforms.opacity.value = material.opacity;
  1377. uniforms.diffuse.value = material.color;
  1378. uniforms.map.value = material.map;
  1379. uniforms.specularMap.value = material.specularMap;
  1380. uniforms.alphaMap.value = material.alphaMap;
  1381. if ( material.bumpMap ) {
  1382. uniforms.bumpMap.value = material.bumpMap;
  1383. uniforms.bumpScale.value = material.bumpScale;
  1384. }
  1385. if ( material.normalMap ) {
  1386. uniforms.normalMap.value = material.normalMap;
  1387. uniforms.normalScale.value.copy( material.normalScale );
  1388. }
  1389. // uv repeat and offset setting priorities
  1390. // 1. color map
  1391. // 2. specular map
  1392. // 3. normal map
  1393. // 4. bump map
  1394. // 5. alpha map
  1395. var uvScaleMap;
  1396. if ( material.map ) {
  1397. uvScaleMap = material.map;
  1398. } else if ( material.specularMap ) {
  1399. uvScaleMap = material.specularMap;
  1400. } else if ( material.normalMap ) {
  1401. uvScaleMap = material.normalMap;
  1402. } else if ( material.bumpMap ) {
  1403. uvScaleMap = material.bumpMap;
  1404. } else if ( material.alphaMap ) {
  1405. uvScaleMap = material.alphaMap;
  1406. }
  1407. if ( uvScaleMap !== undefined ) {
  1408. var offset = uvScaleMap.offset;
  1409. var repeat = uvScaleMap.repeat;
  1410. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1411. }
  1412. uniforms.envMap.value = material.envMap;
  1413. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  1414. uniforms.reflectivity.value = material.reflectivity;
  1415. uniforms.refractionRatio.value = material.refractionRatio;
  1416. }
  1417. function refreshUniformsLine ( uniforms, material ) {
  1418. uniforms.diffuse.value = material.color;
  1419. uniforms.opacity.value = material.opacity;
  1420. }
  1421. function refreshUniformsDash ( uniforms, material ) {
  1422. uniforms.dashSize.value = material.dashSize;
  1423. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1424. uniforms.scale.value = material.scale;
  1425. }
  1426. function refreshUniformsParticle ( uniforms, material ) {
  1427. uniforms.psColor.value = material.color;
  1428. uniforms.opacity.value = material.opacity;
  1429. uniforms.size.value = material.size;
  1430. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  1431. uniforms.map.value = material.map;
  1432. if ( material.map !== null ) {
  1433. var offset = material.map.offset;
  1434. var repeat = material.map.repeat;
  1435. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1436. }
  1437. }
  1438. function refreshUniformsFog ( uniforms, fog ) {
  1439. uniforms.fogColor.value = fog.color;
  1440. if ( fog instanceof THREE.Fog ) {
  1441. uniforms.fogNear.value = fog.near;
  1442. uniforms.fogFar.value = fog.far;
  1443. } else if ( fog instanceof THREE.FogExp2 ) {
  1444. uniforms.fogDensity.value = fog.density;
  1445. }
  1446. }
  1447. function refreshUniformsPhong ( uniforms, material ) {
  1448. uniforms.shininess.value = material.shininess;
  1449. uniforms.emissive.value = material.emissive;
  1450. uniforms.specular.value = material.specular;
  1451. uniforms.lightMap.value = material.lightMap;
  1452. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1453. uniforms.aoMap.value = material.aoMap;
  1454. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1455. }
  1456. function refreshUniformsLambert ( uniforms, material ) {
  1457. uniforms.emissive.value = material.emissive;
  1458. }
  1459. function refreshUniformsLights ( uniforms, lights ) {
  1460. uniforms.ambientLightColor.value = lights.ambient;
  1461. uniforms.directionalLightColor.value = lights.directional.colors;
  1462. uniforms.directionalLightDirection.value = lights.directional.positions;
  1463. uniforms.pointLightColor.value = lights.point.colors;
  1464. uniforms.pointLightPosition.value = lights.point.positions;
  1465. uniforms.pointLightDistance.value = lights.point.distances;
  1466. uniforms.pointLightDecay.value = lights.point.decays;
  1467. uniforms.spotLightColor.value = lights.spot.colors;
  1468. uniforms.spotLightPosition.value = lights.spot.positions;
  1469. uniforms.spotLightDistance.value = lights.spot.distances;
  1470. uniforms.spotLightDirection.value = lights.spot.directions;
  1471. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  1472. uniforms.spotLightExponent.value = lights.spot.exponents;
  1473. uniforms.spotLightDecay.value = lights.spot.decays;
  1474. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  1475. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  1476. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  1477. }
  1478. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1479. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  1480. uniforms.ambientLightColor.needsUpdate = value;
  1481. uniforms.directionalLightColor.needsUpdate = value;
  1482. uniforms.directionalLightDirection.needsUpdate = value;
  1483. uniforms.pointLightColor.needsUpdate = value;
  1484. uniforms.pointLightPosition.needsUpdate = value;
  1485. uniforms.pointLightDistance.needsUpdate = value;
  1486. uniforms.pointLightDecay.needsUpdate = value;
  1487. uniforms.spotLightColor.needsUpdate = value;
  1488. uniforms.spotLightPosition.needsUpdate = value;
  1489. uniforms.spotLightDistance.needsUpdate = value;
  1490. uniforms.spotLightDirection.needsUpdate = value;
  1491. uniforms.spotLightAngleCos.needsUpdate = value;
  1492. uniforms.spotLightExponent.needsUpdate = value;
  1493. uniforms.spotLightDecay.needsUpdate = value;
  1494. uniforms.hemisphereLightSkyColor.needsUpdate = value;
  1495. uniforms.hemisphereLightGroundColor.needsUpdate = value;
  1496. uniforms.hemisphereLightDirection.needsUpdate = value;
  1497. }
  1498. function refreshUniformsShadow ( uniforms, lights ) {
  1499. if ( uniforms.shadowMatrix ) {
  1500. var j = 0;
  1501. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  1502. var light = lights[ i ];
  1503. if ( ! light.castShadow ) continue;
  1504. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  1505. uniforms.shadowMap.value[ j ] = light.shadowMap;
  1506. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  1507. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  1508. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  1509. uniforms.shadowBias.value[ j ] = light.shadowBias;
  1510. j ++;
  1511. }
  1512. }
  1513. }
  1514. }
  1515. // Uniforms (load to GPU)
  1516. function loadUniformsMatrices ( uniforms, object ) {
  1517. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  1518. if ( uniforms.normalMatrix ) {
  1519. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  1520. }
  1521. }
  1522. function getTextureUnit() {
  1523. var textureUnit = _usedTextureUnits;
  1524. if ( textureUnit >= _maxTextures ) {
  1525. THREE.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  1526. }
  1527. _usedTextureUnits += 1;
  1528. return textureUnit;
  1529. }
  1530. function loadUniformsGeneric ( uniforms ) {
  1531. var texture, textureUnit, offset;
  1532. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  1533. var uniform = uniforms[ j ][ 0 ];
  1534. // needsUpdate property is not added to all uniforms.
  1535. if ( uniform.needsUpdate === false ) continue;
  1536. var type = uniform.type;
  1537. var value = uniform.value;
  1538. var location = uniforms[ j ][ 1 ];
  1539. switch ( type ) {
  1540. case '1i':
  1541. _gl.uniform1i( location, value );
  1542. break;
  1543. case '1f':
  1544. _gl.uniform1f( location, value );
  1545. break;
  1546. case '2f':
  1547. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  1548. break;
  1549. case '3f':
  1550. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  1551. break;
  1552. case '4f':
  1553. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  1554. break;
  1555. case '1iv':
  1556. _gl.uniform1iv( location, value );
  1557. break;
  1558. case '3iv':
  1559. _gl.uniform3iv( location, value );
  1560. break;
  1561. case '1fv':
  1562. _gl.uniform1fv( location, value );
  1563. break;
  1564. case '2fv':
  1565. _gl.uniform2fv( location, value );
  1566. break;
  1567. case '3fv':
  1568. _gl.uniform3fv( location, value );
  1569. break;
  1570. case '4fv':
  1571. _gl.uniform4fv( location, value );
  1572. break;
  1573. case 'Matrix3fv':
  1574. _gl.uniformMatrix3fv( location, false, value );
  1575. break;
  1576. case 'Matrix4fv':
  1577. _gl.uniformMatrix4fv( location, false, value );
  1578. break;
  1579. //
  1580. case 'i':
  1581. // single integer
  1582. _gl.uniform1i( location, value );
  1583. break;
  1584. case 'f':
  1585. // single float
  1586. _gl.uniform1f( location, value );
  1587. break;
  1588. case 'v2':
  1589. // single THREE.Vector2
  1590. _gl.uniform2f( location, value.x, value.y );
  1591. break;
  1592. case 'v3':
  1593. // single THREE.Vector3
  1594. _gl.uniform3f( location, value.x, value.y, value.z );
  1595. break;
  1596. case 'v4':
  1597. // single THREE.Vector4
  1598. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  1599. break;
  1600. case 'c':
  1601. // single THREE.Color
  1602. _gl.uniform3f( location, value.r, value.g, value.b );
  1603. break;
  1604. case 'iv1':
  1605. // flat array of integers (JS or typed array)
  1606. _gl.uniform1iv( location, value );
  1607. break;
  1608. case 'iv':
  1609. // flat array of integers with 3 x N size (JS or typed array)
  1610. _gl.uniform3iv( location, value );
  1611. break;
  1612. case 'fv1':
  1613. // flat array of floats (JS or typed array)
  1614. _gl.uniform1fv( location, value );
  1615. break;
  1616. case 'fv':
  1617. // flat array of floats with 3 x N size (JS or typed array)
  1618. _gl.uniform3fv( location, value );
  1619. break;
  1620. case 'v2v':
  1621. // array of THREE.Vector2
  1622. if ( uniform._array === undefined ) {
  1623. uniform._array = new Float32Array( 2 * value.length );
  1624. }
  1625. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1626. offset = i * 2;
  1627. uniform._array[ offset + 0 ] = value[ i ].x;
  1628. uniform._array[ offset + 1 ] = value[ i ].y;
  1629. }
  1630. _gl.uniform2fv( location, uniform._array );
  1631. break;
  1632. case 'v3v':
  1633. // array of THREE.Vector3
  1634. if ( uniform._array === undefined ) {
  1635. uniform._array = new Float32Array( 3 * value.length );
  1636. }
  1637. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1638. offset = i * 3;
  1639. uniform._array[ offset + 0 ] = value[ i ].x;
  1640. uniform._array[ offset + 1 ] = value[ i ].y;
  1641. uniform._array[ offset + 2 ] = value[ i ].z;
  1642. }
  1643. _gl.uniform3fv( location, uniform._array );
  1644. break;
  1645. case 'v4v':
  1646. // array of THREE.Vector4
  1647. if ( uniform._array === undefined ) {
  1648. uniform._array = new Float32Array( 4 * value.length );
  1649. }
  1650. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1651. offset = i * 4;
  1652. uniform._array[ offset + 0 ] = value[ i ].x;
  1653. uniform._array[ offset + 1 ] = value[ i ].y;
  1654. uniform._array[ offset + 2 ] = value[ i ].z;
  1655. uniform._array[ offset + 3 ] = value[ i ].w;
  1656. }
  1657. _gl.uniform4fv( location, uniform._array );
  1658. break;
  1659. case 'm3':
  1660. // single THREE.Matrix3
  1661. _gl.uniformMatrix3fv( location, false, value.elements );
  1662. break;
  1663. case 'm3v':
  1664. // array of THREE.Matrix3
  1665. if ( uniform._array === undefined ) {
  1666. uniform._array = new Float32Array( 9 * value.length );
  1667. }
  1668. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1669. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  1670. }
  1671. _gl.uniformMatrix3fv( location, false, uniform._array );
  1672. break;
  1673. case 'm4':
  1674. // single THREE.Matrix4
  1675. _gl.uniformMatrix4fv( location, false, value.elements );
  1676. break;
  1677. case 'm4v':
  1678. // array of THREE.Matrix4
  1679. if ( uniform._array === undefined ) {
  1680. uniform._array = new Float32Array( 16 * value.length );
  1681. }
  1682. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1683. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  1684. }
  1685. _gl.uniformMatrix4fv( location, false, uniform._array );
  1686. break;
  1687. case 't':
  1688. // single THREE.Texture (2d or cube)
  1689. texture = value;
  1690. textureUnit = getTextureUnit();
  1691. _gl.uniform1i( location, textureUnit );
  1692. if ( ! texture ) continue;
  1693. if ( texture instanceof THREE.CubeTexture ||
  1694. ( texture.image instanceof Array && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  1695. setCubeTexture( texture, textureUnit );
  1696. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  1697. setCubeTextureDynamic( texture, textureUnit );
  1698. } else {
  1699. _this.setTexture( texture, textureUnit );
  1700. }
  1701. break;
  1702. case 'tv':
  1703. // array of THREE.Texture (2d)
  1704. if ( uniform._array === undefined ) {
  1705. uniform._array = [];
  1706. }
  1707. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  1708. uniform._array[ i ] = getTextureUnit();
  1709. }
  1710. _gl.uniform1iv( location, uniform._array );
  1711. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  1712. texture = uniform.value[ i ];
  1713. textureUnit = uniform._array[ i ];
  1714. if ( ! texture ) continue;
  1715. _this.setTexture( texture, textureUnit );
  1716. }
  1717. break;
  1718. default:
  1719. THREE.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  1720. }
  1721. }
  1722. }
  1723. function setupMatrices ( object, camera ) {
  1724. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  1725. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  1726. }
  1727. function setColorLinear( array, offset, color, intensity ) {
  1728. array[ offset + 0 ] = color.r * intensity;
  1729. array[ offset + 1 ] = color.g * intensity;
  1730. array[ offset + 2 ] = color.b * intensity;
  1731. }
  1732. function setupLights ( lights ) {
  1733. var l, ll, light,
  1734. r = 0, g = 0, b = 0,
  1735. color, skyColor, groundColor,
  1736. intensity,
  1737. distance,
  1738. zlights = _lights,
  1739. dirColors = zlights.directional.colors,
  1740. dirPositions = zlights.directional.positions,
  1741. pointColors = zlights.point.colors,
  1742. pointPositions = zlights.point.positions,
  1743. pointDistances = zlights.point.distances,
  1744. pointDecays = zlights.point.decays,
  1745. spotColors = zlights.spot.colors,
  1746. spotPositions = zlights.spot.positions,
  1747. spotDistances = zlights.spot.distances,
  1748. spotDirections = zlights.spot.directions,
  1749. spotAnglesCos = zlights.spot.anglesCos,
  1750. spotExponents = zlights.spot.exponents,
  1751. spotDecays = zlights.spot.decays,
  1752. hemiSkyColors = zlights.hemi.skyColors,
  1753. hemiGroundColors = zlights.hemi.groundColors,
  1754. hemiPositions = zlights.hemi.positions,
  1755. dirLength = 0,
  1756. pointLength = 0,
  1757. spotLength = 0,
  1758. hemiLength = 0,
  1759. dirCount = 0,
  1760. pointCount = 0,
  1761. spotCount = 0,
  1762. hemiCount = 0,
  1763. dirOffset = 0,
  1764. pointOffset = 0,
  1765. spotOffset = 0,
  1766. hemiOffset = 0;
  1767. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  1768. light = lights[ l ];
  1769. if ( light.onlyShadow ) continue;
  1770. color = light.color;
  1771. intensity = light.intensity;
  1772. distance = light.distance;
  1773. if ( light instanceof THREE.AmbientLight ) {
  1774. if ( ! light.visible ) continue;
  1775. r += color.r;
  1776. g += color.g;
  1777. b += color.b;
  1778. } else if ( light instanceof THREE.DirectionalLight ) {
  1779. dirCount += 1;
  1780. if ( ! light.visible ) continue;
  1781. _direction.setFromMatrixPosition( light.matrixWorld );
  1782. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1783. _direction.sub( _vector3 );
  1784. _direction.normalize();
  1785. dirOffset = dirLength * 3;
  1786. dirPositions[ dirOffset + 0 ] = _direction.x;
  1787. dirPositions[ dirOffset + 1 ] = _direction.y;
  1788. dirPositions[ dirOffset + 2 ] = _direction.z;
  1789. setColorLinear( dirColors, dirOffset, color, intensity );
  1790. dirLength += 1;
  1791. } else if ( light instanceof THREE.PointLight ) {
  1792. pointCount += 1;
  1793. if ( ! light.visible ) continue;
  1794. pointOffset = pointLength * 3;
  1795. setColorLinear( pointColors, pointOffset, color, intensity );
  1796. _vector3.setFromMatrixPosition( light.matrixWorld );
  1797. pointPositions[ pointOffset + 0 ] = _vector3.x;
  1798. pointPositions[ pointOffset + 1 ] = _vector3.y;
  1799. pointPositions[ pointOffset + 2 ] = _vector3.z;
  1800. // distance is 0 if decay is 0, because there is no attenuation at all.
  1801. pointDistances[ pointLength ] = distance;
  1802. pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  1803. pointLength += 1;
  1804. } else if ( light instanceof THREE.SpotLight ) {
  1805. spotCount += 1;
  1806. if ( ! light.visible ) continue;
  1807. spotOffset = spotLength * 3;
  1808. setColorLinear( spotColors, spotOffset, color, intensity );
  1809. _direction.setFromMatrixPosition( light.matrixWorld );
  1810. spotPositions[ spotOffset + 0 ] = _direction.x;
  1811. spotPositions[ spotOffset + 1 ] = _direction.y;
  1812. spotPositions[ spotOffset + 2 ] = _direction.z;
  1813. spotDistances[ spotLength ] = distance;
  1814. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1815. _direction.sub( _vector3 );
  1816. _direction.normalize();
  1817. spotDirections[ spotOffset + 0 ] = _direction.x;
  1818. spotDirections[ spotOffset + 1 ] = _direction.y;
  1819. spotDirections[ spotOffset + 2 ] = _direction.z;
  1820. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  1821. spotExponents[ spotLength ] = light.exponent;
  1822. spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  1823. spotLength += 1;
  1824. } else if ( light instanceof THREE.HemisphereLight ) {
  1825. hemiCount += 1;
  1826. if ( ! light.visible ) continue;
  1827. _direction.setFromMatrixPosition( light.matrixWorld );
  1828. _direction.normalize();
  1829. hemiOffset = hemiLength * 3;
  1830. hemiPositions[ hemiOffset + 0 ] = _direction.x;
  1831. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  1832. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  1833. skyColor = light.color;
  1834. groundColor = light.groundColor;
  1835. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  1836. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  1837. hemiLength += 1;
  1838. }
  1839. }
  1840. // null eventual remains from removed lights
  1841. // (this is to avoid if in shader)
  1842. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  1843. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  1844. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  1845. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  1846. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  1847. zlights.directional.length = dirLength;
  1848. zlights.point.length = pointLength;
  1849. zlights.spot.length = spotLength;
  1850. zlights.hemi.length = hemiLength;
  1851. zlights.ambient[ 0 ] = r;
  1852. zlights.ambient[ 1 ] = g;
  1853. zlights.ambient[ 2 ] = b;
  1854. }
  1855. // GL state setting
  1856. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  1857. if ( cullFace === THREE.CullFaceNone ) {
  1858. _gl.disable( _gl.CULL_FACE );
  1859. } else {
  1860. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  1861. _gl.frontFace( _gl.CW );
  1862. } else {
  1863. _gl.frontFace( _gl.CCW );
  1864. }
  1865. if ( cullFace === THREE.CullFaceBack ) {
  1866. _gl.cullFace( _gl.BACK );
  1867. } else if ( cullFace === THREE.CullFaceFront ) {
  1868. _gl.cullFace( _gl.FRONT );
  1869. } else {
  1870. _gl.cullFace( _gl.FRONT_AND_BACK );
  1871. }
  1872. _gl.enable( _gl.CULL_FACE );
  1873. }
  1874. };
  1875. this.setMaterialFaces = function ( material ) {
  1876. state.setDoubleSided( material.side === THREE.DoubleSide );
  1877. state.setFlipSided( material.side === THREE.BackSide );
  1878. };
  1879. // Textures
  1880. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  1881. var extension;
  1882. if ( isImagePowerOfTwo ) {
  1883. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  1884. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  1885. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  1886. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  1887. } else {
  1888. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  1889. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  1890. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  1891. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' );
  1892. }
  1893. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  1894. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  1895. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  1896. THREE.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' );
  1897. }
  1898. }
  1899. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  1900. if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) {
  1901. if ( texture.anisotropy > 1 || texture.__currentAnisotropy ) {
  1902. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  1903. texture.__currentAnisotropy = texture.anisotropy;
  1904. }
  1905. }
  1906. }
  1907. this.uploadTexture = function ( texture, slot ) {
  1908. if ( texture.__webglInit === undefined ) {
  1909. texture.__webglInit = true;
  1910. texture.addEventListener( 'dispose', onTextureDispose );
  1911. texture.__webglTexture = _gl.createTexture();
  1912. _this.info.memory.textures ++;
  1913. }
  1914. _gl.activeTexture( _gl.TEXTURE0 + slot );
  1915. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  1916. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  1917. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  1918. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  1919. texture.image = clampToMaxSize( texture.image, _maxTextureSize );
  1920. var image = texture.image,
  1921. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  1922. glFormat = paramThreeToGL( texture.format ),
  1923. glType = paramThreeToGL( texture.type );
  1924. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  1925. var mipmap, mipmaps = texture.mipmaps;
  1926. if ( texture instanceof THREE.DataTexture ) {
  1927. // use manually created mipmaps if available
  1928. // if there are no manual mipmaps
  1929. // set 0 level mipmap and then use GL to generate other mipmap levels
  1930. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  1931. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1932. mipmap = mipmaps[ i ];
  1933. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1934. }
  1935. texture.generateMipmaps = false;
  1936. } else {
  1937. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  1938. }
  1939. } else if ( texture instanceof THREE.CompressedTexture ) {
  1940. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1941. mipmap = mipmaps[ i ];
  1942. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  1943. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  1944. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  1945. } else {
  1946. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  1947. }
  1948. } else {
  1949. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1950. }
  1951. }
  1952. } else { // regular Texture (image, video, canvas)
  1953. // use manually created mipmaps if available
  1954. // if there are no manual mipmaps
  1955. // set 0 level mipmap and then use GL to generate other mipmap levels
  1956. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  1957. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1958. mipmap = mipmaps[ i ];
  1959. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  1960. }
  1961. texture.generateMipmaps = false;
  1962. } else {
  1963. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  1964. }
  1965. }
  1966. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1967. texture.needsUpdate = false;
  1968. if ( texture.onUpdate ) texture.onUpdate( texture );
  1969. };
  1970. this.setTexture = function ( texture, slot ) {
  1971. if ( texture.needsUpdate === true ) {
  1972. var image = texture.image;
  1973. if ( image.complete === false ) {
  1974. THREE.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  1975. return;
  1976. }
  1977. _this.uploadTexture( texture, slot );
  1978. return;
  1979. }
  1980. _gl.activeTexture( _gl.TEXTURE0 + slot );
  1981. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  1982. };
  1983. function clampToMaxSize ( image, maxSize ) {
  1984. if ( image.width > maxSize || image.height > maxSize ) {
  1985. // Warning: Scaling through the canvas will only work with images that use
  1986. // premultiplied alpha.
  1987. var scale = maxSize / Math.max( image.width, image.height );
  1988. var canvas = document.createElement( 'canvas' );
  1989. canvas.width = Math.floor( image.width * scale );
  1990. canvas.height = Math.floor( image.height * scale );
  1991. var context = canvas.getContext( '2d' );
  1992. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  1993. THREE.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  1994. return canvas;
  1995. }
  1996. return image;
  1997. }
  1998. function setCubeTexture ( texture, slot ) {
  1999. if ( texture.image.length === 6 ) {
  2000. if ( texture.needsUpdate ) {
  2001. if ( ! texture.image.__webglTextureCube ) {
  2002. texture.addEventListener( 'dispose', onTextureDispose );
  2003. texture.image.__webglTextureCube = _gl.createTexture();
  2004. _this.info.memory.textures ++;
  2005. }
  2006. _gl.activeTexture( _gl.TEXTURE0 + slot );
  2007. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  2008. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  2009. var isCompressed = texture instanceof THREE.CompressedTexture;
  2010. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  2011. var cubeImage = [];
  2012. for ( var i = 0; i < 6; i ++ ) {
  2013. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  2014. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  2015. } else {
  2016. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  2017. }
  2018. }
  2019. var image = cubeImage[ 0 ],
  2020. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  2021. glFormat = paramThreeToGL( texture.format ),
  2022. glType = paramThreeToGL( texture.type );
  2023. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  2024. for ( var i = 0; i < 6; i ++ ) {
  2025. if ( ! isCompressed ) {
  2026. if ( isDataTexture ) {
  2027. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  2028. } else {
  2029. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  2030. }
  2031. } else {
  2032. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  2033. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  2034. mipmap = mipmaps[ j ];
  2035. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  2036. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  2037. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  2038. } else {
  2039. THREE.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  2040. }
  2041. } else {
  2042. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  2043. }
  2044. }
  2045. }
  2046. }
  2047. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  2048. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  2049. }
  2050. texture.needsUpdate = false;
  2051. if ( texture.onUpdate ) texture.onUpdate( texture );
  2052. } else {
  2053. _gl.activeTexture( _gl.TEXTURE0 + slot );
  2054. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  2055. }
  2056. }
  2057. }
  2058. function setCubeTextureDynamic ( texture, slot ) {
  2059. _gl.activeTexture( _gl.TEXTURE0 + slot );
  2060. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  2061. }
  2062. // Render targets
  2063. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  2064. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  2065. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  2066. }
  2067. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  2068. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  2069. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  2070. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  2071. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  2072. /* For some reason this is not working. Defaulting to RGBA4.
  2073. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  2074. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  2075. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  2076. */
  2077. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  2078. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  2079. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  2080. } else {
  2081. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  2082. }
  2083. }
  2084. this.setRenderTarget = function ( renderTarget ) {
  2085. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  2086. if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) {
  2087. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  2088. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  2089. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  2090. renderTarget.__webglTexture = _gl.createTexture();
  2091. _this.info.memory.textures ++;
  2092. // Setup texture, create render and frame buffers
  2093. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  2094. glFormat = paramThreeToGL( renderTarget.format ),
  2095. glType = paramThreeToGL( renderTarget.type );
  2096. if ( isCube ) {
  2097. renderTarget.__webglFramebuffer = [];
  2098. renderTarget.__webglRenderbuffer = [];
  2099. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  2100. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  2101. for ( var i = 0; i < 6; i ++ ) {
  2102. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  2103. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  2104. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  2105. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  2106. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  2107. }
  2108. if ( renderTarget.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  2109. } else {
  2110. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  2111. if ( renderTarget.shareDepthFrom ) {
  2112. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  2113. } else {
  2114. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  2115. }
  2116. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  2117. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  2118. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  2119. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  2120. if ( renderTarget.shareDepthFrom ) {
  2121. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  2122. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  2123. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  2124. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  2125. }
  2126. } else {
  2127. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  2128. }
  2129. if ( renderTarget.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  2130. }
  2131. // Release everything
  2132. if ( isCube ) {
  2133. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  2134. } else {
  2135. _gl.bindTexture( _gl.TEXTURE_2D, null );
  2136. }
  2137. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  2138. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  2139. }
  2140. var framebuffer, width, height, vx, vy;
  2141. if ( renderTarget ) {
  2142. if ( isCube ) {
  2143. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  2144. } else {
  2145. framebuffer = renderTarget.__webglFramebuffer;
  2146. }
  2147. width = renderTarget.width;
  2148. height = renderTarget.height;
  2149. vx = 0;
  2150. vy = 0;
  2151. } else {
  2152. framebuffer = null;
  2153. width = _viewportWidth;
  2154. height = _viewportHeight;
  2155. vx = _viewportX;
  2156. vy = _viewportY;
  2157. }
  2158. if ( framebuffer !== _currentFramebuffer ) {
  2159. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  2160. _gl.viewport( vx, vy, width, height );
  2161. _currentFramebuffer = framebuffer;
  2162. }
  2163. _currentWidth = width;
  2164. _currentHeight = height;
  2165. };
  2166. this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) {
  2167. if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) {
  2168. THREE.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  2169. return;
  2170. }
  2171. if ( renderTarget.__webglFramebuffer ) {
  2172. if ( renderTarget.format !== THREE.RGBAFormat ) {
  2173. THREE.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' );
  2174. return;
  2175. }
  2176. var restore = false;
  2177. if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) {
  2178. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer );
  2179. restore = true;
  2180. }
  2181. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  2182. _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer );
  2183. } else {
  2184. THREE.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  2185. }
  2186. if ( restore ) {
  2187. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  2188. }
  2189. }
  2190. };
  2191. function updateRenderTargetMipmap ( renderTarget ) {
  2192. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  2193. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  2194. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  2195. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  2196. } else {
  2197. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  2198. _gl.generateMipmap( _gl.TEXTURE_2D );
  2199. _gl.bindTexture( _gl.TEXTURE_2D, null );
  2200. }
  2201. }
  2202. // Fallback filters for non-power-of-2 textures
  2203. function filterFallback ( f ) {
  2204. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  2205. return _gl.NEAREST;
  2206. }
  2207. return _gl.LINEAR;
  2208. }
  2209. // Map three.js constants to WebGL constants
  2210. function paramThreeToGL ( p ) {
  2211. var extension;
  2212. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  2213. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  2214. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  2215. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  2216. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  2217. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  2218. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  2219. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  2220. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  2221. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  2222. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  2223. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  2224. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  2225. if ( p === THREE.ByteType ) return _gl.BYTE;
  2226. if ( p === THREE.ShortType ) return _gl.SHORT;
  2227. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  2228. if ( p === THREE.IntType ) return _gl.INT;
  2229. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  2230. if ( p === THREE.FloatType ) return _gl.FLOAT;
  2231. extension = extensions.get( 'OES_texture_half_float' );
  2232. if ( extension !== null ) {
  2233. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  2234. }
  2235. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  2236. if ( p === THREE.RGBFormat ) return _gl.RGB;
  2237. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  2238. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  2239. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  2240. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  2241. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  2242. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  2243. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  2244. if ( p === THREE.OneFactor ) return _gl.ONE;
  2245. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  2246. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  2247. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  2248. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  2249. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  2250. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  2251. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  2252. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  2253. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  2254. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  2255. if ( extension !== null ) {
  2256. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  2257. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  2258. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  2259. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  2260. }
  2261. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  2262. if ( extension !== null ) {
  2263. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  2264. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  2265. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  2266. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  2267. }
  2268. extension = extensions.get( 'EXT_blend_minmax' );
  2269. if ( extension !== null ) {
  2270. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  2271. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  2272. }
  2273. return 0;
  2274. }
  2275. // Allocations
  2276. function allocateBones ( object ) {
  2277. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  2278. return 1024;
  2279. } else {
  2280. // default for when object is not specified
  2281. // ( for example when prebuilding shader to be used with multiple objects )
  2282. //
  2283. // - leave some extra space for other uniforms
  2284. // - limit here is ANGLE's 254 max uniform vectors
  2285. // (up to 54 should be safe)
  2286. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  2287. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  2288. var maxBones = nVertexMatrices;
  2289. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  2290. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  2291. if ( maxBones < object.skeleton.bones.length ) {
  2292. THREE.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  2293. }
  2294. }
  2295. return maxBones;
  2296. }
  2297. }
  2298. function allocateLights( lights ) {
  2299. var dirLights = 0;
  2300. var pointLights = 0;
  2301. var spotLights = 0;
  2302. var hemiLights = 0;
  2303. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  2304. var light = lights[ l ];
  2305. if ( light.onlyShadow || light.visible === false ) continue;
  2306. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  2307. if ( light instanceof THREE.PointLight ) pointLights ++;
  2308. if ( light instanceof THREE.SpotLight ) spotLights ++;
  2309. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  2310. }
  2311. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  2312. }
  2313. function allocateShadows( lights ) {
  2314. var maxShadows = 0;
  2315. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  2316. var light = lights[ l ];
  2317. if ( ! light.castShadow ) continue;
  2318. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  2319. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  2320. }
  2321. return maxShadows;
  2322. }
  2323. // DEPRECATED
  2324. this.initMaterial = function () {
  2325. THREE.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  2326. };
  2327. this.addPrePlugin = function () {
  2328. THREE.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  2329. };
  2330. this.addPostPlugin = function () {
  2331. THREE.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  2332. };
  2333. this.updateShadowMap = function () {
  2334. THREE.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  2335. };
  2336. Object.defineProperties( this, {
  2337. shadowMapEnabled: {
  2338. get: function () {
  2339. return shadowMap.enabled;
  2340. },
  2341. set: function ( value ) {
  2342. THREE.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  2343. shadowMap.enabled = value;
  2344. }
  2345. },
  2346. shadowMapType: {
  2347. get: function () {
  2348. return shadowMap.type;
  2349. },
  2350. set: function ( value ) {
  2351. THREE.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  2352. shadowMap.type = value;
  2353. }
  2354. },
  2355. shadowMapCullFace: {
  2356. get: function () {
  2357. return shadowMap.cullFace;
  2358. },
  2359. set: function ( value ) {
  2360. THREE.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  2361. shadowMap.cullFace = value;
  2362. }
  2363. },
  2364. shadowMapDebug: {
  2365. get: function () {
  2366. return shadowMap.debug;
  2367. },
  2368. set: function ( value ) {
  2369. THREE.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
  2370. shadowMap.debug = value;
  2371. }
  2372. },
  2373. shadowMapCascade: {
  2374. get: function () {
  2375. return shadowMap.cascade;
  2376. },
  2377. set: function ( value ) {
  2378. THREE.warn( 'THREE.WebGLRenderer: .shadowMapCascade is now .shadowMap.cascade.' );
  2379. shadowMap.cascade = value;
  2380. }
  2381. }
  2382. } );
  2383. };
粤ICP备19079148号