WebGLRenderer.js 95 KB

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