WebGLRenderer.js 95 KB

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