WebGLRenderer.js 96 KB

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