WebGLRenderer.js 95 KB

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