WebGLRenderer.js 95 KB

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