WebGLRenderer.js 95 KB

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