WebGLRenderer.js 159 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793
  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. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  12. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  13. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  17. _clearColor = new THREE.Color( 0x000000 ),
  18. _clearAlpha = 0;
  19. if ( parameters.clearColor !== undefined ) {
  20. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  21. _clearColor.setHex( parameters.clearColor );
  22. }
  23. if ( parameters.clearAlpha !== undefined ) {
  24. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  25. _clearAlpha = parameters.clearAlpha;
  26. }
  27. // public properties
  28. this.domElement = _canvas;
  29. this.context = null;
  30. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  31. ? parameters.devicePixelRatio
  32. : window.devicePixelRatio !== undefined
  33. ? window.devicePixelRatio
  34. : 1;
  35. // clearing
  36. this.autoClear = true;
  37. this.autoClearColor = true;
  38. this.autoClearDepth = true;
  39. this.autoClearStencil = true;
  40. // scene graph
  41. this.sortObjects = true;
  42. this.autoUpdateObjects = true;
  43. // physically based shading
  44. this.gammaInput = false;
  45. this.gammaOutput = false;
  46. this.physicallyBasedShading = false;
  47. // shadow map
  48. this.shadowMapEnabled = false;
  49. this.shadowMapAutoUpdate = true;
  50. this.shadowMapType = THREE.PCFShadowMap;
  51. this.shadowMapCullFace = THREE.CullFaceFront;
  52. this.shadowMapDebug = false;
  53. this.shadowMapCascade = false;
  54. // morphs
  55. this.maxMorphTargets = 8;
  56. this.maxMorphNormals = 4;
  57. // flags
  58. this.autoScaleCubemaps = true;
  59. // custom render plugins
  60. this.renderPluginsPre = [];
  61. this.renderPluginsPost = [];
  62. // info
  63. this.info = {
  64. memory: {
  65. programs: 0,
  66. geometries: 0,
  67. textures: 0
  68. },
  69. render: {
  70. calls: 0,
  71. vertices: 0,
  72. faces: 0,
  73. points: 0
  74. }
  75. };
  76. // internal properties
  77. var _this = this,
  78. _programs = [],
  79. _programs_counter = 0,
  80. // internal state cache
  81. _currentProgram = null,
  82. _currentFramebuffer = null,
  83. _currentMaterialId = -1,
  84. _currentGeometryGroupHash = null,
  85. _currentCamera = null,
  86. _geometryGroupCounter = 0,
  87. _usedTextureUnits = 0,
  88. // GL state cache
  89. _oldDoubleSided = -1,
  90. _oldFlipSided = -1,
  91. _oldBlending = -1,
  92. _oldBlendEquation = -1,
  93. _oldBlendSrc = -1,
  94. _oldBlendDst = -1,
  95. _oldDepthTest = -1,
  96. _oldDepthWrite = -1,
  97. _oldPolygonOffset = null,
  98. _oldPolygonOffsetFactor = null,
  99. _oldPolygonOffsetUnits = null,
  100. _oldLineWidth = null,
  101. _viewportX = 0,
  102. _viewportY = 0,
  103. _viewportWidth = 0,
  104. _viewportHeight = 0,
  105. _currentWidth = 0,
  106. _currentHeight = 0,
  107. _enabledAttributes = {},
  108. // frustum
  109. _frustum = new THREE.Frustum(),
  110. // camera matrices cache
  111. _projScreenMatrix = new THREE.Matrix4(),
  112. _projScreenMatrixPS = new THREE.Matrix4(),
  113. _vector3 = new THREE.Vector3(),
  114. // light arrays cache
  115. _direction = new THREE.Vector3(),
  116. _lightsNeedUpdate = true,
  117. _lights = {
  118. ambient: [ 0, 0, 0 ],
  119. directional: { length: 0, colors: new Array(), positions: new Array() },
  120. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  121. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  122. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  123. };
  124. // initialize
  125. var _gl;
  126. var _glExtensionTextureFloat;
  127. var _glExtensionTextureFloatLinear;
  128. var _glExtensionStandardDerivatives;
  129. var _glExtensionTextureFilterAnisotropic;
  130. var _glExtensionCompressedTextureS3TC;
  131. initGL();
  132. setDefaultGLState();
  133. this.context = _gl;
  134. // GPU capabilities
  135. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  136. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  137. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  138. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  139. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  140. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  141. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  142. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  143. //
  144. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  145. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  146. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  147. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  148. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  149. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  150. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  151. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  152. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  153. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  154. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  155. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  156. // clamp precision to maximum available
  157. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  158. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  159. if ( _precision === "highp" && ! highpAvailable ) {
  160. if ( mediumpAvailable ) {
  161. _precision = "mediump";
  162. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  163. } else {
  164. _precision = "lowp";
  165. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  166. }
  167. }
  168. if ( _precision === "mediump" && ! mediumpAvailable ) {
  169. _precision = "lowp";
  170. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  171. }
  172. // API
  173. this.getContext = function () {
  174. return _gl;
  175. };
  176. this.supportsVertexTextures = function () {
  177. return _supportsVertexTextures;
  178. };
  179. this.supportsFloatTextures = function () {
  180. return _glExtensionTextureFloat;
  181. };
  182. this.supportsStandardDerivatives = function () {
  183. return _glExtensionStandardDerivatives;
  184. };
  185. this.supportsCompressedTextureS3TC = function () {
  186. return _glExtensionCompressedTextureS3TC;
  187. };
  188. this.getMaxAnisotropy = function () {
  189. return _maxAnisotropy;
  190. };
  191. this.getPrecision = function () {
  192. return _precision;
  193. };
  194. this.setSize = function ( width, height, updateStyle ) {
  195. _canvas.width = width * this.devicePixelRatio;
  196. _canvas.height = height * this.devicePixelRatio;
  197. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  198. _canvas.style.width = width + 'px';
  199. _canvas.style.height = height + 'px';
  200. }
  201. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  202. };
  203. this.setViewport = function ( x, y, width, height ) {
  204. _viewportX = x !== undefined ? x : 0;
  205. _viewportY = y !== undefined ? y : 0;
  206. _viewportWidth = width !== undefined ? width : _canvas.width;
  207. _viewportHeight = height !== undefined ? height : _canvas.height;
  208. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  209. };
  210. this.setScissor = function ( x, y, width, height ) {
  211. _gl.scissor( x, y, width, height );
  212. };
  213. this.enableScissorTest = function ( enable ) {
  214. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  215. };
  216. // Clearing
  217. this.setClearColor = function ( color, alpha ) {
  218. _clearColor.set( color );
  219. _clearAlpha = alpha !== undefined ? alpha : 1;
  220. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  221. };
  222. this.setClearColorHex = function ( hex, alpha ) {
  223. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  224. this.setClearColor( hex, alpha );
  225. };
  226. this.getClearColor = function () {
  227. return _clearColor;
  228. };
  229. this.getClearAlpha = function () {
  230. return _clearAlpha;
  231. };
  232. this.clear = function ( color, depth, stencil ) {
  233. var bits = 0;
  234. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  235. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  236. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  237. _gl.clear( bits );
  238. };
  239. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  240. this.setRenderTarget( renderTarget );
  241. this.clear( color, depth, stencil );
  242. };
  243. // Plugins
  244. this.addPostPlugin = function ( plugin ) {
  245. plugin.init( this );
  246. this.renderPluginsPost.push( plugin );
  247. };
  248. this.addPrePlugin = function ( plugin ) {
  249. plugin.init( this );
  250. this.renderPluginsPre.push( plugin );
  251. };
  252. // Rendering
  253. this.updateShadowMap = function ( scene, camera ) {
  254. _currentProgram = null;
  255. _oldBlending = -1;
  256. _oldDepthTest = -1;
  257. _oldDepthWrite = -1;
  258. _currentGeometryGroupHash = -1;
  259. _currentMaterialId = -1;
  260. _lightsNeedUpdate = true;
  261. _oldDoubleSided = -1;
  262. _oldFlipSided = -1;
  263. this.shadowMapPlugin.update( scene, camera );
  264. };
  265. // Internal functions
  266. // Buffer allocation
  267. function createParticleBuffers ( geometry ) {
  268. geometry.__webglVertexBuffer = _gl.createBuffer();
  269. geometry.__webglColorBuffer = _gl.createBuffer();
  270. _this.info.memory.geometries ++;
  271. };
  272. function createLineBuffers ( geometry ) {
  273. geometry.__webglVertexBuffer = _gl.createBuffer();
  274. geometry.__webglColorBuffer = _gl.createBuffer();
  275. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  276. _this.info.memory.geometries ++;
  277. };
  278. function createRibbonBuffers ( geometry ) {
  279. geometry.__webglVertexBuffer = _gl.createBuffer();
  280. geometry.__webglColorBuffer = _gl.createBuffer();
  281. geometry.__webglNormalBuffer = _gl.createBuffer();
  282. _this.info.memory.geometries ++;
  283. };
  284. function createMeshBuffers ( geometryGroup ) {
  285. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  286. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  287. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  288. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  289. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  290. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  291. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  292. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  293. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  294. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  295. var m, ml;
  296. if ( geometryGroup.numMorphTargets ) {
  297. geometryGroup.__webglMorphTargetsBuffers = [];
  298. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  299. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  300. }
  301. }
  302. if ( geometryGroup.numMorphNormals ) {
  303. geometryGroup.__webglMorphNormalsBuffers = [];
  304. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  305. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  306. }
  307. }
  308. _this.info.memory.geometries ++;
  309. };
  310. // Events
  311. var onGeometryDispose = function ( event ) {
  312. var geometry = event.target;
  313. geometry.removeEventListener( 'dispose', onGeometryDispose );
  314. deallocateGeometry( geometry );
  315. };
  316. var onTextureDispose = function ( event ) {
  317. var texture = event.target;
  318. texture.removeEventListener( 'dispose', onTextureDispose );
  319. deallocateTexture( texture );
  320. _this.info.memory.textures --;
  321. };
  322. var onRenderTargetDispose = function ( event ) {
  323. var renderTarget = event.target;
  324. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  325. deallocateRenderTarget( renderTarget );
  326. _this.info.memory.textures --;
  327. };
  328. var onMaterialDispose = function ( event ) {
  329. var material = event.target;
  330. material.removeEventListener( 'dispose', onMaterialDispose );
  331. deallocateMaterial( material );
  332. };
  333. // Buffer deallocation
  334. var deleteBuffers = function ( geometry ) {
  335. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  336. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  337. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  338. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  339. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  340. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  341. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  342. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  343. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  344. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  345. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  346. // custom attributes
  347. if ( geometry.__webglCustomAttributesList !== undefined ) {
  348. for ( var id in geometry.__webglCustomAttributesList ) {
  349. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  350. }
  351. }
  352. _this.info.memory.geometries --;
  353. };
  354. var deallocateGeometry = function ( geometry ) {
  355. geometry.__webglInit = undefined;
  356. if ( geometry instanceof THREE.BufferGeometry ) {
  357. var attributes = geometry.attributes;
  358. for ( var key in attributes ) {
  359. if ( attributes[ key ].buffer !== undefined ) {
  360. _gl.deleteBuffer( attributes[ key ].buffer );
  361. }
  362. }
  363. _this.info.memory.geometries --;
  364. } else {
  365. if ( geometry.geometryGroups !== undefined ) {
  366. for ( var g in geometry.geometryGroups ) {
  367. var geometryGroup = geometry.geometryGroups[ g ];
  368. if ( geometryGroup.numMorphTargets !== undefined ) {
  369. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  370. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  371. }
  372. }
  373. if ( geometryGroup.numMorphNormals !== undefined ) {
  374. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  375. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  376. }
  377. }
  378. deleteBuffers( geometryGroup );
  379. }
  380. } else {
  381. deleteBuffers( geometry );
  382. }
  383. }
  384. };
  385. var deallocateTexture = function ( texture ) {
  386. if ( texture.image && texture.image.__webglTextureCube ) {
  387. // cube texture
  388. _gl.deleteTexture( texture.image.__webglTextureCube );
  389. } else {
  390. // 2D texture
  391. if ( ! texture.__webglInit ) return;
  392. texture.__webglInit = false;
  393. _gl.deleteTexture( texture.__webglTexture );
  394. }
  395. };
  396. var deallocateRenderTarget = function ( renderTarget ) {
  397. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  398. _gl.deleteTexture( renderTarget.__webglTexture );
  399. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  400. for ( var i = 0; i < 6; i ++ ) {
  401. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  402. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  403. }
  404. } else {
  405. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  406. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  407. }
  408. };
  409. var deallocateMaterial = function ( material ) {
  410. var program = material.program;
  411. if ( program === undefined ) return;
  412. material.program = undefined;
  413. // only deallocate GL program if this was the last use of shared program
  414. // assumed there is only single copy of any program in the _programs list
  415. // (that's how it's constructed)
  416. var i, il, programInfo;
  417. var deleteProgram = false;
  418. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  419. programInfo = _programs[ i ];
  420. if ( programInfo.program === program ) {
  421. programInfo.usedTimes --;
  422. if ( programInfo.usedTimes === 0 ) {
  423. deleteProgram = true;
  424. }
  425. break;
  426. }
  427. }
  428. if ( deleteProgram === true ) {
  429. // avoid using array.splice, this is costlier than creating new array from scratch
  430. var newPrograms = [];
  431. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  432. programInfo = _programs[ i ];
  433. if ( programInfo.program !== program ) {
  434. newPrograms.push( programInfo );
  435. }
  436. }
  437. _programs = newPrograms;
  438. _gl.deleteProgram( program );
  439. _this.info.memory.programs --;
  440. }
  441. };
  442. // Buffer initialization
  443. function initCustomAttributes ( geometry, object ) {
  444. var nvertices = geometry.vertices.length;
  445. var material = object.material;
  446. if ( material.attributes ) {
  447. if ( geometry.__webglCustomAttributesList === undefined ) {
  448. geometry.__webglCustomAttributesList = [];
  449. }
  450. for ( var a in material.attributes ) {
  451. var attribute = material.attributes[ a ];
  452. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  453. attribute.__webglInitialized = true;
  454. var size = 1; // "f" and "i"
  455. if ( attribute.type === "v2" ) size = 2;
  456. else if ( attribute.type === "v3" ) size = 3;
  457. else if ( attribute.type === "v4" ) size = 4;
  458. else if ( attribute.type === "c" ) size = 3;
  459. attribute.size = size;
  460. attribute.array = new Float32Array( nvertices * size );
  461. attribute.buffer = _gl.createBuffer();
  462. attribute.buffer.belongsToAttribute = a;
  463. attribute.needsUpdate = true;
  464. }
  465. geometry.__webglCustomAttributesList.push( attribute );
  466. }
  467. }
  468. };
  469. function initParticleBuffers ( geometry, object ) {
  470. var nvertices = geometry.vertices.length;
  471. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  472. geometry.__colorArray = new Float32Array( nvertices * 3 );
  473. geometry.__sortArray = [];
  474. geometry.__webglParticleCount = nvertices;
  475. initCustomAttributes ( geometry, object );
  476. };
  477. function initLineBuffers ( geometry, object ) {
  478. var nvertices = geometry.vertices.length;
  479. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  480. geometry.__colorArray = new Float32Array( nvertices * 3 );
  481. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  482. geometry.__webglLineCount = nvertices;
  483. initCustomAttributes ( geometry, object );
  484. };
  485. function initRibbonBuffers ( geometry, object ) {
  486. var nvertices = geometry.vertices.length;
  487. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  488. geometry.__colorArray = new Float32Array( nvertices * 3 );
  489. geometry.__normalArray = new Float32Array( nvertices * 3 );
  490. geometry.__webglVertexCount = nvertices;
  491. initCustomAttributes ( geometry, object );
  492. };
  493. function initMeshBuffers ( geometryGroup, object ) {
  494. var geometry = object.geometry,
  495. faces3 = geometryGroup.faces3,
  496. nvertices = faces3.length * 3,
  497. ntris = faces3.length * 1,
  498. nlines = faces3.length * 3,
  499. material = getBufferMaterial( object, geometryGroup ),
  500. uvType = bufferGuessUVType( material ),
  501. normalType = bufferGuessNormalType( material ),
  502. vertexColorType = bufferGuessVertexColorType( material );
  503. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  504. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  505. if ( normalType ) {
  506. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  507. }
  508. if ( geometry.hasTangents ) {
  509. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  510. }
  511. if ( vertexColorType ) {
  512. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  513. }
  514. if ( uvType ) {
  515. if ( geometry.faceVertexUvs.length > 0 ) {
  516. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  517. }
  518. if ( geometry.faceVertexUvs.length > 1 ) {
  519. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  520. }
  521. }
  522. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  523. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  524. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  525. }
  526. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  527. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  528. var m, ml;
  529. if ( geometryGroup.numMorphTargets ) {
  530. geometryGroup.__morphTargetsArrays = [];
  531. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  532. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  533. }
  534. }
  535. if ( geometryGroup.numMorphNormals ) {
  536. geometryGroup.__morphNormalsArrays = [];
  537. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  538. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  539. }
  540. }
  541. geometryGroup.__webglFaceCount = ntris * 3;
  542. geometryGroup.__webglLineCount = nlines * 2;
  543. // custom attributes
  544. if ( material.attributes ) {
  545. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  546. geometryGroup.__webglCustomAttributesList = [];
  547. }
  548. for ( var a in material.attributes ) {
  549. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  550. // attribute buffers which are correctly indexed in the setMeshBuffers function
  551. var originalAttribute = material.attributes[ a ];
  552. var attribute = {};
  553. for ( var property in originalAttribute ) {
  554. attribute[ property ] = originalAttribute[ property ];
  555. }
  556. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  557. attribute.__webglInitialized = true;
  558. var size = 1; // "f" and "i"
  559. if( attribute.type === "v2" ) size = 2;
  560. else if( attribute.type === "v3" ) size = 3;
  561. else if( attribute.type === "v4" ) size = 4;
  562. else if( attribute.type === "c" ) size = 3;
  563. attribute.size = size;
  564. attribute.array = new Float32Array( nvertices * size );
  565. attribute.buffer = _gl.createBuffer();
  566. attribute.buffer.belongsToAttribute = a;
  567. originalAttribute.needsUpdate = true;
  568. attribute.__original = originalAttribute;
  569. }
  570. geometryGroup.__webglCustomAttributesList.push( attribute );
  571. }
  572. }
  573. geometryGroup.__inittedArrays = true;
  574. };
  575. function getBufferMaterial( object, geometryGroup ) {
  576. return object.material instanceof THREE.MeshFaceMaterial
  577. ? object.material.materials[ geometryGroup.materialIndex ]
  578. : object.material;
  579. };
  580. function materialNeedsSmoothNormals ( material ) {
  581. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  582. };
  583. function bufferGuessNormalType ( material ) {
  584. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  585. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  586. return false;
  587. }
  588. if ( materialNeedsSmoothNormals( material ) ) {
  589. return THREE.SmoothShading;
  590. } else {
  591. return THREE.FlatShading;
  592. }
  593. };
  594. function bufferGuessVertexColorType( material ) {
  595. if ( material.vertexColors ) {
  596. return material.vertexColors;
  597. }
  598. return false;
  599. };
  600. function bufferGuessUVType( material ) {
  601. // material must use some texture to require uvs
  602. if ( material.map ||
  603. material.lightMap ||
  604. material.bumpMap ||
  605. material.normalMap ||
  606. material.specularMap ||
  607. material instanceof THREE.ShaderMaterial ) {
  608. return true;
  609. }
  610. return false;
  611. };
  612. //
  613. function initDirectBuffers( geometry ) {
  614. var a, attribute, type;
  615. for ( a in geometry.attributes ) {
  616. if ( a === "index" ) {
  617. type = _gl.ELEMENT_ARRAY_BUFFER;
  618. } else {
  619. type = _gl.ARRAY_BUFFER;
  620. }
  621. attribute = geometry.attributes[ a ];
  622. if ( attribute.numItems === undefined ) {
  623. attribute.numItems = attribute.array.length;
  624. }
  625. attribute.buffer = _gl.createBuffer();
  626. _gl.bindBuffer( type, attribute.buffer );
  627. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  628. }
  629. };
  630. // Buffer setting
  631. function setParticleBuffers ( geometry, hint, object ) {
  632. var v, c, vertex, offset, index, color,
  633. vertices = geometry.vertices,
  634. vl = vertices.length,
  635. colors = geometry.colors,
  636. cl = colors.length,
  637. vertexArray = geometry.__vertexArray,
  638. colorArray = geometry.__colorArray,
  639. sortArray = geometry.__sortArray,
  640. dirtyVertices = geometry.verticesNeedUpdate,
  641. dirtyElements = geometry.elementsNeedUpdate,
  642. dirtyColors = geometry.colorsNeedUpdate,
  643. customAttributes = geometry.__webglCustomAttributesList,
  644. i, il,
  645. a, ca, cal, value,
  646. customAttribute;
  647. if ( object.sortParticles ) {
  648. _projScreenMatrixPS.copy( _projScreenMatrix );
  649. _projScreenMatrixPS.multiply( object.matrixWorld );
  650. for ( v = 0; v < vl; v ++ ) {
  651. vertex = vertices[ v ];
  652. _vector3.copy( vertex );
  653. _vector3.applyProjection( _projScreenMatrixPS );
  654. sortArray[ v ] = [ _vector3.z, v ];
  655. }
  656. sortArray.sort( numericalSort );
  657. for ( v = 0; v < vl; v ++ ) {
  658. vertex = vertices[ sortArray[v][1] ];
  659. offset = v * 3;
  660. vertexArray[ offset ] = vertex.x;
  661. vertexArray[ offset + 1 ] = vertex.y;
  662. vertexArray[ offset + 2 ] = vertex.z;
  663. }
  664. for ( c = 0; c < cl; c ++ ) {
  665. offset = c * 3;
  666. color = colors[ sortArray[c][1] ];
  667. colorArray[ offset ] = color.r;
  668. colorArray[ offset + 1 ] = color.g;
  669. colorArray[ offset + 2 ] = color.b;
  670. }
  671. if ( customAttributes ) {
  672. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  673. customAttribute = customAttributes[ i ];
  674. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  675. offset = 0;
  676. cal = customAttribute.value.length;
  677. if ( customAttribute.size === 1 ) {
  678. for ( ca = 0; ca < cal; ca ++ ) {
  679. index = sortArray[ ca ][ 1 ];
  680. customAttribute.array[ ca ] = customAttribute.value[ index ];
  681. }
  682. } else if ( customAttribute.size === 2 ) {
  683. for ( ca = 0; ca < cal; ca ++ ) {
  684. index = sortArray[ ca ][ 1 ];
  685. value = customAttribute.value[ index ];
  686. customAttribute.array[ offset ] = value.x;
  687. customAttribute.array[ offset + 1 ] = value.y;
  688. offset += 2;
  689. }
  690. } else if ( customAttribute.size === 3 ) {
  691. if ( customAttribute.type === "c" ) {
  692. for ( ca = 0; ca < cal; ca ++ ) {
  693. index = sortArray[ ca ][ 1 ];
  694. value = customAttribute.value[ index ];
  695. customAttribute.array[ offset ] = value.r;
  696. customAttribute.array[ offset + 1 ] = value.g;
  697. customAttribute.array[ offset + 2 ] = value.b;
  698. offset += 3;
  699. }
  700. } else {
  701. for ( ca = 0; ca < cal; ca ++ ) {
  702. index = sortArray[ ca ][ 1 ];
  703. value = customAttribute.value[ index ];
  704. customAttribute.array[ offset ] = value.x;
  705. customAttribute.array[ offset + 1 ] = value.y;
  706. customAttribute.array[ offset + 2 ] = value.z;
  707. offset += 3;
  708. }
  709. }
  710. } else if ( customAttribute.size === 4 ) {
  711. for ( ca = 0; ca < cal; ca ++ ) {
  712. index = sortArray[ ca ][ 1 ];
  713. value = customAttribute.value[ index ];
  714. customAttribute.array[ offset ] = value.x;
  715. customAttribute.array[ offset + 1 ] = value.y;
  716. customAttribute.array[ offset + 2 ] = value.z;
  717. customAttribute.array[ offset + 3 ] = value.w;
  718. offset += 4;
  719. }
  720. }
  721. }
  722. }
  723. } else {
  724. if ( dirtyVertices ) {
  725. for ( v = 0; v < vl; v ++ ) {
  726. vertex = vertices[ v ];
  727. offset = v * 3;
  728. vertexArray[ offset ] = vertex.x;
  729. vertexArray[ offset + 1 ] = vertex.y;
  730. vertexArray[ offset + 2 ] = vertex.z;
  731. }
  732. }
  733. if ( dirtyColors ) {
  734. for ( c = 0; c < cl; c ++ ) {
  735. color = colors[ c ];
  736. offset = c * 3;
  737. colorArray[ offset ] = color.r;
  738. colorArray[ offset + 1 ] = color.g;
  739. colorArray[ offset + 2 ] = color.b;
  740. }
  741. }
  742. if ( customAttributes ) {
  743. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  744. customAttribute = customAttributes[ i ];
  745. if ( customAttribute.needsUpdate &&
  746. ( customAttribute.boundTo === undefined ||
  747. customAttribute.boundTo === "vertices") ) {
  748. cal = customAttribute.value.length;
  749. offset = 0;
  750. if ( customAttribute.size === 1 ) {
  751. for ( ca = 0; ca < cal; ca ++ ) {
  752. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  753. }
  754. } else if ( customAttribute.size === 2 ) {
  755. for ( ca = 0; ca < cal; ca ++ ) {
  756. value = customAttribute.value[ ca ];
  757. customAttribute.array[ offset ] = value.x;
  758. customAttribute.array[ offset + 1 ] = value.y;
  759. offset += 2;
  760. }
  761. } else if ( customAttribute.size === 3 ) {
  762. if ( customAttribute.type === "c" ) {
  763. for ( ca = 0; ca < cal; ca ++ ) {
  764. value = customAttribute.value[ ca ];
  765. customAttribute.array[ offset ] = value.r;
  766. customAttribute.array[ offset + 1 ] = value.g;
  767. customAttribute.array[ offset + 2 ] = value.b;
  768. offset += 3;
  769. }
  770. } else {
  771. for ( ca = 0; ca < cal; ca ++ ) {
  772. value = customAttribute.value[ ca ];
  773. customAttribute.array[ offset ] = value.x;
  774. customAttribute.array[ offset + 1 ] = value.y;
  775. customAttribute.array[ offset + 2 ] = value.z;
  776. offset += 3;
  777. }
  778. }
  779. } else if ( customAttribute.size === 4 ) {
  780. for ( ca = 0; ca < cal; ca ++ ) {
  781. value = customAttribute.value[ ca ];
  782. customAttribute.array[ offset ] = value.x;
  783. customAttribute.array[ offset + 1 ] = value.y;
  784. customAttribute.array[ offset + 2 ] = value.z;
  785. customAttribute.array[ offset + 3 ] = value.w;
  786. offset += 4;
  787. }
  788. }
  789. }
  790. }
  791. }
  792. }
  793. if ( dirtyVertices || object.sortParticles ) {
  794. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  795. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  796. }
  797. if ( dirtyColors || object.sortParticles ) {
  798. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  799. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  800. }
  801. if ( customAttributes ) {
  802. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  803. customAttribute = customAttributes[ i ];
  804. if ( customAttribute.needsUpdate || object.sortParticles ) {
  805. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  806. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  807. }
  808. }
  809. }
  810. };
  811. function setLineBuffers ( geometry, hint ) {
  812. var v, c, d, vertex, offset, color,
  813. vertices = geometry.vertices,
  814. colors = geometry.colors,
  815. lineDistances = geometry.lineDistances,
  816. vl = vertices.length,
  817. cl = colors.length,
  818. dl = lineDistances.length,
  819. vertexArray = geometry.__vertexArray,
  820. colorArray = geometry.__colorArray,
  821. lineDistanceArray = geometry.__lineDistanceArray,
  822. dirtyVertices = geometry.verticesNeedUpdate,
  823. dirtyColors = geometry.colorsNeedUpdate,
  824. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  825. customAttributes = geometry.__webglCustomAttributesList,
  826. i, il,
  827. a, ca, cal, value,
  828. customAttribute;
  829. if ( dirtyVertices ) {
  830. for ( v = 0; v < vl; v ++ ) {
  831. vertex = vertices[ v ];
  832. offset = v * 3;
  833. vertexArray[ offset ] = vertex.x;
  834. vertexArray[ offset + 1 ] = vertex.y;
  835. vertexArray[ offset + 2 ] = vertex.z;
  836. }
  837. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  838. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  839. }
  840. if ( dirtyColors ) {
  841. for ( c = 0; c < cl; c ++ ) {
  842. color = colors[ c ];
  843. offset = c * 3;
  844. colorArray[ offset ] = color.r;
  845. colorArray[ offset + 1 ] = color.g;
  846. colorArray[ offset + 2 ] = color.b;
  847. }
  848. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  849. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  850. }
  851. if ( dirtyLineDistances ) {
  852. for ( d = 0; d < dl; d ++ ) {
  853. lineDistanceArray[ d ] = lineDistances[ d ];
  854. }
  855. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  856. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  857. }
  858. if ( customAttributes ) {
  859. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  860. customAttribute = customAttributes[ i ];
  861. if ( customAttribute.needsUpdate &&
  862. ( customAttribute.boundTo === undefined ||
  863. customAttribute.boundTo === "vertices" ) ) {
  864. offset = 0;
  865. cal = customAttribute.value.length;
  866. if ( customAttribute.size === 1 ) {
  867. for ( ca = 0; ca < cal; ca ++ ) {
  868. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  869. }
  870. } else if ( customAttribute.size === 2 ) {
  871. for ( ca = 0; ca < cal; ca ++ ) {
  872. value = customAttribute.value[ ca ];
  873. customAttribute.array[ offset ] = value.x;
  874. customAttribute.array[ offset + 1 ] = value.y;
  875. offset += 2;
  876. }
  877. } else if ( customAttribute.size === 3 ) {
  878. if ( customAttribute.type === "c" ) {
  879. for ( ca = 0; ca < cal; ca ++ ) {
  880. value = customAttribute.value[ ca ];
  881. customAttribute.array[ offset ] = value.r;
  882. customAttribute.array[ offset + 1 ] = value.g;
  883. customAttribute.array[ offset + 2 ] = value.b;
  884. offset += 3;
  885. }
  886. } else {
  887. for ( ca = 0; ca < cal; ca ++ ) {
  888. value = customAttribute.value[ ca ];
  889. customAttribute.array[ offset ] = value.x;
  890. customAttribute.array[ offset + 1 ] = value.y;
  891. customAttribute.array[ offset + 2 ] = value.z;
  892. offset += 3;
  893. }
  894. }
  895. } else if ( customAttribute.size === 4 ) {
  896. for ( ca = 0; ca < cal; ca ++ ) {
  897. value = customAttribute.value[ ca ];
  898. customAttribute.array[ offset ] = value.x;
  899. customAttribute.array[ offset + 1 ] = value.y;
  900. customAttribute.array[ offset + 2 ] = value.z;
  901. customAttribute.array[ offset + 3 ] = value.w;
  902. offset += 4;
  903. }
  904. }
  905. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  906. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  907. }
  908. }
  909. }
  910. };
  911. function setRibbonBuffers ( geometry, hint ) {
  912. var v, c, n, vertex, offset, color, normal,
  913. i, il, ca, cal, customAttribute, value,
  914. vertices = geometry.vertices,
  915. colors = geometry.colors,
  916. normals = geometry.normals,
  917. vl = vertices.length,
  918. cl = colors.length,
  919. nl = normals.length,
  920. vertexArray = geometry.__vertexArray,
  921. colorArray = geometry.__colorArray,
  922. normalArray = geometry.__normalArray,
  923. dirtyVertices = geometry.verticesNeedUpdate,
  924. dirtyColors = geometry.colorsNeedUpdate,
  925. dirtyNormals = geometry.normalsNeedUpdate,
  926. customAttributes = geometry.__webglCustomAttributesList;
  927. if ( dirtyVertices ) {
  928. for ( v = 0; v < vl; v ++ ) {
  929. vertex = vertices[ v ];
  930. offset = v * 3;
  931. vertexArray[ offset ] = vertex.x;
  932. vertexArray[ offset + 1 ] = vertex.y;
  933. vertexArray[ offset + 2 ] = vertex.z;
  934. }
  935. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  936. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  937. }
  938. if ( dirtyColors ) {
  939. for ( c = 0; c < cl; c ++ ) {
  940. color = colors[ c ];
  941. offset = c * 3;
  942. colorArray[ offset ] = color.r;
  943. colorArray[ offset + 1 ] = color.g;
  944. colorArray[ offset + 2 ] = color.b;
  945. }
  946. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  947. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  948. }
  949. if ( dirtyNormals ) {
  950. for ( n = 0; n < nl; n ++ ) {
  951. normal = normals[ n ];
  952. offset = n * 3;
  953. normalArray[ offset ] = normal.x;
  954. normalArray[ offset + 1 ] = normal.y;
  955. normalArray[ offset + 2 ] = normal.z;
  956. }
  957. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  958. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  959. }
  960. if ( customAttributes ) {
  961. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  962. customAttribute = customAttributes[ i ];
  963. if ( customAttribute.needsUpdate &&
  964. ( customAttribute.boundTo === undefined ||
  965. customAttribute.boundTo === "vertices" ) ) {
  966. offset = 0;
  967. cal = customAttribute.value.length;
  968. if ( customAttribute.size === 1 ) {
  969. for ( ca = 0; ca < cal; ca ++ ) {
  970. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  971. }
  972. } else if ( customAttribute.size === 2 ) {
  973. for ( ca = 0; ca < cal; ca ++ ) {
  974. value = customAttribute.value[ ca ];
  975. customAttribute.array[ offset ] = value.x;
  976. customAttribute.array[ offset + 1 ] = value.y;
  977. offset += 2;
  978. }
  979. } else if ( customAttribute.size === 3 ) {
  980. if ( customAttribute.type === "c" ) {
  981. for ( ca = 0; ca < cal; ca ++ ) {
  982. value = customAttribute.value[ ca ];
  983. customAttribute.array[ offset ] = value.r;
  984. customAttribute.array[ offset + 1 ] = value.g;
  985. customAttribute.array[ offset + 2 ] = value.b;
  986. offset += 3;
  987. }
  988. } else {
  989. for ( ca = 0; ca < cal; ca ++ ) {
  990. value = customAttribute.value[ ca ];
  991. customAttribute.array[ offset ] = value.x;
  992. customAttribute.array[ offset + 1 ] = value.y;
  993. customAttribute.array[ offset + 2 ] = value.z;
  994. offset += 3;
  995. }
  996. }
  997. } else if ( customAttribute.size === 4 ) {
  998. for ( ca = 0; ca < cal; ca ++ ) {
  999. value = customAttribute.value[ ca ];
  1000. customAttribute.array[ offset ] = value.x;
  1001. customAttribute.array[ offset + 1 ] = value.y;
  1002. customAttribute.array[ offset + 2 ] = value.z;
  1003. customAttribute.array[ offset + 3 ] = value.w;
  1004. offset += 4;
  1005. }
  1006. }
  1007. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  1008. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  1009. }
  1010. }
  1011. }
  1012. };
  1013. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  1014. if ( ! geometryGroup.__inittedArrays ) {
  1015. return;
  1016. }
  1017. var normalType = bufferGuessNormalType( material ),
  1018. vertexColorType = bufferGuessVertexColorType( material ),
  1019. uvType = bufferGuessUVType( material ),
  1020. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  1021. var f, fl, fi, face,
  1022. vertexNormals, faceNormal, normal,
  1023. vertexColors, faceColor,
  1024. vertexTangents,
  1025. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  1026. c1, c2, c3, c4,
  1027. sw1, sw2, sw3, sw4,
  1028. si1, si2, si3, si4,
  1029. sa1, sa2, sa3, sa4,
  1030. sb1, sb2, sb3, sb4,
  1031. m, ml, i, il,
  1032. vn, uvi, uv2i,
  1033. vk, vkl, vka,
  1034. nka, chf, faceVertexNormals,
  1035. a,
  1036. vertexIndex = 0,
  1037. offset = 0,
  1038. offset_uv = 0,
  1039. offset_uv2 = 0,
  1040. offset_face = 0,
  1041. offset_normal = 0,
  1042. offset_tangent = 0,
  1043. offset_line = 0,
  1044. offset_color = 0,
  1045. offset_skin = 0,
  1046. offset_morphTarget = 0,
  1047. offset_custom = 0,
  1048. offset_customSrc = 0,
  1049. value,
  1050. vertexArray = geometryGroup.__vertexArray,
  1051. uvArray = geometryGroup.__uvArray,
  1052. uv2Array = geometryGroup.__uv2Array,
  1053. normalArray = geometryGroup.__normalArray,
  1054. tangentArray = geometryGroup.__tangentArray,
  1055. colorArray = geometryGroup.__colorArray,
  1056. skinIndexArray = geometryGroup.__skinIndexArray,
  1057. skinWeightArray = geometryGroup.__skinWeightArray,
  1058. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  1059. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  1060. customAttributes = geometryGroup.__webglCustomAttributesList,
  1061. customAttribute,
  1062. faceArray = geometryGroup.__faceArray,
  1063. lineArray = geometryGroup.__lineArray,
  1064. geometry = object.geometry, // this is shared for all chunks
  1065. dirtyVertices = geometry.verticesNeedUpdate,
  1066. dirtyElements = geometry.elementsNeedUpdate,
  1067. dirtyUvs = geometry.uvsNeedUpdate,
  1068. dirtyNormals = geometry.normalsNeedUpdate,
  1069. dirtyTangents = geometry.tangentsNeedUpdate,
  1070. dirtyColors = geometry.colorsNeedUpdate,
  1071. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  1072. vertices = geometry.vertices,
  1073. chunk_faces3 = geometryGroup.faces3,
  1074. obj_faces = geometry.faces,
  1075. obj_uvs = geometry.faceVertexUvs[ 0 ],
  1076. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  1077. obj_colors = geometry.colors,
  1078. obj_skinIndices = geometry.skinIndices,
  1079. obj_skinWeights = geometry.skinWeights,
  1080. morphTargets = geometry.morphTargets,
  1081. morphNormals = geometry.morphNormals;
  1082. if ( dirtyVertices ) {
  1083. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1084. face = obj_faces[ chunk_faces3[ f ] ];
  1085. v1 = vertices[ face.a ];
  1086. v2 = vertices[ face.b ];
  1087. v3 = vertices[ face.c ];
  1088. vertexArray[ offset ] = v1.x;
  1089. vertexArray[ offset + 1 ] = v1.y;
  1090. vertexArray[ offset + 2 ] = v1.z;
  1091. vertexArray[ offset + 3 ] = v2.x;
  1092. vertexArray[ offset + 4 ] = v2.y;
  1093. vertexArray[ offset + 5 ] = v2.z;
  1094. vertexArray[ offset + 6 ] = v3.x;
  1095. vertexArray[ offset + 7 ] = v3.y;
  1096. vertexArray[ offset + 8 ] = v3.z;
  1097. offset += 9;
  1098. }
  1099. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  1100. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  1101. }
  1102. if ( dirtyMorphTargets ) {
  1103. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  1104. offset_morphTarget = 0;
  1105. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1106. chf = chunk_faces3[ f ];
  1107. face = obj_faces[ chf ];
  1108. // morph positions
  1109. v1 = morphTargets[ vk ].vertices[ face.a ];
  1110. v2 = morphTargets[ vk ].vertices[ face.b ];
  1111. v3 = morphTargets[ vk ].vertices[ face.c ];
  1112. vka = morphTargetsArrays[ vk ];
  1113. vka[ offset_morphTarget ] = v1.x;
  1114. vka[ offset_morphTarget + 1 ] = v1.y;
  1115. vka[ offset_morphTarget + 2 ] = v1.z;
  1116. vka[ offset_morphTarget + 3 ] = v2.x;
  1117. vka[ offset_morphTarget + 4 ] = v2.y;
  1118. vka[ offset_morphTarget + 5 ] = v2.z;
  1119. vka[ offset_morphTarget + 6 ] = v3.x;
  1120. vka[ offset_morphTarget + 7 ] = v3.y;
  1121. vka[ offset_morphTarget + 8 ] = v3.z;
  1122. // morph normals
  1123. if ( material.morphNormals ) {
  1124. if ( needsSmoothNormals ) {
  1125. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  1126. n1 = faceVertexNormals.a;
  1127. n2 = faceVertexNormals.b;
  1128. n3 = faceVertexNormals.c;
  1129. } else {
  1130. n1 = morphNormals[ vk ].faceNormals[ chf ];
  1131. n2 = n1;
  1132. n3 = n1;
  1133. }
  1134. nka = morphNormalsArrays[ vk ];
  1135. nka[ offset_morphTarget ] = n1.x;
  1136. nka[ offset_morphTarget + 1 ] = n1.y;
  1137. nka[ offset_morphTarget + 2 ] = n1.z;
  1138. nka[ offset_morphTarget + 3 ] = n2.x;
  1139. nka[ offset_morphTarget + 4 ] = n2.y;
  1140. nka[ offset_morphTarget + 5 ] = n2.z;
  1141. nka[ offset_morphTarget + 6 ] = n3.x;
  1142. nka[ offset_morphTarget + 7 ] = n3.y;
  1143. nka[ offset_morphTarget + 8 ] = n3.z;
  1144. }
  1145. //
  1146. offset_morphTarget += 9;
  1147. }
  1148. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  1149. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  1150. if ( material.morphNormals ) {
  1151. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  1152. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  1153. }
  1154. }
  1155. }
  1156. if ( obj_skinWeights.length ) {
  1157. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1158. face = obj_faces[ chunk_faces3[ f ] ];
  1159. // weights
  1160. sw1 = obj_skinWeights[ face.a ];
  1161. sw2 = obj_skinWeights[ face.b ];
  1162. sw3 = obj_skinWeights[ face.c ];
  1163. skinWeightArray[ offset_skin ] = sw1.x;
  1164. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  1165. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  1166. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  1167. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  1168. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  1169. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  1170. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  1171. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  1172. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  1173. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  1174. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  1175. // indices
  1176. si1 = obj_skinIndices[ face.a ];
  1177. si2 = obj_skinIndices[ face.b ];
  1178. si3 = obj_skinIndices[ face.c ];
  1179. skinIndexArray[ offset_skin ] = si1.x;
  1180. skinIndexArray[ offset_skin + 1 ] = si1.y;
  1181. skinIndexArray[ offset_skin + 2 ] = si1.z;
  1182. skinIndexArray[ offset_skin + 3 ] = si1.w;
  1183. skinIndexArray[ offset_skin + 4 ] = si2.x;
  1184. skinIndexArray[ offset_skin + 5 ] = si2.y;
  1185. skinIndexArray[ offset_skin + 6 ] = si2.z;
  1186. skinIndexArray[ offset_skin + 7 ] = si2.w;
  1187. skinIndexArray[ offset_skin + 8 ] = si3.x;
  1188. skinIndexArray[ offset_skin + 9 ] = si3.y;
  1189. skinIndexArray[ offset_skin + 10 ] = si3.z;
  1190. skinIndexArray[ offset_skin + 11 ] = si3.w;
  1191. offset_skin += 12;
  1192. }
  1193. if ( offset_skin > 0 ) {
  1194. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  1195. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  1196. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  1197. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  1198. }
  1199. }
  1200. if ( dirtyColors && vertexColorType ) {
  1201. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1202. face = obj_faces[ chunk_faces3[ f ] ];
  1203. vertexColors = face.vertexColors;
  1204. faceColor = face.color;
  1205. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  1206. c1 = vertexColors[ 0 ];
  1207. c2 = vertexColors[ 1 ];
  1208. c3 = vertexColors[ 2 ];
  1209. } else {
  1210. c1 = faceColor;
  1211. c2 = faceColor;
  1212. c3 = faceColor;
  1213. }
  1214. colorArray[ offset_color ] = c1.r;
  1215. colorArray[ offset_color + 1 ] = c1.g;
  1216. colorArray[ offset_color + 2 ] = c1.b;
  1217. colorArray[ offset_color + 3 ] = c2.r;
  1218. colorArray[ offset_color + 4 ] = c2.g;
  1219. colorArray[ offset_color + 5 ] = c2.b;
  1220. colorArray[ offset_color + 6 ] = c3.r;
  1221. colorArray[ offset_color + 7 ] = c3.g;
  1222. colorArray[ offset_color + 8 ] = c3.b;
  1223. offset_color += 9;
  1224. }
  1225. if ( offset_color > 0 ) {
  1226. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  1227. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  1228. }
  1229. }
  1230. if ( dirtyTangents && geometry.hasTangents ) {
  1231. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1232. face = obj_faces[ chunk_faces3[ f ] ];
  1233. vertexTangents = face.vertexTangents;
  1234. t1 = vertexTangents[ 0 ];
  1235. t2 = vertexTangents[ 1 ];
  1236. t3 = vertexTangents[ 2 ];
  1237. tangentArray[ offset_tangent ] = t1.x;
  1238. tangentArray[ offset_tangent + 1 ] = t1.y;
  1239. tangentArray[ offset_tangent + 2 ] = t1.z;
  1240. tangentArray[ offset_tangent + 3 ] = t1.w;
  1241. tangentArray[ offset_tangent + 4 ] = t2.x;
  1242. tangentArray[ offset_tangent + 5 ] = t2.y;
  1243. tangentArray[ offset_tangent + 6 ] = t2.z;
  1244. tangentArray[ offset_tangent + 7 ] = t2.w;
  1245. tangentArray[ offset_tangent + 8 ] = t3.x;
  1246. tangentArray[ offset_tangent + 9 ] = t3.y;
  1247. tangentArray[ offset_tangent + 10 ] = t3.z;
  1248. tangentArray[ offset_tangent + 11 ] = t3.w;
  1249. offset_tangent += 12;
  1250. }
  1251. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  1252. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  1253. }
  1254. if ( dirtyNormals && normalType ) {
  1255. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1256. face = obj_faces[ chunk_faces3[ f ] ];
  1257. vertexNormals = face.vertexNormals;
  1258. faceNormal = face.normal;
  1259. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  1260. for ( i = 0; i < 3; i ++ ) {
  1261. vn = vertexNormals[ i ];
  1262. normalArray[ offset_normal ] = vn.x;
  1263. normalArray[ offset_normal + 1 ] = vn.y;
  1264. normalArray[ offset_normal + 2 ] = vn.z;
  1265. offset_normal += 3;
  1266. }
  1267. } else {
  1268. for ( i = 0; i < 3; i ++ ) {
  1269. normalArray[ offset_normal ] = faceNormal.x;
  1270. normalArray[ offset_normal + 1 ] = faceNormal.y;
  1271. normalArray[ offset_normal + 2 ] = faceNormal.z;
  1272. offset_normal += 3;
  1273. }
  1274. }
  1275. }
  1276. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  1277. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  1278. }
  1279. if ( dirtyUvs && obj_uvs && uvType ) {
  1280. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1281. fi = chunk_faces3[ f ];
  1282. uv = obj_uvs[ fi ];
  1283. if ( uv === undefined ) continue;
  1284. for ( i = 0; i < 3; i ++ ) {
  1285. uvi = uv[ i ];
  1286. uvArray[ offset_uv ] = uvi.x;
  1287. uvArray[ offset_uv + 1 ] = uvi.y;
  1288. offset_uv += 2;
  1289. }
  1290. }
  1291. if ( offset_uv > 0 ) {
  1292. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  1293. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  1294. }
  1295. }
  1296. if ( dirtyUvs && obj_uvs2 && uvType ) {
  1297. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1298. fi = chunk_faces3[ f ];
  1299. uv2 = obj_uvs2[ fi ];
  1300. if ( uv2 === undefined ) continue;
  1301. for ( i = 0; i < 3; i ++ ) {
  1302. uv2i = uv2[ i ];
  1303. uv2Array[ offset_uv2 ] = uv2i.x;
  1304. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  1305. offset_uv2 += 2;
  1306. }
  1307. }
  1308. if ( offset_uv2 > 0 ) {
  1309. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  1310. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  1311. }
  1312. }
  1313. if ( dirtyElements ) {
  1314. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1315. faceArray[ offset_face ] = vertexIndex;
  1316. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  1317. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  1318. offset_face += 3;
  1319. lineArray[ offset_line ] = vertexIndex;
  1320. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  1321. lineArray[ offset_line + 2 ] = vertexIndex;
  1322. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  1323. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  1324. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  1325. offset_line += 6;
  1326. vertexIndex += 3;
  1327. }
  1328. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  1329. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  1330. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  1331. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  1332. }
  1333. if ( customAttributes ) {
  1334. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  1335. customAttribute = customAttributes[ i ];
  1336. if ( ! customAttribute.__original.needsUpdate ) continue;
  1337. offset_custom = 0;
  1338. offset_customSrc = 0;
  1339. if ( customAttribute.size === 1 ) {
  1340. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  1341. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1342. face = obj_faces[ chunk_faces3[ f ] ];
  1343. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  1344. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  1345. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  1346. offset_custom += 3;
  1347. }
  1348. } else if ( customAttribute.boundTo === "faces" ) {
  1349. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1350. value = customAttribute.value[ chunk_faces3[ f ] ];
  1351. customAttribute.array[ offset_custom ] = value;
  1352. customAttribute.array[ offset_custom + 1 ] = value;
  1353. customAttribute.array[ offset_custom + 2 ] = value;
  1354. offset_custom += 3;
  1355. }
  1356. }
  1357. } else if ( customAttribute.size === 2 ) {
  1358. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  1359. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1360. face = obj_faces[ chunk_faces3[ f ] ];
  1361. v1 = customAttribute.value[ face.a ];
  1362. v2 = customAttribute.value[ face.b ];
  1363. v3 = customAttribute.value[ face.c ];
  1364. customAttribute.array[ offset_custom ] = v1.x;
  1365. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1366. customAttribute.array[ offset_custom + 2 ] = v2.x;
  1367. customAttribute.array[ offset_custom + 3 ] = v2.y;
  1368. customAttribute.array[ offset_custom + 4 ] = v3.x;
  1369. customAttribute.array[ offset_custom + 5 ] = v3.y;
  1370. offset_custom += 6;
  1371. }
  1372. } else if ( customAttribute.boundTo === "faces" ) {
  1373. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1374. value = customAttribute.value[ chunk_faces3[ f ] ];
  1375. v1 = value;
  1376. v2 = value;
  1377. v3 = value;
  1378. customAttribute.array[ offset_custom ] = v1.x;
  1379. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1380. customAttribute.array[ offset_custom + 2 ] = v2.x;
  1381. customAttribute.array[ offset_custom + 3 ] = v2.y;
  1382. customAttribute.array[ offset_custom + 4 ] = v3.x;
  1383. customAttribute.array[ offset_custom + 5 ] = v3.y;
  1384. offset_custom += 6;
  1385. }
  1386. }
  1387. } else if ( customAttribute.size === 3 ) {
  1388. var pp;
  1389. if ( customAttribute.type === "c" ) {
  1390. pp = [ "r", "g", "b" ];
  1391. } else {
  1392. pp = [ "x", "y", "z" ];
  1393. }
  1394. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  1395. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1396. face = obj_faces[ chunk_faces3[ f ] ];
  1397. v1 = customAttribute.value[ face.a ];
  1398. v2 = customAttribute.value[ face.b ];
  1399. v3 = customAttribute.value[ face.c ];
  1400. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1401. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1402. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1403. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1404. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1405. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1406. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1407. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1408. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1409. offset_custom += 9;
  1410. }
  1411. } else if ( customAttribute.boundTo === "faces" ) {
  1412. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1413. value = customAttribute.value[ chunk_faces3[ f ] ];
  1414. v1 = value;
  1415. v2 = value;
  1416. v3 = value;
  1417. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1418. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1419. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1420. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1421. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1422. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1423. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1424. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1425. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1426. offset_custom += 9;
  1427. }
  1428. } else if ( customAttribute.boundTo === "faceVertices" ) {
  1429. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1430. value = customAttribute.value[ chunk_faces3[ f ] ];
  1431. v1 = value[ 0 ];
  1432. v2 = value[ 1 ];
  1433. v3 = value[ 2 ];
  1434. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  1435. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  1436. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  1437. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  1438. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  1439. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  1440. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  1441. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  1442. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  1443. offset_custom += 9;
  1444. }
  1445. }
  1446. } else if ( customAttribute.size === 4 ) {
  1447. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  1448. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1449. face = obj_faces[ chunk_faces3[ f ] ];
  1450. v1 = customAttribute.value[ face.a ];
  1451. v2 = customAttribute.value[ face.b ];
  1452. v3 = customAttribute.value[ face.c ];
  1453. customAttribute.array[ offset_custom ] = v1.x;
  1454. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1455. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1456. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1457. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1458. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1459. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1460. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1461. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1462. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1463. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1464. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1465. offset_custom += 12;
  1466. }
  1467. } else if ( customAttribute.boundTo === "faces" ) {
  1468. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1469. value = customAttribute.value[ chunk_faces3[ f ] ];
  1470. v1 = value;
  1471. v2 = value;
  1472. v3 = value;
  1473. customAttribute.array[ offset_custom ] = v1.x;
  1474. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1475. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1476. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1477. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1478. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1479. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1480. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1481. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1482. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1483. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1484. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1485. offset_custom += 12;
  1486. }
  1487. } else if ( customAttribute.boundTo === "faceVertices" ) {
  1488. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  1489. value = customAttribute.value[ chunk_faces3[ f ] ];
  1490. v1 = value[ 0 ];
  1491. v2 = value[ 1 ];
  1492. v3 = value[ 2 ];
  1493. customAttribute.array[ offset_custom ] = v1.x;
  1494. customAttribute.array[ offset_custom + 1 ] = v1.y;
  1495. customAttribute.array[ offset_custom + 2 ] = v1.z;
  1496. customAttribute.array[ offset_custom + 3 ] = v1.w;
  1497. customAttribute.array[ offset_custom + 4 ] = v2.x;
  1498. customAttribute.array[ offset_custom + 5 ] = v2.y;
  1499. customAttribute.array[ offset_custom + 6 ] = v2.z;
  1500. customAttribute.array[ offset_custom + 7 ] = v2.w;
  1501. customAttribute.array[ offset_custom + 8 ] = v3.x;
  1502. customAttribute.array[ offset_custom + 9 ] = v3.y;
  1503. customAttribute.array[ offset_custom + 10 ] = v3.z;
  1504. customAttribute.array[ offset_custom + 11 ] = v3.w;
  1505. offset_custom += 12;
  1506. }
  1507. }
  1508. }
  1509. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  1510. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  1511. }
  1512. }
  1513. if ( dispose ) {
  1514. delete geometryGroup.__inittedArrays;
  1515. delete geometryGroup.__colorArray;
  1516. delete geometryGroup.__normalArray;
  1517. delete geometryGroup.__tangentArray;
  1518. delete geometryGroup.__uvArray;
  1519. delete geometryGroup.__uv2Array;
  1520. delete geometryGroup.__faceArray;
  1521. delete geometryGroup.__vertexArray;
  1522. delete geometryGroup.__lineArray;
  1523. delete geometryGroup.__skinIndexArray;
  1524. delete geometryGroup.__skinWeightArray;
  1525. }
  1526. };
  1527. function setDirectBuffers ( geometry, hint, dispose ) {
  1528. var attributes = geometry.attributes;
  1529. var attributeName, attributeItem;
  1530. for ( attributeName in attributes ) {
  1531. attributeItem = attributes[ attributeName ];
  1532. if ( attributeItem.needsUpdate ) {
  1533. if ( attributeName === 'index' ) {
  1534. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  1535. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  1536. } else {
  1537. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1538. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  1539. }
  1540. attributeItem.needsUpdate = false;
  1541. }
  1542. if ( dispose && ! attributeItem.dynamic ) {
  1543. attributeItem.array = null;
  1544. }
  1545. }
  1546. };
  1547. // Buffer rendering
  1548. this.renderBufferImmediate = function ( object, program, material ) {
  1549. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  1550. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  1551. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  1552. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  1553. if ( object.hasPositions ) {
  1554. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  1555. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  1556. _gl.enableVertexAttribArray( program.attributes.position );
  1557. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1558. }
  1559. if ( object.hasNormals ) {
  1560. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  1561. if ( material.shading === THREE.FlatShading ) {
  1562. var nx, ny, nz,
  1563. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  1564. normalArray,
  1565. i, il = object.count * 3;
  1566. for( i = 0; i < il; i += 9 ) {
  1567. normalArray = object.normalArray;
  1568. nax = normalArray[ i ];
  1569. nay = normalArray[ i + 1 ];
  1570. naz = normalArray[ i + 2 ];
  1571. nbx = normalArray[ i + 3 ];
  1572. nby = normalArray[ i + 4 ];
  1573. nbz = normalArray[ i + 5 ];
  1574. ncx = normalArray[ i + 6 ];
  1575. ncy = normalArray[ i + 7 ];
  1576. ncz = normalArray[ i + 8 ];
  1577. nx = ( nax + nbx + ncx ) / 3;
  1578. ny = ( nay + nby + ncy ) / 3;
  1579. nz = ( naz + nbz + ncz ) / 3;
  1580. normalArray[ i ] = nx;
  1581. normalArray[ i + 1 ] = ny;
  1582. normalArray[ i + 2 ] = nz;
  1583. normalArray[ i + 3 ] = nx;
  1584. normalArray[ i + 4 ] = ny;
  1585. normalArray[ i + 5 ] = nz;
  1586. normalArray[ i + 6 ] = nx;
  1587. normalArray[ i + 7 ] = ny;
  1588. normalArray[ i + 8 ] = nz;
  1589. }
  1590. }
  1591. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  1592. _gl.enableVertexAttribArray( program.attributes.normal );
  1593. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  1594. }
  1595. if ( object.hasUvs && material.map ) {
  1596. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  1597. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  1598. _gl.enableVertexAttribArray( program.attributes.uv );
  1599. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  1600. }
  1601. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  1602. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  1603. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  1604. _gl.enableVertexAttribArray( program.attributes.color );
  1605. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  1606. }
  1607. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  1608. object.count = 0;
  1609. };
  1610. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  1611. if ( material.visible === false ) return;
  1612. var linewidth, a, attribute;
  1613. var attributeItem, attributeName, attributePointer, attributeSize;
  1614. var program = setProgram( camera, lights, fog, material, object );
  1615. var programAttributes = program.attributes;
  1616. var geometryAttributes = geometry.attributes;
  1617. var updateBuffers = false,
  1618. wireframeBit = material.wireframe ? 1 : 0,
  1619. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  1620. if ( geometryHash !== _currentGeometryGroupHash ) {
  1621. _currentGeometryGroupHash = geometryHash;
  1622. updateBuffers = true;
  1623. }
  1624. if ( updateBuffers ) {
  1625. disableAttributes();
  1626. }
  1627. // render mesh
  1628. if ( object instanceof THREE.Mesh ) {
  1629. var index = geometryAttributes[ "index" ];
  1630. // indexed triangles
  1631. if ( index ) {
  1632. var offsets = geometry.offsets;
  1633. // if there is more than 1 chunk
  1634. // must set attribute pointers to use new offsets for each chunk
  1635. // even if geometry and materials didn't change
  1636. if ( offsets.length > 1 ) updateBuffers = true;
  1637. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  1638. var startIndex = offsets[ i ].index;
  1639. if ( updateBuffers ) {
  1640. for ( attributeName in programAttributes ) {
  1641. attributePointer = programAttributes[ attributeName ];
  1642. attributeItem = geometryAttributes[ attributeName ];
  1643. if ( attributePointer >= 0 ) {
  1644. if ( attributeItem ) {
  1645. attributeSize = attributeItem.itemSize;
  1646. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1647. enableAttribute( attributePointer );
  1648. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  1649. } else if ( material.defaultAttributeValues ) {
  1650. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  1651. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1652. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  1653. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1654. }
  1655. }
  1656. }
  1657. }
  1658. // indices
  1659. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  1660. }
  1661. // render indexed triangles
  1662. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  1663. _this.info.render.calls ++;
  1664. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  1665. _this.info.render.faces += offsets[ i ].count / 3;
  1666. }
  1667. // non-indexed triangles
  1668. } else {
  1669. if ( updateBuffers ) {
  1670. for ( attributeName in programAttributes ) {
  1671. if ( attributeName === 'index') continue;
  1672. attributePointer = programAttributes[ attributeName ];
  1673. attributeItem = geometryAttributes[ attributeName ];
  1674. if ( attributePointer >= 0 ) {
  1675. if ( attributeItem ) {
  1676. attributeSize = attributeItem.itemSize;
  1677. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1678. enableAttribute( attributePointer );
  1679. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  1680. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  1681. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  1682. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1683. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  1684. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1685. }
  1686. }
  1687. }
  1688. }
  1689. }
  1690. var position = geometry.attributes[ "position" ];
  1691. // render non-indexed triangles
  1692. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  1693. _this.info.render.calls ++;
  1694. _this.info.render.vertices += position.numItems / 3;
  1695. _this.info.render.faces += position.numItems / 3 / 3;
  1696. }
  1697. // render particles
  1698. } else if ( object instanceof THREE.ParticleSystem ) {
  1699. if ( updateBuffers ) {
  1700. for ( attributeName in programAttributes ) {
  1701. attributePointer = programAttributes[ attributeName ];
  1702. attributeItem = geometryAttributes[ attributeName ];
  1703. if ( attributePointer >= 0 ) {
  1704. if ( attributeItem ) {
  1705. attributeSize = attributeItem.itemSize;
  1706. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1707. enableAttribute( attributePointer );
  1708. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  1709. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  1710. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  1711. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1712. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  1713. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1714. }
  1715. }
  1716. }
  1717. }
  1718. var position = geometryAttributes[ "position" ];
  1719. // render particles
  1720. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  1721. _this.info.render.calls ++;
  1722. _this.info.render.points += position.numItems / 3;
  1723. }
  1724. } else if ( object instanceof THREE.Line ) {
  1725. if ( updateBuffers ) {
  1726. for ( attributeName in programAttributes ) {
  1727. attributePointer = programAttributes[ attributeName ];
  1728. attributeItem = geometryAttributes[ attributeName ];
  1729. if ( attributePointer >= 0 ) {
  1730. if ( attributeItem ) {
  1731. attributeSize = attributeItem.itemSize;
  1732. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  1733. enableAttribute( attributePointer );
  1734. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  1735. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  1736. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  1737. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1738. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  1739. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  1740. }
  1741. }
  1742. }
  1743. }
  1744. // render lines
  1745. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  1746. setLineWidth( material.linewidth );
  1747. var position = geometryAttributes[ "position" ];
  1748. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  1749. _this.info.render.calls ++;
  1750. _this.info.render.points += position.numItems;
  1751. }
  1752. }
  1753. };
  1754. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  1755. if ( material.visible === false ) return;
  1756. var linewidth, a, attribute, i, il;
  1757. var program = setProgram( camera, lights, fog, material, object );
  1758. var attributes = program.attributes;
  1759. var updateBuffers = false,
  1760. wireframeBit = material.wireframe ? 1 : 0,
  1761. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  1762. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  1763. _currentGeometryGroupHash = geometryGroupHash;
  1764. updateBuffers = true;
  1765. }
  1766. if ( updateBuffers ) {
  1767. disableAttributes();
  1768. }
  1769. // vertices
  1770. if ( !material.morphTargets && attributes.position >= 0 ) {
  1771. if ( updateBuffers ) {
  1772. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  1773. enableAttribute( attributes.position );
  1774. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1775. }
  1776. } else {
  1777. if ( object.morphTargetBase ) {
  1778. setupMorphTargets( material, geometryGroup, object );
  1779. }
  1780. }
  1781. if ( updateBuffers ) {
  1782. // custom attributes
  1783. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  1784. if ( geometryGroup.__webglCustomAttributesList ) {
  1785. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  1786. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  1787. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  1788. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  1789. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  1790. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  1791. }
  1792. }
  1793. }
  1794. // colors
  1795. if ( attributes.color >= 0 ) {
  1796. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  1797. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  1798. enableAttribute( attributes.color );
  1799. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  1800. } else if ( material.defaultAttributeValues ) {
  1801. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  1802. }
  1803. }
  1804. // normals
  1805. if ( attributes.normal >= 0 ) {
  1806. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  1807. enableAttribute( attributes.normal );
  1808. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  1809. }
  1810. // tangents
  1811. if ( attributes.tangent >= 0 ) {
  1812. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  1813. enableAttribute( attributes.tangent );
  1814. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  1815. }
  1816. // uvs
  1817. if ( attributes.uv >= 0 ) {
  1818. if ( object.geometry.faceVertexUvs[0] ) {
  1819. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  1820. enableAttribute( attributes.uv );
  1821. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  1822. } else if ( material.defaultAttributeValues ) {
  1823. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  1824. }
  1825. }
  1826. if ( attributes.uv2 >= 0 ) {
  1827. if ( object.geometry.faceVertexUvs[1] ) {
  1828. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  1829. enableAttribute( attributes.uv2 );
  1830. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  1831. } else if ( material.defaultAttributeValues ) {
  1832. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  1833. }
  1834. }
  1835. if ( material.skinning &&
  1836. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  1837. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  1838. enableAttribute( attributes.skinIndex );
  1839. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  1840. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  1841. enableAttribute( attributes.skinWeight );
  1842. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  1843. }
  1844. // line distances
  1845. if ( attributes.lineDistance >= 0 ) {
  1846. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  1847. enableAttribute( attributes.lineDistance );
  1848. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  1849. }
  1850. }
  1851. // render mesh
  1852. if ( object instanceof THREE.Mesh ) {
  1853. // wireframe
  1854. if ( material.wireframe ) {
  1855. setLineWidth( material.wireframeLinewidth );
  1856. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  1857. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  1858. // triangles
  1859. } else {
  1860. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  1861. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  1862. }
  1863. _this.info.render.calls ++;
  1864. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  1865. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  1866. // render lines
  1867. } else if ( object instanceof THREE.Line ) {
  1868. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  1869. setLineWidth( material.linewidth );
  1870. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  1871. _this.info.render.calls ++;
  1872. // render particles
  1873. } else if ( object instanceof THREE.ParticleSystem ) {
  1874. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  1875. _this.info.render.calls ++;
  1876. _this.info.render.points += geometryGroup.__webglParticleCount;
  1877. // render ribbon
  1878. } else if ( object instanceof THREE.Ribbon ) {
  1879. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  1880. _this.info.render.calls ++;
  1881. }
  1882. };
  1883. function enableAttribute( attribute ) {
  1884. if ( ! _enabledAttributes[ attribute ] ) {
  1885. _gl.enableVertexAttribArray( attribute );
  1886. _enabledAttributes[ attribute ] = true;
  1887. }
  1888. };
  1889. function disableAttributes() {
  1890. for ( var attribute in _enabledAttributes ) {
  1891. if ( _enabledAttributes[ attribute ] ) {
  1892. _gl.disableVertexAttribArray( attribute );
  1893. _enabledAttributes[ attribute ] = false;
  1894. }
  1895. }
  1896. };
  1897. function setupMorphTargets ( material, geometryGroup, object ) {
  1898. // set base
  1899. var attributes = material.program.attributes;
  1900. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  1901. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  1902. enableAttribute( attributes.position );
  1903. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1904. } else if ( attributes.position >= 0 ) {
  1905. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  1906. enableAttribute( attributes.position );
  1907. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  1908. }
  1909. if ( object.morphTargetForcedOrder.length ) {
  1910. // set forced order
  1911. var m = 0;
  1912. var order = object.morphTargetForcedOrder;
  1913. var influences = object.morphTargetInfluences;
  1914. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  1915. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  1916. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  1917. enableAttribute( attributes[ "morphTarget" + m ] );
  1918. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1919. }
  1920. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  1921. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  1922. enableAttribute( attributes[ "morphNormal" + m ] );
  1923. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1924. }
  1925. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  1926. m ++;
  1927. }
  1928. } else {
  1929. // find the most influencing
  1930. var influence, activeInfluenceIndices = [];
  1931. var influences = object.morphTargetInfluences;
  1932. var i, il = influences.length;
  1933. for ( i = 0; i < il; i ++ ) {
  1934. influence = influences[ i ];
  1935. if ( influence > 0 ) {
  1936. activeInfluenceIndices.push( [ influence, i ] );
  1937. }
  1938. }
  1939. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  1940. activeInfluenceIndices.sort( numericalSort );
  1941. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  1942. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  1943. activeInfluenceIndices.sort( numericalSort );
  1944. } else if ( activeInfluenceIndices.length === 0 ) {
  1945. activeInfluenceIndices.push( [ 0, 0 ] );
  1946. };
  1947. var influenceIndex, m = 0;
  1948. while ( m < material.numSupportedMorphTargets ) {
  1949. if ( activeInfluenceIndices[ m ] ) {
  1950. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  1951. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  1952. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  1953. enableAttribute( attributes[ "morphTarget" + m ] );
  1954. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1955. }
  1956. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  1957. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  1958. enableAttribute( attributes[ "morphNormal" + m ] );
  1959. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1960. }
  1961. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  1962. } else {
  1963. /*
  1964. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1965. if ( material.morphNormals ) {
  1966. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  1967. }
  1968. */
  1969. object.__webglMorphTargetInfluences[ m ] = 0;
  1970. }
  1971. m ++;
  1972. }
  1973. }
  1974. // load updated influences uniform
  1975. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  1976. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  1977. }
  1978. };
  1979. // Sorting
  1980. function painterSortStable ( a, b ) {
  1981. if ( a.z !== b.z ) {
  1982. return b.z - a.z;
  1983. } else {
  1984. return a.id - b.id;
  1985. }
  1986. };
  1987. function numericalSort ( a, b ) {
  1988. return b[ 0 ] - a[ 0 ];
  1989. };
  1990. // Rendering
  1991. this.render = function ( scene, camera, renderTarget, forceClear ) {
  1992. if ( camera instanceof THREE.Camera === false ) {
  1993. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  1994. return;
  1995. }
  1996. var i, il,
  1997. webglObject, object,
  1998. renderList,
  1999. lights = scene.__lights,
  2000. fog = scene.fog;
  2001. // reset caching for this frame
  2002. _currentMaterialId = -1;
  2003. _lightsNeedUpdate = true;
  2004. // update scene graph
  2005. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  2006. // update camera matrices and frustum
  2007. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2008. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2009. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  2010. _frustum.setFromMatrix( _projScreenMatrix );
  2011. // update WebGL objects
  2012. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  2013. // custom render plugins (pre pass)
  2014. renderPlugins( this.renderPluginsPre, scene, camera );
  2015. //
  2016. _this.info.render.calls = 0;
  2017. _this.info.render.vertices = 0;
  2018. _this.info.render.faces = 0;
  2019. _this.info.render.points = 0;
  2020. this.setRenderTarget( renderTarget );
  2021. if ( this.autoClear || forceClear ) {
  2022. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  2023. }
  2024. // set matrices for regular objects (frustum culled)
  2025. renderList = scene.__webglObjects;
  2026. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  2027. webglObject = renderList[ i ];
  2028. object = webglObject.object;
  2029. webglObject.id = i;
  2030. webglObject.render = false;
  2031. if ( object.visible ) {
  2032. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  2033. setupMatrices( object, camera );
  2034. unrollBufferMaterial( webglObject );
  2035. webglObject.render = true;
  2036. if ( this.sortObjects === true ) {
  2037. if ( object.renderDepth !== null ) {
  2038. webglObject.z = object.renderDepth;
  2039. } else {
  2040. _vector3.getPositionFromMatrix( object.matrixWorld );
  2041. _vector3.applyProjection( _projScreenMatrix );
  2042. webglObject.z = _vector3.z;
  2043. }
  2044. }
  2045. }
  2046. }
  2047. }
  2048. if ( this.sortObjects ) {
  2049. renderList.sort( painterSortStable );
  2050. }
  2051. // set matrices for immediate objects
  2052. renderList = scene.__webglObjectsImmediate;
  2053. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  2054. webglObject = renderList[ i ];
  2055. object = webglObject.object;
  2056. if ( object.visible ) {
  2057. setupMatrices( object, camera );
  2058. unrollImmediateBufferMaterial( webglObject );
  2059. }
  2060. }
  2061. if ( scene.overrideMaterial ) {
  2062. var material = scene.overrideMaterial;
  2063. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  2064. this.setDepthTest( material.depthTest );
  2065. this.setDepthWrite( material.depthWrite );
  2066. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  2067. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  2068. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  2069. } else {
  2070. var material = null;
  2071. // opaque pass (front-to-back order)
  2072. this.setBlending( THREE.NoBlending );
  2073. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  2074. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  2075. // transparent pass (back-to-front order)
  2076. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  2077. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  2078. }
  2079. // custom render plugins (post pass)
  2080. renderPlugins( this.renderPluginsPost, scene, camera );
  2081. // Generate mipmap if we're using any kind of mipmap filtering
  2082. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  2083. updateRenderTargetMipmap( renderTarget );
  2084. }
  2085. // Ensure depth buffer writing is enabled so it can be cleared on next render
  2086. this.setDepthTest( true );
  2087. this.setDepthWrite( true );
  2088. // _gl.finish();
  2089. };
  2090. function renderPlugins( plugins, scene, camera ) {
  2091. if ( ! plugins.length ) return;
  2092. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  2093. // reset state for plugin (to start from clean slate)
  2094. _currentProgram = null;
  2095. _currentCamera = null;
  2096. _oldBlending = -1;
  2097. _oldDepthTest = -1;
  2098. _oldDepthWrite = -1;
  2099. _oldDoubleSided = -1;
  2100. _oldFlipSided = -1;
  2101. _currentGeometryGroupHash = -1;
  2102. _currentMaterialId = -1;
  2103. _lightsNeedUpdate = true;
  2104. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  2105. // reset state after plugin (anything could have changed)
  2106. _currentProgram = null;
  2107. _currentCamera = null;
  2108. _oldBlending = -1;
  2109. _oldDepthTest = -1;
  2110. _oldDepthWrite = -1;
  2111. _oldDoubleSided = -1;
  2112. _oldFlipSided = -1;
  2113. _currentGeometryGroupHash = -1;
  2114. _currentMaterialId = -1;
  2115. _lightsNeedUpdate = true;
  2116. }
  2117. };
  2118. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  2119. var webglObject, object, buffer, material, start, end, delta;
  2120. if ( reverse ) {
  2121. start = renderList.length - 1;
  2122. end = -1;
  2123. delta = -1;
  2124. } else {
  2125. start = 0;
  2126. end = renderList.length;
  2127. delta = 1;
  2128. }
  2129. for ( var i = start; i !== end; i += delta ) {
  2130. webglObject = renderList[ i ];
  2131. if ( webglObject.render ) {
  2132. object = webglObject.object;
  2133. buffer = webglObject.buffer;
  2134. if ( overrideMaterial ) {
  2135. material = overrideMaterial;
  2136. } else {
  2137. material = webglObject[ materialType ];
  2138. if ( ! material ) continue;
  2139. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  2140. _this.setDepthTest( material.depthTest );
  2141. _this.setDepthWrite( material.depthWrite );
  2142. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  2143. }
  2144. _this.setMaterialFaces( material );
  2145. if ( buffer instanceof THREE.BufferGeometry ) {
  2146. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  2147. } else {
  2148. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  2149. }
  2150. }
  2151. }
  2152. };
  2153. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  2154. var webglObject, object, material, program;
  2155. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  2156. webglObject = renderList[ i ];
  2157. object = webglObject.object;
  2158. if ( object.visible ) {
  2159. if ( overrideMaterial ) {
  2160. material = overrideMaterial;
  2161. } else {
  2162. material = webglObject[ materialType ];
  2163. if ( ! material ) continue;
  2164. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  2165. _this.setDepthTest( material.depthTest );
  2166. _this.setDepthWrite( material.depthWrite );
  2167. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  2168. }
  2169. _this.renderImmediateObject( camera, lights, fog, material, object );
  2170. }
  2171. }
  2172. };
  2173. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  2174. var program = setProgram( camera, lights, fog, material, object );
  2175. _currentGeometryGroupHash = -1;
  2176. _this.setMaterialFaces( material );
  2177. if ( object.immediateRenderCallback ) {
  2178. object.immediateRenderCallback( program, _gl, _frustum );
  2179. } else {
  2180. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  2181. }
  2182. };
  2183. function unrollImmediateBufferMaterial ( globject ) {
  2184. var object = globject.object,
  2185. material = object.material;
  2186. if ( material.transparent ) {
  2187. globject.transparent = material;
  2188. globject.opaque = null;
  2189. } else {
  2190. globject.opaque = material;
  2191. globject.transparent = null;
  2192. }
  2193. };
  2194. function unrollBufferMaterial ( globject ) {
  2195. var object = globject.object,
  2196. buffer = globject.buffer,
  2197. material, materialIndex, meshMaterial;
  2198. meshMaterial = object.material;
  2199. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  2200. materialIndex = buffer.materialIndex;
  2201. material = meshMaterial.materials[ materialIndex ];
  2202. if ( material.transparent ) {
  2203. globject.transparent = material;
  2204. globject.opaque = null;
  2205. } else {
  2206. globject.opaque = material;
  2207. globject.transparent = null;
  2208. }
  2209. } else {
  2210. material = meshMaterial;
  2211. if ( material ) {
  2212. if ( material.transparent ) {
  2213. globject.transparent = material;
  2214. globject.opaque = null;
  2215. } else {
  2216. globject.opaque = material;
  2217. globject.transparent = null;
  2218. }
  2219. }
  2220. }
  2221. };
  2222. // Geometry splitting
  2223. function sortFacesByMaterial ( geometry, material ) {
  2224. var f, fl, face, materialIndex, vertices,
  2225. groupHash, hash_map = {};
  2226. var numMorphTargets = geometry.morphTargets.length;
  2227. var numMorphNormals = geometry.morphNormals.length;
  2228. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  2229. geometry.geometryGroups = {};
  2230. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  2231. face = geometry.faces[ f ];
  2232. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  2233. if ( hash_map[ materialIndex ] === undefined ) {
  2234. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  2235. }
  2236. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  2237. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  2238. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  2239. }
  2240. vertices = 3;
  2241. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  2242. hash_map[ materialIndex ].counter += 1;
  2243. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  2244. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  2245. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  2246. }
  2247. }
  2248. geometry.geometryGroups[ groupHash ].faces3.push( f );
  2249. geometry.geometryGroups[ groupHash ].vertices += vertices;
  2250. }
  2251. geometry.geometryGroupsList = [];
  2252. for ( var g in geometry.geometryGroups ) {
  2253. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  2254. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  2255. }
  2256. };
  2257. // Objects refresh
  2258. this.initWebGLObjects = function ( scene ) {
  2259. if ( !scene.__webglObjects ) {
  2260. scene.__webglObjects = [];
  2261. scene.__webglObjectsImmediate = [];
  2262. scene.__webglSprites = [];
  2263. scene.__webglFlares = [];
  2264. }
  2265. while ( scene.__objectsAdded.length ) {
  2266. addObject( scene.__objectsAdded[ 0 ], scene );
  2267. scene.__objectsAdded.splice( 0, 1 );
  2268. }
  2269. while ( scene.__objectsRemoved.length ) {
  2270. removeObject( scene.__objectsRemoved[ 0 ], scene );
  2271. scene.__objectsRemoved.splice( 0, 1 );
  2272. }
  2273. // update must be called after objects adding / removal
  2274. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  2275. var object = scene.__webglObjects[ o ].object;
  2276. // TODO: Remove this hack (WebGLRenderer refactoring)
  2277. if ( object.__webglInit === undefined ) {
  2278. if ( object.__webglActive !== undefined ) {
  2279. removeObject( object, scene );
  2280. }
  2281. addObject( object, scene );
  2282. }
  2283. updateObject( object );
  2284. }
  2285. };
  2286. // Objects adding
  2287. function addObject( object, scene ) {
  2288. var g, geometry, material, geometryGroup;
  2289. if ( object.__webglInit === undefined ) {
  2290. object.__webglInit = true;
  2291. object._modelViewMatrix = new THREE.Matrix4();
  2292. object._normalMatrix = new THREE.Matrix3();
  2293. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  2294. object.geometry.__webglInit = true;
  2295. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  2296. }
  2297. geometry = object.geometry;
  2298. if ( geometry === undefined ) {
  2299. // fail silently for now
  2300. } else if ( geometry instanceof THREE.BufferGeometry ) {
  2301. initDirectBuffers( geometry );
  2302. } else if ( object instanceof THREE.Mesh ) {
  2303. material = object.material;
  2304. if ( geometry.geometryGroups === undefined ) {
  2305. sortFacesByMaterial( geometry, material );
  2306. }
  2307. // create separate VBOs per geometry chunk
  2308. for ( g in geometry.geometryGroups ) {
  2309. geometryGroup = geometry.geometryGroups[ g ];
  2310. // initialise VBO on the first access
  2311. if ( ! geometryGroup.__webglVertexBuffer ) {
  2312. createMeshBuffers( geometryGroup );
  2313. initMeshBuffers( geometryGroup, object );
  2314. geometry.verticesNeedUpdate = true;
  2315. geometry.morphTargetsNeedUpdate = true;
  2316. geometry.elementsNeedUpdate = true;
  2317. geometry.uvsNeedUpdate = true;
  2318. geometry.normalsNeedUpdate = true;
  2319. geometry.tangentsNeedUpdate = true;
  2320. geometry.colorsNeedUpdate = true;
  2321. }
  2322. }
  2323. } else if ( object instanceof THREE.Ribbon ) {
  2324. if ( ! geometry.__webglVertexBuffer ) {
  2325. createRibbonBuffers( geometry );
  2326. initRibbonBuffers( geometry, object );
  2327. geometry.verticesNeedUpdate = true;
  2328. geometry.colorsNeedUpdate = true;
  2329. geometry.normalsNeedUpdate = true;
  2330. }
  2331. } else if ( object instanceof THREE.Line ) {
  2332. if ( ! geometry.__webglVertexBuffer ) {
  2333. createLineBuffers( geometry );
  2334. initLineBuffers( geometry, object );
  2335. geometry.verticesNeedUpdate = true;
  2336. geometry.colorsNeedUpdate = true;
  2337. geometry.lineDistancesNeedUpdate = true;
  2338. }
  2339. } else if ( object instanceof THREE.ParticleSystem ) {
  2340. if ( ! geometry.__webglVertexBuffer ) {
  2341. createParticleBuffers( geometry );
  2342. initParticleBuffers( geometry, object );
  2343. geometry.verticesNeedUpdate = true;
  2344. geometry.colorsNeedUpdate = true;
  2345. }
  2346. }
  2347. }
  2348. if ( object.__webglActive === undefined ) {
  2349. if ( object instanceof THREE.Mesh ) {
  2350. geometry = object.geometry;
  2351. if ( geometry instanceof THREE.BufferGeometry ) {
  2352. addBuffer( scene.__webglObjects, geometry, object );
  2353. } else if ( geometry instanceof THREE.Geometry ) {
  2354. for ( g in geometry.geometryGroups ) {
  2355. geometryGroup = geometry.geometryGroups[ g ];
  2356. addBuffer( scene.__webglObjects, geometryGroup, object );
  2357. }
  2358. }
  2359. } else if ( object instanceof THREE.Ribbon ||
  2360. object instanceof THREE.Line ||
  2361. object instanceof THREE.ParticleSystem ) {
  2362. geometry = object.geometry;
  2363. addBuffer( scene.__webglObjects, geometry, object );
  2364. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  2365. addBufferImmediate( scene.__webglObjectsImmediate, object );
  2366. } else if ( object instanceof THREE.Sprite ) {
  2367. scene.__webglSprites.push( object );
  2368. } else if ( object instanceof THREE.LensFlare ) {
  2369. scene.__webglFlares.push( object );
  2370. }
  2371. object.__webglActive = true;
  2372. }
  2373. };
  2374. function addBuffer( objlist, buffer, object ) {
  2375. objlist.push(
  2376. {
  2377. id: null,
  2378. buffer: buffer,
  2379. object: object,
  2380. opaque: null,
  2381. transparent: null,
  2382. z: 0
  2383. }
  2384. );
  2385. };
  2386. function addBufferImmediate( objlist, object ) {
  2387. objlist.push(
  2388. {
  2389. id: null,
  2390. object: object,
  2391. opaque: null,
  2392. transparent: null,
  2393. z: 0
  2394. }
  2395. );
  2396. };
  2397. // Objects updates
  2398. function updateObject( object ) {
  2399. var geometry = object.geometry,
  2400. geometryGroup, customAttributesDirty, material;
  2401. if ( geometry instanceof THREE.BufferGeometry ) {
  2402. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  2403. } else if ( object instanceof THREE.Mesh ) {
  2404. // check all geometry groups
  2405. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  2406. geometryGroup = geometry.geometryGroupsList[ i ];
  2407. material = getBufferMaterial( object, geometryGroup );
  2408. if ( geometry.buffersNeedUpdate ) {
  2409. initMeshBuffers( geometryGroup, object );
  2410. }
  2411. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2412. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  2413. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  2414. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  2415. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  2416. }
  2417. }
  2418. geometry.verticesNeedUpdate = false;
  2419. geometry.morphTargetsNeedUpdate = false;
  2420. geometry.elementsNeedUpdate = false;
  2421. geometry.uvsNeedUpdate = false;
  2422. geometry.normalsNeedUpdate = false;
  2423. geometry.colorsNeedUpdate = false;
  2424. geometry.tangentsNeedUpdate = false;
  2425. geometry.buffersNeedUpdate = false;
  2426. material.attributes && clearCustomAttributes( material );
  2427. } else if ( object instanceof THREE.Ribbon ) {
  2428. material = getBufferMaterial( object, geometry );
  2429. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2430. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  2431. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  2432. }
  2433. geometry.verticesNeedUpdate = false;
  2434. geometry.colorsNeedUpdate = false;
  2435. geometry.normalsNeedUpdate = false;
  2436. material.attributes && clearCustomAttributes( material );
  2437. } else if ( object instanceof THREE.Line ) {
  2438. material = getBufferMaterial( object, geometry );
  2439. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2440. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  2441. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  2442. }
  2443. geometry.verticesNeedUpdate = false;
  2444. geometry.colorsNeedUpdate = false;
  2445. geometry.lineDistancesNeedUpdate = false;
  2446. material.attributes && clearCustomAttributes( material );
  2447. } else if ( object instanceof THREE.ParticleSystem ) {
  2448. material = getBufferMaterial( object, geometry );
  2449. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  2450. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  2451. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  2452. }
  2453. geometry.verticesNeedUpdate = false;
  2454. geometry.colorsNeedUpdate = false;
  2455. material.attributes && clearCustomAttributes( material );
  2456. }
  2457. };
  2458. // Objects updates - custom attributes check
  2459. function areCustomAttributesDirty( material ) {
  2460. for ( var a in material.attributes ) {
  2461. if ( material.attributes[ a ].needsUpdate ) return true;
  2462. }
  2463. return false;
  2464. };
  2465. function clearCustomAttributes( material ) {
  2466. for ( var a in material.attributes ) {
  2467. material.attributes[ a ].needsUpdate = false;
  2468. }
  2469. };
  2470. // Objects removal
  2471. function removeObject( object, scene ) {
  2472. if ( object instanceof THREE.Mesh ||
  2473. object instanceof THREE.ParticleSystem ||
  2474. object instanceof THREE.Ribbon ||
  2475. object instanceof THREE.Line ) {
  2476. removeInstances( scene.__webglObjects, object );
  2477. } else if ( object instanceof THREE.Sprite ) {
  2478. removeInstancesDirect( scene.__webglSprites, object );
  2479. } else if ( object instanceof THREE.LensFlare ) {
  2480. removeInstancesDirect( scene.__webglFlares, object );
  2481. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  2482. removeInstances( scene.__webglObjectsImmediate, object );
  2483. }
  2484. delete object.__webglActive;
  2485. };
  2486. function removeInstances( objlist, object ) {
  2487. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  2488. if ( objlist[ o ].object === object ) {
  2489. objlist.splice( o, 1 );
  2490. }
  2491. }
  2492. };
  2493. function removeInstancesDirect( objlist, object ) {
  2494. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  2495. if ( objlist[ o ] === object ) {
  2496. objlist.splice( o, 1 );
  2497. }
  2498. }
  2499. };
  2500. // Materials
  2501. this.initMaterial = function ( material, lights, fog, object ) {
  2502. material.addEventListener( 'dispose', onMaterialDispose );
  2503. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  2504. if ( material instanceof THREE.MeshDepthMaterial ) {
  2505. shaderID = 'depth';
  2506. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  2507. shaderID = 'normal';
  2508. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  2509. shaderID = 'basic';
  2510. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  2511. shaderID = 'lambert';
  2512. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  2513. shaderID = 'phong';
  2514. } else if ( material instanceof THREE.LineBasicMaterial ) {
  2515. shaderID = 'basic';
  2516. } else if ( material instanceof THREE.LineDashedMaterial ) {
  2517. shaderID = 'dashed';
  2518. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  2519. shaderID = 'particle_basic';
  2520. }
  2521. if ( shaderID ) {
  2522. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  2523. }
  2524. // heuristics to create shader parameters according to lights in the scene
  2525. // (not to blow over maxLights budget)
  2526. maxLightCount = allocateLights( lights );
  2527. maxShadows = allocateShadows( lights );
  2528. maxBones = allocateBones( object );
  2529. parameters = {
  2530. map: !!material.map,
  2531. envMap: !!material.envMap,
  2532. lightMap: !!material.lightMap,
  2533. bumpMap: !!material.bumpMap,
  2534. normalMap: !!material.normalMap,
  2535. specularMap: !!material.specularMap,
  2536. vertexColors: material.vertexColors,
  2537. fog: fog,
  2538. useFog: material.fog,
  2539. fogExp: fog instanceof THREE.FogExp2,
  2540. sizeAttenuation: material.sizeAttenuation,
  2541. skinning: material.skinning,
  2542. maxBones: maxBones,
  2543. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  2544. boneTextureWidth: object && object.boneTextureWidth,
  2545. boneTextureHeight: object && object.boneTextureHeight,
  2546. morphTargets: material.morphTargets,
  2547. morphNormals: material.morphNormals,
  2548. maxMorphTargets: this.maxMorphTargets,
  2549. maxMorphNormals: this.maxMorphNormals,
  2550. maxDirLights: maxLightCount.directional,
  2551. maxPointLights: maxLightCount.point,
  2552. maxSpotLights: maxLightCount.spot,
  2553. maxHemiLights: maxLightCount.hemi,
  2554. maxShadows: maxShadows,
  2555. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  2556. shadowMapType: this.shadowMapType,
  2557. shadowMapDebug: this.shadowMapDebug,
  2558. shadowMapCascade: this.shadowMapCascade,
  2559. alphaTest: material.alphaTest,
  2560. metal: material.metal,
  2561. perPixel: material.perPixel,
  2562. wrapAround: material.wrapAround,
  2563. doubleSided: material.side === THREE.DoubleSide,
  2564. flipSided: material.side === THREE.BackSide
  2565. };
  2566. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  2567. var attributes = material.program.attributes;
  2568. if ( material.morphTargets ) {
  2569. material.numSupportedMorphTargets = 0;
  2570. var id, base = "morphTarget";
  2571. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  2572. id = base + i;
  2573. if ( attributes[ id ] >= 0 ) {
  2574. material.numSupportedMorphTargets ++;
  2575. }
  2576. }
  2577. }
  2578. if ( material.morphNormals ) {
  2579. material.numSupportedMorphNormals = 0;
  2580. var id, base = "morphNormal";
  2581. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  2582. id = base + i;
  2583. if ( attributes[ id ] >= 0 ) {
  2584. material.numSupportedMorphNormals ++;
  2585. }
  2586. }
  2587. }
  2588. material.uniformsList = [];
  2589. for ( u in material.uniforms ) {
  2590. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  2591. }
  2592. };
  2593. function setMaterialShaders( material, shaders ) {
  2594. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  2595. material.vertexShader = shaders.vertexShader;
  2596. material.fragmentShader = shaders.fragmentShader;
  2597. };
  2598. function setProgram( camera, lights, fog, material, object ) {
  2599. _usedTextureUnits = 0;
  2600. if ( material.needsUpdate ) {
  2601. if ( material.program ) deallocateMaterial( material );
  2602. _this.initMaterial( material, lights, fog, object );
  2603. material.needsUpdate = false;
  2604. }
  2605. if ( material.morphTargets ) {
  2606. if ( ! object.__webglMorphTargetInfluences ) {
  2607. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  2608. }
  2609. }
  2610. var refreshMaterial = false;
  2611. var program = material.program,
  2612. p_uniforms = program.uniforms,
  2613. m_uniforms = material.uniforms;
  2614. if ( program !== _currentProgram ) {
  2615. _gl.useProgram( program );
  2616. _currentProgram = program;
  2617. refreshMaterial = true;
  2618. }
  2619. if ( material.id !== _currentMaterialId ) {
  2620. _currentMaterialId = material.id;
  2621. refreshMaterial = true;
  2622. }
  2623. if ( refreshMaterial || camera !== _currentCamera ) {
  2624. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  2625. if ( camera !== _currentCamera ) _currentCamera = camera;
  2626. }
  2627. // skinning uniforms must be set even if material didn't change
  2628. // auto-setting of texture unit for bone texture must go before other textures
  2629. // not sure why, but otherwise weird things happen
  2630. if ( material.skinning ) {
  2631. if ( _supportsBoneTextures && object.useVertexTexture ) {
  2632. if ( p_uniforms.boneTexture !== null ) {
  2633. var textureUnit = getTextureUnit();
  2634. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  2635. _this.setTexture( object.boneTexture, textureUnit );
  2636. }
  2637. } else {
  2638. if ( p_uniforms.boneGlobalMatrices !== null ) {
  2639. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  2640. }
  2641. }
  2642. }
  2643. if ( refreshMaterial ) {
  2644. // refresh uniforms common to several materials
  2645. if ( fog && material.fog ) {
  2646. refreshUniformsFog( m_uniforms, fog );
  2647. }
  2648. if ( material instanceof THREE.MeshPhongMaterial ||
  2649. material instanceof THREE.MeshLambertMaterial ||
  2650. material.lights ) {
  2651. if ( _lightsNeedUpdate ) {
  2652. setupLights( program, lights );
  2653. _lightsNeedUpdate = false;
  2654. }
  2655. refreshUniformsLights( m_uniforms, _lights );
  2656. }
  2657. if ( material instanceof THREE.MeshBasicMaterial ||
  2658. material instanceof THREE.MeshLambertMaterial ||
  2659. material instanceof THREE.MeshPhongMaterial ) {
  2660. refreshUniformsCommon( m_uniforms, material );
  2661. }
  2662. // refresh single material specific uniforms
  2663. if ( material instanceof THREE.LineBasicMaterial ) {
  2664. refreshUniformsLine( m_uniforms, material );
  2665. } else if ( material instanceof THREE.LineDashedMaterial ) {
  2666. refreshUniformsLine( m_uniforms, material );
  2667. refreshUniformsDash( m_uniforms, material );
  2668. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  2669. refreshUniformsParticle( m_uniforms, material );
  2670. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  2671. refreshUniformsPhong( m_uniforms, material );
  2672. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  2673. refreshUniformsLambert( m_uniforms, material );
  2674. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  2675. m_uniforms.mNear.value = camera.near;
  2676. m_uniforms.mFar.value = camera.far;
  2677. m_uniforms.opacity.value = material.opacity;
  2678. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  2679. m_uniforms.opacity.value = material.opacity;
  2680. }
  2681. if ( object.receiveShadow && ! material._shadowPass ) {
  2682. refreshUniformsShadow( m_uniforms, lights );
  2683. }
  2684. // load common uniforms
  2685. loadUniformsGeneric( program, material.uniformsList );
  2686. // load material specific uniforms
  2687. // (shader material also gets them for the sake of genericity)
  2688. if ( material instanceof THREE.ShaderMaterial ||
  2689. material instanceof THREE.MeshPhongMaterial ||
  2690. material.envMap ) {
  2691. if ( p_uniforms.cameraPosition !== null ) {
  2692. _vector3.getPositionFromMatrix( camera.matrixWorld );
  2693. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  2694. }
  2695. }
  2696. if ( material instanceof THREE.MeshPhongMaterial ||
  2697. material instanceof THREE.MeshLambertMaterial ||
  2698. material instanceof THREE.ShaderMaterial ||
  2699. material.skinning ) {
  2700. if ( p_uniforms.viewMatrix !== null ) {
  2701. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  2702. }
  2703. }
  2704. }
  2705. loadUniformsMatrices( p_uniforms, object );
  2706. if ( p_uniforms.modelMatrix !== null ) {
  2707. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  2708. }
  2709. return program;
  2710. };
  2711. // Uniforms (refresh uniforms objects)
  2712. function refreshUniformsCommon ( uniforms, material ) {
  2713. uniforms.opacity.value = material.opacity;
  2714. if ( _this.gammaInput ) {
  2715. uniforms.diffuse.value.copyGammaToLinear( material.color );
  2716. } else {
  2717. uniforms.diffuse.value = material.color;
  2718. }
  2719. uniforms.map.value = material.map;
  2720. uniforms.lightMap.value = material.lightMap;
  2721. uniforms.specularMap.value = material.specularMap;
  2722. if ( material.bumpMap ) {
  2723. uniforms.bumpMap.value = material.bumpMap;
  2724. uniforms.bumpScale.value = material.bumpScale;
  2725. }
  2726. if ( material.normalMap ) {
  2727. uniforms.normalMap.value = material.normalMap;
  2728. uniforms.normalScale.value.copy( material.normalScale );
  2729. }
  2730. // uv repeat and offset setting priorities
  2731. // 1. color map
  2732. // 2. specular map
  2733. // 3. normal map
  2734. // 4. bump map
  2735. var uvScaleMap;
  2736. if ( material.map ) {
  2737. uvScaleMap = material.map;
  2738. } else if ( material.specularMap ) {
  2739. uvScaleMap = material.specularMap;
  2740. } else if ( material.normalMap ) {
  2741. uvScaleMap = material.normalMap;
  2742. } else if ( material.bumpMap ) {
  2743. uvScaleMap = material.bumpMap;
  2744. }
  2745. if ( uvScaleMap !== undefined ) {
  2746. var offset = uvScaleMap.offset;
  2747. var repeat = uvScaleMap.repeat;
  2748. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  2749. }
  2750. uniforms.envMap.value = material.envMap;
  2751. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  2752. if ( _this.gammaInput ) {
  2753. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  2754. uniforms.reflectivity.value = material.reflectivity;
  2755. } else {
  2756. uniforms.reflectivity.value = material.reflectivity;
  2757. }
  2758. uniforms.refractionRatio.value = material.refractionRatio;
  2759. uniforms.combine.value = material.combine;
  2760. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  2761. };
  2762. function refreshUniformsLine ( uniforms, material ) {
  2763. uniforms.diffuse.value = material.color;
  2764. uniforms.opacity.value = material.opacity;
  2765. };
  2766. function refreshUniformsDash ( uniforms, material ) {
  2767. uniforms.dashSize.value = material.dashSize;
  2768. uniforms.totalSize.value = material.dashSize + material.gapSize;
  2769. uniforms.scale.value = material.scale;
  2770. };
  2771. function refreshUniformsParticle ( uniforms, material ) {
  2772. uniforms.psColor.value = material.color;
  2773. uniforms.opacity.value = material.opacity;
  2774. uniforms.size.value = material.size;
  2775. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  2776. uniforms.map.value = material.map;
  2777. };
  2778. function refreshUniformsFog ( uniforms, fog ) {
  2779. uniforms.fogColor.value = fog.color;
  2780. if ( fog instanceof THREE.Fog ) {
  2781. uniforms.fogNear.value = fog.near;
  2782. uniforms.fogFar.value = fog.far;
  2783. } else if ( fog instanceof THREE.FogExp2 ) {
  2784. uniforms.fogDensity.value = fog.density;
  2785. }
  2786. };
  2787. function refreshUniformsPhong ( uniforms, material ) {
  2788. uniforms.shininess.value = material.shininess;
  2789. if ( _this.gammaInput ) {
  2790. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  2791. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  2792. uniforms.specular.value.copyGammaToLinear( material.specular );
  2793. } else {
  2794. uniforms.ambient.value = material.ambient;
  2795. uniforms.emissive.value = material.emissive;
  2796. uniforms.specular.value = material.specular;
  2797. }
  2798. if ( material.wrapAround ) {
  2799. uniforms.wrapRGB.value.copy( material.wrapRGB );
  2800. }
  2801. };
  2802. function refreshUniformsLambert ( uniforms, material ) {
  2803. if ( _this.gammaInput ) {
  2804. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  2805. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  2806. } else {
  2807. uniforms.ambient.value = material.ambient;
  2808. uniforms.emissive.value = material.emissive;
  2809. }
  2810. if ( material.wrapAround ) {
  2811. uniforms.wrapRGB.value.copy( material.wrapRGB );
  2812. }
  2813. };
  2814. function refreshUniformsLights ( uniforms, lights ) {
  2815. uniforms.ambientLightColor.value = lights.ambient;
  2816. uniforms.directionalLightColor.value = lights.directional.colors;
  2817. uniforms.directionalLightDirection.value = lights.directional.positions;
  2818. uniforms.pointLightColor.value = lights.point.colors;
  2819. uniforms.pointLightPosition.value = lights.point.positions;
  2820. uniforms.pointLightDistance.value = lights.point.distances;
  2821. uniforms.spotLightColor.value = lights.spot.colors;
  2822. uniforms.spotLightPosition.value = lights.spot.positions;
  2823. uniforms.spotLightDistance.value = lights.spot.distances;
  2824. uniforms.spotLightDirection.value = lights.spot.directions;
  2825. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  2826. uniforms.spotLightExponent.value = lights.spot.exponents;
  2827. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  2828. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  2829. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  2830. };
  2831. function refreshUniformsShadow ( uniforms, lights ) {
  2832. if ( uniforms.shadowMatrix ) {
  2833. var j = 0;
  2834. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  2835. var light = lights[ i ];
  2836. if ( ! light.castShadow ) continue;
  2837. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  2838. uniforms.shadowMap.value[ j ] = light.shadowMap;
  2839. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  2840. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  2841. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  2842. uniforms.shadowBias.value[ j ] = light.shadowBias;
  2843. j ++;
  2844. }
  2845. }
  2846. }
  2847. };
  2848. // Uniforms (load to GPU)
  2849. function loadUniformsMatrices ( uniforms, object ) {
  2850. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  2851. if ( uniforms.normalMatrix ) {
  2852. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  2853. }
  2854. };
  2855. function getTextureUnit() {
  2856. var textureUnit = _usedTextureUnits;
  2857. if ( textureUnit >= _maxTextures ) {
  2858. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  2859. }
  2860. _usedTextureUnits += 1;
  2861. return textureUnit;
  2862. };
  2863. function loadUniformsGeneric ( program, uniforms ) {
  2864. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  2865. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  2866. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  2867. if ( !location ) continue;
  2868. uniform = uniforms[ j ][ 0 ];
  2869. type = uniform.type;
  2870. value = uniform.value;
  2871. if ( type === "i" ) { // single integer
  2872. _gl.uniform1i( location, value );
  2873. } else if ( type === "f" ) { // single float
  2874. _gl.uniform1f( location, value );
  2875. } else if ( type === "v2" ) { // single THREE.Vector2
  2876. _gl.uniform2f( location, value.x, value.y );
  2877. } else if ( type === "v3" ) { // single THREE.Vector3
  2878. _gl.uniform3f( location, value.x, value.y, value.z );
  2879. } else if ( type === "v4" ) { // single THREE.Vector4
  2880. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  2881. } else if ( type === "c" ) { // single THREE.Color
  2882. _gl.uniform3f( location, value.r, value.g, value.b );
  2883. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  2884. _gl.uniform1iv( location, value );
  2885. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  2886. _gl.uniform3iv( location, value );
  2887. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  2888. _gl.uniform1fv( location, value );
  2889. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  2890. _gl.uniform3fv( location, value );
  2891. } else if ( type === "v2v" ) { // array of THREE.Vector2
  2892. if ( uniform._array === undefined ) {
  2893. uniform._array = new Float32Array( 2 * value.length );
  2894. }
  2895. for ( i = 0, il = value.length; i < il; i ++ ) {
  2896. offset = i * 2;
  2897. uniform._array[ offset ] = value[ i ].x;
  2898. uniform._array[ offset + 1 ] = value[ i ].y;
  2899. }
  2900. _gl.uniform2fv( location, uniform._array );
  2901. } else if ( type === "v3v" ) { // array of THREE.Vector3
  2902. if ( uniform._array === undefined ) {
  2903. uniform._array = new Float32Array( 3 * value.length );
  2904. }
  2905. for ( i = 0, il = value.length; i < il; i ++ ) {
  2906. offset = i * 3;
  2907. uniform._array[ offset ] = value[ i ].x;
  2908. uniform._array[ offset + 1 ] = value[ i ].y;
  2909. uniform._array[ offset + 2 ] = value[ i ].z;
  2910. }
  2911. _gl.uniform3fv( location, uniform._array );
  2912. } else if ( type === "v4v" ) { // array of THREE.Vector4
  2913. if ( uniform._array === undefined ) {
  2914. uniform._array = new Float32Array( 4 * value.length );
  2915. }
  2916. for ( i = 0, il = value.length; i < il; i ++ ) {
  2917. offset = i * 4;
  2918. uniform._array[ offset ] = value[ i ].x;
  2919. uniform._array[ offset + 1 ] = value[ i ].y;
  2920. uniform._array[ offset + 2 ] = value[ i ].z;
  2921. uniform._array[ offset + 3 ] = value[ i ].w;
  2922. }
  2923. _gl.uniform4fv( location, uniform._array );
  2924. } else if ( type === "m4") { // single THREE.Matrix4
  2925. if ( uniform._array === undefined ) {
  2926. uniform._array = new Float32Array( 16 );
  2927. }
  2928. value.flattenToArray( uniform._array );
  2929. _gl.uniformMatrix4fv( location, false, uniform._array );
  2930. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  2931. if ( uniform._array === undefined ) {
  2932. uniform._array = new Float32Array( 16 * value.length );
  2933. }
  2934. for ( i = 0, il = value.length; i < il; i ++ ) {
  2935. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  2936. }
  2937. _gl.uniformMatrix4fv( location, false, uniform._array );
  2938. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  2939. texture = value;
  2940. textureUnit = getTextureUnit();
  2941. _gl.uniform1i( location, textureUnit );
  2942. if ( !texture ) continue;
  2943. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  2944. setCubeTexture( texture, textureUnit );
  2945. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  2946. setCubeTextureDynamic( texture, textureUnit );
  2947. } else {
  2948. _this.setTexture( texture, textureUnit );
  2949. }
  2950. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  2951. if ( uniform._array === undefined ) {
  2952. uniform._array = [];
  2953. }
  2954. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  2955. uniform._array[ i ] = getTextureUnit();
  2956. }
  2957. _gl.uniform1iv( location, uniform._array );
  2958. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  2959. texture = uniform.value[ i ];
  2960. textureUnit = uniform._array[ i ];
  2961. if ( !texture ) continue;
  2962. _this.setTexture( texture, textureUnit );
  2963. }
  2964. } else {
  2965. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  2966. }
  2967. }
  2968. };
  2969. function setupMatrices ( object, camera ) {
  2970. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  2971. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  2972. };
  2973. //
  2974. function setColorGamma( array, offset, color, intensitySq ) {
  2975. array[ offset ] = color.r * color.r * intensitySq;
  2976. array[ offset + 1 ] = color.g * color.g * intensitySq;
  2977. array[ offset + 2 ] = color.b * color.b * intensitySq;
  2978. };
  2979. function setColorLinear( array, offset, color, intensity ) {
  2980. array[ offset ] = color.r * intensity;
  2981. array[ offset + 1 ] = color.g * intensity;
  2982. array[ offset + 2 ] = color.b * intensity;
  2983. };
  2984. function setupLights ( program, lights ) {
  2985. var l, ll, light, n,
  2986. r = 0, g = 0, b = 0,
  2987. color, skyColor, groundColor,
  2988. intensity, intensitySq,
  2989. position,
  2990. distance,
  2991. zlights = _lights,
  2992. dirColors = zlights.directional.colors,
  2993. dirPositions = zlights.directional.positions,
  2994. pointColors = zlights.point.colors,
  2995. pointPositions = zlights.point.positions,
  2996. pointDistances = zlights.point.distances,
  2997. spotColors = zlights.spot.colors,
  2998. spotPositions = zlights.spot.positions,
  2999. spotDistances = zlights.spot.distances,
  3000. spotDirections = zlights.spot.directions,
  3001. spotAnglesCos = zlights.spot.anglesCos,
  3002. spotExponents = zlights.spot.exponents,
  3003. hemiSkyColors = zlights.hemi.skyColors,
  3004. hemiGroundColors = zlights.hemi.groundColors,
  3005. hemiPositions = zlights.hemi.positions,
  3006. dirLength = 0,
  3007. pointLength = 0,
  3008. spotLength = 0,
  3009. hemiLength = 0,
  3010. dirCount = 0,
  3011. pointCount = 0,
  3012. spotCount = 0,
  3013. hemiCount = 0,
  3014. dirOffset = 0,
  3015. pointOffset = 0,
  3016. spotOffset = 0,
  3017. hemiOffset = 0;
  3018. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  3019. light = lights[ l ];
  3020. if ( light.onlyShadow ) continue;
  3021. color = light.color;
  3022. intensity = light.intensity;
  3023. distance = light.distance;
  3024. if ( light instanceof THREE.AmbientLight ) {
  3025. if ( ! light.visible ) continue;
  3026. if ( _this.gammaInput ) {
  3027. r += color.r * color.r;
  3028. g += color.g * color.g;
  3029. b += color.b * color.b;
  3030. } else {
  3031. r += color.r;
  3032. g += color.g;
  3033. b += color.b;
  3034. }
  3035. } else if ( light instanceof THREE.DirectionalLight ) {
  3036. dirCount += 1;
  3037. if ( ! light.visible ) continue;
  3038. _direction.getPositionFromMatrix( light.matrixWorld );
  3039. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  3040. _direction.sub( _vector3 );
  3041. _direction.normalize();
  3042. // skip lights with undefined direction
  3043. // these create troubles in OpenGL (making pixel black)
  3044. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  3045. dirOffset = dirLength * 3;
  3046. dirPositions[ dirOffset ] = _direction.x;
  3047. dirPositions[ dirOffset + 1 ] = _direction.y;
  3048. dirPositions[ dirOffset + 2 ] = _direction.z;
  3049. if ( _this.gammaInput ) {
  3050. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  3051. } else {
  3052. setColorLinear( dirColors, dirOffset, color, intensity );
  3053. }
  3054. dirLength += 1;
  3055. } else if ( light instanceof THREE.PointLight ) {
  3056. pointCount += 1;
  3057. if ( ! light.visible ) continue;
  3058. pointOffset = pointLength * 3;
  3059. if ( _this.gammaInput ) {
  3060. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  3061. } else {
  3062. setColorLinear( pointColors, pointOffset, color, intensity );
  3063. }
  3064. _vector3.getPositionFromMatrix( light.matrixWorld );
  3065. pointPositions[ pointOffset ] = _vector3.x;
  3066. pointPositions[ pointOffset + 1 ] = _vector3.y;
  3067. pointPositions[ pointOffset + 2 ] = _vector3.z;
  3068. pointDistances[ pointLength ] = distance;
  3069. pointLength += 1;
  3070. } else if ( light instanceof THREE.SpotLight ) {
  3071. spotCount += 1;
  3072. if ( ! light.visible ) continue;
  3073. spotOffset = spotLength * 3;
  3074. if ( _this.gammaInput ) {
  3075. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  3076. } else {
  3077. setColorLinear( spotColors, spotOffset, color, intensity );
  3078. }
  3079. _vector3.getPositionFromMatrix( light.matrixWorld );
  3080. spotPositions[ spotOffset ] = _vector3.x;
  3081. spotPositions[ spotOffset + 1 ] = _vector3.y;
  3082. spotPositions[ spotOffset + 2 ] = _vector3.z;
  3083. spotDistances[ spotLength ] = distance;
  3084. _direction.copy( _vector3 );
  3085. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  3086. _direction.sub( _vector3 );
  3087. _direction.normalize();
  3088. spotDirections[ spotOffset ] = _direction.x;
  3089. spotDirections[ spotOffset + 1 ] = _direction.y;
  3090. spotDirections[ spotOffset + 2 ] = _direction.z;
  3091. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  3092. spotExponents[ spotLength ] = light.exponent;
  3093. spotLength += 1;
  3094. } else if ( light instanceof THREE.HemisphereLight ) {
  3095. hemiCount += 1;
  3096. if ( ! light.visible ) continue;
  3097. _direction.getPositionFromMatrix( light.matrixWorld );
  3098. _direction.normalize();
  3099. // skip lights with undefined direction
  3100. // these create troubles in OpenGL (making pixel black)
  3101. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  3102. hemiOffset = hemiLength * 3;
  3103. hemiPositions[ hemiOffset ] = _direction.x;
  3104. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  3105. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  3106. skyColor = light.color;
  3107. groundColor = light.groundColor;
  3108. if ( _this.gammaInput ) {
  3109. intensitySq = intensity * intensity;
  3110. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  3111. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  3112. } else {
  3113. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  3114. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  3115. }
  3116. hemiLength += 1;
  3117. }
  3118. }
  3119. // null eventual remains from removed lights
  3120. // (this is to avoid if in shader)
  3121. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  3122. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  3123. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  3124. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  3125. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  3126. zlights.directional.length = dirLength;
  3127. zlights.point.length = pointLength;
  3128. zlights.spot.length = spotLength;
  3129. zlights.hemi.length = hemiLength;
  3130. zlights.ambient[ 0 ] = r;
  3131. zlights.ambient[ 1 ] = g;
  3132. zlights.ambient[ 2 ] = b;
  3133. };
  3134. // GL state setting
  3135. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  3136. if ( cullFace === THREE.CullFaceNone ) {
  3137. _gl.disable( _gl.CULL_FACE );
  3138. } else {
  3139. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  3140. _gl.frontFace( _gl.CW );
  3141. } else {
  3142. _gl.frontFace( _gl.CCW );
  3143. }
  3144. if ( cullFace === THREE.CullFaceBack ) {
  3145. _gl.cullFace( _gl.BACK );
  3146. } else if ( cullFace === THREE.CullFaceFront ) {
  3147. _gl.cullFace( _gl.FRONT );
  3148. } else {
  3149. _gl.cullFace( _gl.FRONT_AND_BACK );
  3150. }
  3151. _gl.enable( _gl.CULL_FACE );
  3152. }
  3153. };
  3154. this.setMaterialFaces = function ( material ) {
  3155. var doubleSided = material.side === THREE.DoubleSide;
  3156. var flipSided = material.side === THREE.BackSide;
  3157. if ( _oldDoubleSided !== doubleSided ) {
  3158. if ( doubleSided ) {
  3159. _gl.disable( _gl.CULL_FACE );
  3160. } else {
  3161. _gl.enable( _gl.CULL_FACE );
  3162. }
  3163. _oldDoubleSided = doubleSided;
  3164. }
  3165. if ( _oldFlipSided !== flipSided ) {
  3166. if ( flipSided ) {
  3167. _gl.frontFace( _gl.CW );
  3168. } else {
  3169. _gl.frontFace( _gl.CCW );
  3170. }
  3171. _oldFlipSided = flipSided;
  3172. }
  3173. };
  3174. this.setDepthTest = function ( depthTest ) {
  3175. if ( _oldDepthTest !== depthTest ) {
  3176. if ( depthTest ) {
  3177. _gl.enable( _gl.DEPTH_TEST );
  3178. } else {
  3179. _gl.disable( _gl.DEPTH_TEST );
  3180. }
  3181. _oldDepthTest = depthTest;
  3182. }
  3183. };
  3184. this.setDepthWrite = function ( depthWrite ) {
  3185. if ( _oldDepthWrite !== depthWrite ) {
  3186. _gl.depthMask( depthWrite );
  3187. _oldDepthWrite = depthWrite;
  3188. }
  3189. };
  3190. function setLineWidth ( width ) {
  3191. if ( width !== _oldLineWidth ) {
  3192. _gl.lineWidth( width );
  3193. _oldLineWidth = width;
  3194. }
  3195. };
  3196. function setPolygonOffset ( polygonoffset, factor, units ) {
  3197. if ( _oldPolygonOffset !== polygonoffset ) {
  3198. if ( polygonoffset ) {
  3199. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  3200. } else {
  3201. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  3202. }
  3203. _oldPolygonOffset = polygonoffset;
  3204. }
  3205. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  3206. _gl.polygonOffset( factor, units );
  3207. _oldPolygonOffsetFactor = factor;
  3208. _oldPolygonOffsetUnits = units;
  3209. }
  3210. };
  3211. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  3212. if ( blending !== _oldBlending ) {
  3213. if ( blending === THREE.NoBlending ) {
  3214. _gl.disable( _gl.BLEND );
  3215. } else if ( blending === THREE.AdditiveBlending ) {
  3216. _gl.enable( _gl.BLEND );
  3217. _gl.blendEquation( _gl.FUNC_ADD );
  3218. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  3219. } else if ( blending === THREE.SubtractiveBlending ) {
  3220. // TODO: Find blendFuncSeparate() combination
  3221. _gl.enable( _gl.BLEND );
  3222. _gl.blendEquation( _gl.FUNC_ADD );
  3223. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  3224. } else if ( blending === THREE.MultiplyBlending ) {
  3225. // TODO: Find blendFuncSeparate() combination
  3226. _gl.enable( _gl.BLEND );
  3227. _gl.blendEquation( _gl.FUNC_ADD );
  3228. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  3229. } else if ( blending === THREE.CustomBlending ) {
  3230. _gl.enable( _gl.BLEND );
  3231. } else {
  3232. _gl.enable( _gl.BLEND );
  3233. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  3234. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  3235. }
  3236. _oldBlending = blending;
  3237. }
  3238. if ( blending === THREE.CustomBlending ) {
  3239. if ( blendEquation !== _oldBlendEquation ) {
  3240. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  3241. _oldBlendEquation = blendEquation;
  3242. }
  3243. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  3244. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  3245. _oldBlendSrc = blendSrc;
  3246. _oldBlendDst = blendDst;
  3247. }
  3248. } else {
  3249. _oldBlendEquation = null;
  3250. _oldBlendSrc = null;
  3251. _oldBlendDst = null;
  3252. }
  3253. };
  3254. // Defines
  3255. function generateDefines ( defines ) {
  3256. var value, chunk, chunks = [];
  3257. for ( var d in defines ) {
  3258. value = defines[ d ];
  3259. if ( value === false ) continue;
  3260. chunk = "#define " + d + " " + value;
  3261. chunks.push( chunk );
  3262. }
  3263. return chunks.join( "\n" );
  3264. };
  3265. // Shaders
  3266. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  3267. var p, pl, d, program, code;
  3268. var chunks = [];
  3269. // Generate code
  3270. if ( shaderID ) {
  3271. chunks.push( shaderID );
  3272. } else {
  3273. chunks.push( fragmentShader );
  3274. chunks.push( vertexShader );
  3275. }
  3276. for ( d in defines ) {
  3277. chunks.push( d );
  3278. chunks.push( defines[ d ] );
  3279. }
  3280. for ( p in parameters ) {
  3281. chunks.push( p );
  3282. chunks.push( parameters[ p ] );
  3283. }
  3284. code = chunks.join();
  3285. // Check if code has been already compiled
  3286. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  3287. var programInfo = _programs[ p ];
  3288. if ( programInfo.code === code ) {
  3289. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  3290. programInfo.usedTimes ++;
  3291. return programInfo.program;
  3292. }
  3293. }
  3294. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  3295. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  3296. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  3297. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  3298. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  3299. }
  3300. // console.log( "building new program " );
  3301. //
  3302. var customDefines = generateDefines( defines );
  3303. //
  3304. program = _gl.createProgram();
  3305. var prefix_vertex = [
  3306. "precision " + _precision + " float;",
  3307. "precision " + _precision + " int;",
  3308. customDefines,
  3309. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  3310. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  3311. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  3312. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  3313. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  3314. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  3315. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  3316. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  3317. "#define MAX_SHADOWS " + parameters.maxShadows,
  3318. "#define MAX_BONES " + parameters.maxBones,
  3319. parameters.map ? "#define USE_MAP" : "",
  3320. parameters.envMap ? "#define USE_ENVMAP" : "",
  3321. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  3322. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  3323. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  3324. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  3325. parameters.vertexColors ? "#define USE_COLOR" : "",
  3326. parameters.skinning ? "#define USE_SKINNING" : "",
  3327. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  3328. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  3329. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  3330. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  3331. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  3332. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  3333. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  3334. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  3335. parameters.flipSided ? "#define FLIP_SIDED" : "",
  3336. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  3337. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  3338. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  3339. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  3340. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  3341. "uniform mat4 modelMatrix;",
  3342. "uniform mat4 modelViewMatrix;",
  3343. "uniform mat4 projectionMatrix;",
  3344. "uniform mat4 viewMatrix;",
  3345. "uniform mat3 normalMatrix;",
  3346. "uniform vec3 cameraPosition;",
  3347. "attribute vec3 position;",
  3348. "attribute vec3 normal;",
  3349. "attribute vec2 uv;",
  3350. "attribute vec2 uv2;",
  3351. "#ifdef USE_COLOR",
  3352. "attribute vec3 color;",
  3353. "#endif",
  3354. "#ifdef USE_MORPHTARGETS",
  3355. "attribute vec3 morphTarget0;",
  3356. "attribute vec3 morphTarget1;",
  3357. "attribute vec3 morphTarget2;",
  3358. "attribute vec3 morphTarget3;",
  3359. "#ifdef USE_MORPHNORMALS",
  3360. "attribute vec3 morphNormal0;",
  3361. "attribute vec3 morphNormal1;",
  3362. "attribute vec3 morphNormal2;",
  3363. "attribute vec3 morphNormal3;",
  3364. "#else",
  3365. "attribute vec3 morphTarget4;",
  3366. "attribute vec3 morphTarget5;",
  3367. "attribute vec3 morphTarget6;",
  3368. "attribute vec3 morphTarget7;",
  3369. "#endif",
  3370. "#endif",
  3371. "#ifdef USE_SKINNING",
  3372. "attribute vec4 skinIndex;",
  3373. "attribute vec4 skinWeight;",
  3374. "#endif",
  3375. ""
  3376. ].join("\n");
  3377. var prefix_fragment = [
  3378. "precision " + _precision + " float;",
  3379. "precision " + _precision + " int;",
  3380. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  3381. customDefines,
  3382. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  3383. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  3384. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  3385. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  3386. "#define MAX_SHADOWS " + parameters.maxShadows,
  3387. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  3388. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  3389. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  3390. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  3391. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  3392. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  3393. parameters.map ? "#define USE_MAP" : "",
  3394. parameters.envMap ? "#define USE_ENVMAP" : "",
  3395. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  3396. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  3397. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  3398. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  3399. parameters.vertexColors ? "#define USE_COLOR" : "",
  3400. parameters.metal ? "#define METAL" : "",
  3401. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  3402. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  3403. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  3404. parameters.flipSided ? "#define FLIP_SIDED" : "",
  3405. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  3406. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  3407. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  3408. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  3409. "uniform mat4 viewMatrix;",
  3410. "uniform vec3 cameraPosition;",
  3411. ""
  3412. ].join("\n");
  3413. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  3414. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  3415. _gl.attachShader( program, glVertexShader );
  3416. _gl.attachShader( program, glFragmentShader );
  3417. //Force a particular attribute to index 0.
  3418. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  3419. //And, color, for example is often automatically bound to index 0 so disabling it
  3420. if ( index0AttributeName ) {
  3421. _gl.bindAttribLocation( program, 0, index0AttributeName );
  3422. }
  3423. _gl.linkProgram( program );
  3424. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  3425. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  3426. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  3427. }
  3428. // clean up
  3429. _gl.deleteShader( glFragmentShader );
  3430. _gl.deleteShader( glVertexShader );
  3431. // console.log( prefix_fragment + fragmentShader );
  3432. // console.log( prefix_vertex + vertexShader );
  3433. program.uniforms = {};
  3434. program.attributes = {};
  3435. var identifiers, u, a, i;
  3436. // cache uniform locations
  3437. identifiers = [
  3438. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  3439. 'morphTargetInfluences'
  3440. ];
  3441. if ( parameters.useVertexTexture ) {
  3442. identifiers.push( 'boneTexture' );
  3443. } else {
  3444. identifiers.push( 'boneGlobalMatrices' );
  3445. }
  3446. for ( u in uniforms ) {
  3447. identifiers.push( u );
  3448. }
  3449. cacheUniformLocations( program, identifiers );
  3450. // cache attributes locations
  3451. identifiers = [
  3452. "position", "normal", "uv", "uv2", "tangent", "color",
  3453. "skinIndex", "skinWeight", "lineDistance"
  3454. ];
  3455. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  3456. identifiers.push( "morphTarget" + i );
  3457. }
  3458. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  3459. identifiers.push( "morphNormal" + i );
  3460. }
  3461. for ( a in attributes ) {
  3462. identifiers.push( a );
  3463. }
  3464. cacheAttributeLocations( program, identifiers );
  3465. program.id = _programs_counter ++;
  3466. _programs.push( { program: program, code: code, usedTimes: 1 } );
  3467. _this.info.memory.programs = _programs.length;
  3468. return program;
  3469. };
  3470. // Shader parameters cache
  3471. function cacheUniformLocations ( program, identifiers ) {
  3472. var i, l, id;
  3473. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  3474. id = identifiers[ i ];
  3475. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  3476. }
  3477. };
  3478. function cacheAttributeLocations ( program, identifiers ) {
  3479. var i, l, id;
  3480. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  3481. id = identifiers[ i ];
  3482. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  3483. }
  3484. };
  3485. function addLineNumbers ( string ) {
  3486. var chunks = string.split( "\n" );
  3487. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  3488. // Chrome reports shader errors on lines
  3489. // starting counting from 1
  3490. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  3491. }
  3492. return chunks.join( "\n" );
  3493. };
  3494. function getShader ( type, string ) {
  3495. var shader;
  3496. if ( type === "fragment" ) {
  3497. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  3498. } else if ( type === "vertex" ) {
  3499. shader = _gl.createShader( _gl.VERTEX_SHADER );
  3500. }
  3501. _gl.shaderSource( shader, string );
  3502. _gl.compileShader( shader );
  3503. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  3504. console.error( _gl.getShaderInfoLog( shader ) );
  3505. console.error( addLineNumbers( string ) );
  3506. return null;
  3507. }
  3508. return shader;
  3509. };
  3510. // Textures
  3511. function isPowerOfTwo ( value ) {
  3512. return ( value & ( value - 1 ) ) === 0;
  3513. };
  3514. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  3515. if ( isImagePowerOfTwo ) {
  3516. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  3517. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  3518. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  3519. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  3520. } else {
  3521. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  3522. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  3523. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  3524. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  3525. }
  3526. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  3527. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  3528. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  3529. texture.__oldAnisotropy = texture.anisotropy;
  3530. }
  3531. }
  3532. };
  3533. this.setTexture = function ( texture, slot ) {
  3534. if ( texture.needsUpdate ) {
  3535. if ( ! texture.__webglInit ) {
  3536. texture.__webglInit = true;
  3537. texture.addEventListener( 'dispose', onTextureDispose );
  3538. texture.__webglTexture = _gl.createTexture();
  3539. _this.info.memory.textures ++;
  3540. }
  3541. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3542. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  3543. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3544. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  3545. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  3546. var image = texture.image,
  3547. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  3548. glFormat = paramThreeToGL( texture.format ),
  3549. glType = paramThreeToGL( texture.type );
  3550. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  3551. var mipmap, mipmaps = texture.mipmaps;
  3552. if ( texture instanceof THREE.DataTexture ) {
  3553. // use manually created mipmaps if available
  3554. // if there are no manual mipmaps
  3555. // set 0 level mipmap and then use GL to generate other mipmap levels
  3556. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  3557. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3558. mipmap = mipmaps[ i ];
  3559. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3560. }
  3561. texture.generateMipmaps = false;
  3562. } else {
  3563. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  3564. }
  3565. } else if ( texture instanceof THREE.CompressedTexture ) {
  3566. // compressed textures can only use manually created mipmaps
  3567. // WebGL can't generate mipmaps for DDS textures
  3568. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3569. mipmap = mipmaps[ i ];
  3570. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3571. }
  3572. } else { // regular Texture (image, video, canvas)
  3573. // use manually created mipmaps if available
  3574. // if there are no manual mipmaps
  3575. // set 0 level mipmap and then use GL to generate other mipmap levels
  3576. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  3577. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3578. mipmap = mipmaps[ i ];
  3579. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  3580. }
  3581. texture.generateMipmaps = false;
  3582. } else {
  3583. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  3584. }
  3585. }
  3586. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3587. texture.needsUpdate = false;
  3588. if ( texture.onUpdate ) texture.onUpdate();
  3589. } else {
  3590. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3591. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  3592. }
  3593. };
  3594. function clampToMaxSize ( image, maxSize ) {
  3595. if ( image.width <= maxSize && image.height <= maxSize ) {
  3596. return image;
  3597. }
  3598. // Warning: Scaling through the canvas will only work with images that use
  3599. // premultiplied alpha.
  3600. var maxDimension = Math.max( image.width, image.height );
  3601. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  3602. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  3603. var canvas = document.createElement( 'canvas' );
  3604. canvas.width = newWidth;
  3605. canvas.height = newHeight;
  3606. var ctx = canvas.getContext( "2d" );
  3607. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  3608. return canvas;
  3609. }
  3610. function setCubeTexture ( texture, slot ) {
  3611. if ( texture.image.length === 6 ) {
  3612. if ( texture.needsUpdate ) {
  3613. if ( ! texture.image.__webglTextureCube ) {
  3614. texture.addEventListener( 'dispose', onTextureDispose );
  3615. texture.image.__webglTextureCube = _gl.createTexture();
  3616. _this.info.memory.textures ++;
  3617. }
  3618. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3619. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  3620. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3621. var isCompressed = texture instanceof THREE.CompressedTexture;
  3622. var cubeImage = [];
  3623. for ( var i = 0; i < 6; i ++ ) {
  3624. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  3625. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  3626. } else {
  3627. cubeImage[ i ] = texture.image[ i ];
  3628. }
  3629. }
  3630. var image = cubeImage[ 0 ],
  3631. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  3632. glFormat = paramThreeToGL( texture.format ),
  3633. glType = paramThreeToGL( texture.type );
  3634. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  3635. for ( var i = 0; i < 6; i ++ ) {
  3636. if ( isCompressed ) {
  3637. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  3638. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  3639. mipmap = mipmaps[ j ];
  3640. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3641. }
  3642. } else {
  3643. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  3644. }
  3645. }
  3646. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  3647. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3648. }
  3649. texture.needsUpdate = false;
  3650. if ( texture.onUpdate ) texture.onUpdate();
  3651. } else {
  3652. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3653. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  3654. }
  3655. }
  3656. };
  3657. function setCubeTextureDynamic ( texture, slot ) {
  3658. _gl.activeTexture( _gl.TEXTURE0 + slot );
  3659. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  3660. };
  3661. // Render targets
  3662. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  3663. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3664. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  3665. };
  3666. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  3667. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  3668. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3669. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  3670. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3671. /* For some reason this is not working. Defaulting to RGBA4.
  3672. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3673. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  3674. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3675. */
  3676. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3677. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  3678. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3679. } else {
  3680. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  3681. }
  3682. };
  3683. this.setRenderTarget = function ( renderTarget ) {
  3684. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  3685. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  3686. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  3687. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  3688. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  3689. renderTarget.__webglTexture = _gl.createTexture();
  3690. _this.info.memory.textures ++;
  3691. // Setup texture, create render and frame buffers
  3692. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  3693. glFormat = paramThreeToGL( renderTarget.format ),
  3694. glType = paramThreeToGL( renderTarget.type );
  3695. if ( isCube ) {
  3696. renderTarget.__webglFramebuffer = [];
  3697. renderTarget.__webglRenderbuffer = [];
  3698. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  3699. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  3700. for ( var i = 0; i < 6; i ++ ) {
  3701. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  3702. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  3703. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3704. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  3705. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  3706. }
  3707. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3708. } else {
  3709. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  3710. if ( renderTarget.shareDepthFrom ) {
  3711. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  3712. } else {
  3713. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  3714. }
  3715. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  3716. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  3717. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3718. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  3719. if ( renderTarget.shareDepthFrom ) {
  3720. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3721. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  3722. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3723. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  3724. }
  3725. } else {
  3726. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  3727. }
  3728. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3729. }
  3730. // Release everything
  3731. if ( isCube ) {
  3732. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3733. } else {
  3734. _gl.bindTexture( _gl.TEXTURE_2D, null );
  3735. }
  3736. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  3737. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  3738. }
  3739. var framebuffer, width, height, vx, vy;
  3740. if ( renderTarget ) {
  3741. if ( isCube ) {
  3742. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  3743. } else {
  3744. framebuffer = renderTarget.__webglFramebuffer;
  3745. }
  3746. width = renderTarget.width;
  3747. height = renderTarget.height;
  3748. vx = 0;
  3749. vy = 0;
  3750. } else {
  3751. framebuffer = null;
  3752. width = _viewportWidth;
  3753. height = _viewportHeight;
  3754. vx = _viewportX;
  3755. vy = _viewportY;
  3756. }
  3757. if ( framebuffer !== _currentFramebuffer ) {
  3758. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3759. _gl.viewport( vx, vy, width, height );
  3760. _currentFramebuffer = framebuffer;
  3761. }
  3762. _currentWidth = width;
  3763. _currentHeight = height;
  3764. };
  3765. function updateRenderTargetMipmap ( renderTarget ) {
  3766. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  3767. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  3768. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3769. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3770. } else {
  3771. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  3772. _gl.generateMipmap( _gl.TEXTURE_2D );
  3773. _gl.bindTexture( _gl.TEXTURE_2D, null );
  3774. }
  3775. };
  3776. // Fallback filters for non-power-of-2 textures
  3777. function filterFallback ( f ) {
  3778. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  3779. return _gl.NEAREST;
  3780. }
  3781. return _gl.LINEAR;
  3782. };
  3783. // Map three.js constants to WebGL constants
  3784. function paramThreeToGL ( p ) {
  3785. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  3786. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  3787. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  3788. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  3789. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  3790. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  3791. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  3792. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  3793. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  3794. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  3795. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  3796. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  3797. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  3798. if ( p === THREE.ByteType ) return _gl.BYTE;
  3799. if ( p === THREE.ShortType ) return _gl.SHORT;
  3800. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  3801. if ( p === THREE.IntType ) return _gl.INT;
  3802. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  3803. if ( p === THREE.FloatType ) return _gl.FLOAT;
  3804. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  3805. if ( p === THREE.RGBFormat ) return _gl.RGB;
  3806. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  3807. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  3808. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  3809. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  3810. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  3811. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  3812. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  3813. if ( p === THREE.OneFactor ) return _gl.ONE;
  3814. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  3815. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  3816. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  3817. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  3818. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  3819. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  3820. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  3821. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  3822. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  3823. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  3824. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  3825. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3826. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3827. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3828. }
  3829. return 0;
  3830. };
  3831. // Allocations
  3832. function allocateBones ( object ) {
  3833. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  3834. return 1024;
  3835. } else {
  3836. // default for when object is not specified
  3837. // ( for example when prebuilding shader
  3838. // to be used with multiple objects )
  3839. //
  3840. // - leave some extra space for other uniforms
  3841. // - limit here is ANGLE's 254 max uniform vectors
  3842. // (up to 54 should be safe)
  3843. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  3844. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  3845. var maxBones = nVertexMatrices;
  3846. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  3847. maxBones = Math.min( object.bones.length, maxBones );
  3848. if ( maxBones < object.bones.length ) {
  3849. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  3850. }
  3851. }
  3852. return maxBones;
  3853. }
  3854. };
  3855. function allocateLights( lights ) {
  3856. var dirLights = 0;
  3857. var pointLights = 0;
  3858. var spotLights = 0;
  3859. var hemiLights = 0;
  3860. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  3861. var light = lights[ l ];
  3862. if ( light.onlyShadow ) continue;
  3863. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  3864. if ( light instanceof THREE.PointLight ) pointLights ++;
  3865. if ( light instanceof THREE.SpotLight ) spotLights ++;
  3866. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  3867. }
  3868. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  3869. };
  3870. function allocateShadows( lights ) {
  3871. var maxShadows = 0;
  3872. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  3873. var light = lights[ l ];
  3874. if ( ! light.castShadow ) continue;
  3875. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  3876. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  3877. }
  3878. return maxShadows;
  3879. };
  3880. // Initialization
  3881. function initGL() {
  3882. try {
  3883. var attributes = {
  3884. alpha: _alpha,
  3885. premultipliedAlpha: _premultipliedAlpha,
  3886. antialias: _antialias,
  3887. stencil: _stencil,
  3888. preserveDrawingBuffer: _preserveDrawingBuffer
  3889. };
  3890. _gl = _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  3891. if ( _gl === null ) {
  3892. throw 'Error creating WebGL context.';
  3893. }
  3894. } catch ( error ) {
  3895. console.error( error );
  3896. }
  3897. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  3898. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  3899. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  3900. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  3901. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  3902. if ( ! _glExtensionTextureFloat ) {
  3903. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  3904. }
  3905. if ( ! _glExtensionStandardDerivatives ) {
  3906. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  3907. }
  3908. if ( ! _glExtensionTextureFilterAnisotropic ) {
  3909. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  3910. }
  3911. if ( ! _glExtensionCompressedTextureS3TC ) {
  3912. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  3913. }
  3914. if ( _gl.getShaderPrecisionFormat === undefined ) {
  3915. _gl.getShaderPrecisionFormat = function() {
  3916. return {
  3917. "rangeMin" : 1,
  3918. "rangeMax" : 1,
  3919. "precision" : 1
  3920. };
  3921. }
  3922. }
  3923. };
  3924. function setDefaultGLState () {
  3925. _gl.clearColor( 0, 0, 0, 1 );
  3926. _gl.clearDepth( 1 );
  3927. _gl.clearStencil( 0 );
  3928. _gl.enable( _gl.DEPTH_TEST );
  3929. _gl.depthFunc( _gl.LEQUAL );
  3930. _gl.frontFace( _gl.CCW );
  3931. _gl.cullFace( _gl.BACK );
  3932. _gl.enable( _gl.CULL_FACE );
  3933. _gl.enable( _gl.BLEND );
  3934. _gl.blendEquation( _gl.FUNC_ADD );
  3935. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  3936. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  3937. };
  3938. // default plugins (order is important)
  3939. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  3940. this.addPrePlugin( this.shadowMapPlugin );
  3941. this.addPostPlugin( new THREE.SpritePlugin() );
  3942. this.addPostPlugin( new THREE.LensFlarePlugin() );
  3943. };
粤ICP备19079148号