WebGLRenderer.js 86 KB

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