WebGLRenderer.js 96 KB

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