babylon.max.js 2.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = function (otherColor, result) {
  120. result.r = this.r - otherColor.r;
  121. result.g = this.g - otherColor.g;
  122. result.b = this.b - otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. })();
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. })();
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var r = Vector2.Zero();
  499. Vector2.TransformToRef(vector, transformation, r);
  500. return r;
  501. };
  502. Vector2.TransformToRef = function (vector, transformation, result) {
  503. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  504. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  505. result.x = x;
  506. result.y = y;
  507. };
  508. Vector2.Distance = function (value1, value2) {
  509. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  510. };
  511. Vector2.DistanceSquared = function (value1, value2) {
  512. var x = value1.x - value2.x;
  513. var y = value1.y - value2.y;
  514. return (x * x) + (y * y);
  515. };
  516. return Vector2;
  517. })();
  518. BABYLON.Vector2 = Vector2;
  519. var Vector3 = (function () {
  520. function Vector3(x, y, z) {
  521. this.x = x;
  522. this.y = y;
  523. this.z = z;
  524. }
  525. Vector3.prototype.toString = function () {
  526. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  527. };
  528. // Operators
  529. Vector3.prototype.asArray = function () {
  530. var result = [];
  531. this.toArray(result, 0);
  532. return result;
  533. };
  534. Vector3.prototype.toArray = function (array, index) {
  535. if (index === void 0) { index = 0; }
  536. array[index] = this.x;
  537. array[index + 1] = this.y;
  538. array[index + 2] = this.z;
  539. return this;
  540. };
  541. Vector3.prototype.toQuaternion = function () {
  542. var result = new Quaternion(0, 0, 0, 1);
  543. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  544. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  545. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  546. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  547. var cosy = Math.cos(this.y * 0.5);
  548. var siny = Math.sin(this.y * 0.5);
  549. result.x = coszMinusx * siny;
  550. result.y = -sinzMinusx * siny;
  551. result.z = sinxPlusz * cosy;
  552. result.w = cosxPlusz * cosy;
  553. return result;
  554. };
  555. Vector3.prototype.addInPlace = function (otherVector) {
  556. this.x += otherVector.x;
  557. this.y += otherVector.y;
  558. this.z += otherVector.z;
  559. return this;
  560. };
  561. Vector3.prototype.add = function (otherVector) {
  562. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  563. };
  564. Vector3.prototype.addToRef = function (otherVector, result) {
  565. result.x = this.x + otherVector.x;
  566. result.y = this.y + otherVector.y;
  567. result.z = this.z + otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtractInPlace = function (otherVector) {
  571. this.x -= otherVector.x;
  572. this.y -= otherVector.y;
  573. this.z -= otherVector.z;
  574. return this;
  575. };
  576. Vector3.prototype.subtract = function (otherVector) {
  577. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  578. };
  579. Vector3.prototype.subtractToRef = function (otherVector, result) {
  580. result.x = this.x - otherVector.x;
  581. result.y = this.y - otherVector.y;
  582. result.z = this.z - otherVector.z;
  583. return this;
  584. };
  585. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  586. return new Vector3(this.x - x, this.y - y, this.z - z);
  587. };
  588. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  589. result.x = this.x - x;
  590. result.y = this.y - y;
  591. result.z = this.z - z;
  592. return this;
  593. };
  594. Vector3.prototype.negate = function () {
  595. return new Vector3(-this.x, -this.y, -this.z);
  596. };
  597. Vector3.prototype.scaleInPlace = function (scale) {
  598. this.x *= scale;
  599. this.y *= scale;
  600. this.z *= scale;
  601. return this;
  602. };
  603. Vector3.prototype.scale = function (scale) {
  604. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  605. };
  606. Vector3.prototype.scaleToRef = function (scale, result) {
  607. result.x = this.x * scale;
  608. result.y = this.y * scale;
  609. result.z = this.z * scale;
  610. };
  611. Vector3.prototype.equals = function (otherVector) {
  612. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  613. };
  614. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  615. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  616. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  617. };
  618. Vector3.prototype.equalsToFloats = function (x, y, z) {
  619. return this.x === x && this.y === y && this.z === z;
  620. };
  621. Vector3.prototype.multiplyInPlace = function (otherVector) {
  622. this.x *= otherVector.x;
  623. this.y *= otherVector.y;
  624. this.z *= otherVector.z;
  625. return this;
  626. };
  627. Vector3.prototype.multiply = function (otherVector) {
  628. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  629. };
  630. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  631. result.x = this.x * otherVector.x;
  632. result.y = this.y * otherVector.y;
  633. result.z = this.z * otherVector.z;
  634. return this;
  635. };
  636. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  637. return new Vector3(this.x * x, this.y * y, this.z * z);
  638. };
  639. Vector3.prototype.divide = function (otherVector) {
  640. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  641. };
  642. Vector3.prototype.divideToRef = function (otherVector, result) {
  643. result.x = this.x / otherVector.x;
  644. result.y = this.y / otherVector.y;
  645. result.z = this.z / otherVector.z;
  646. return this;
  647. };
  648. Vector3.prototype.MinimizeInPlace = function (other) {
  649. if (other.x < this.x)
  650. this.x = other.x;
  651. if (other.y < this.y)
  652. this.y = other.y;
  653. if (other.z < this.z)
  654. this.z = other.z;
  655. return this;
  656. };
  657. Vector3.prototype.MaximizeInPlace = function (other) {
  658. if (other.x > this.x)
  659. this.x = other.x;
  660. if (other.y > this.y)
  661. this.y = other.y;
  662. if (other.z > this.z)
  663. this.z = other.z;
  664. return this;
  665. };
  666. // Properties
  667. Vector3.prototype.length = function () {
  668. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  669. };
  670. Vector3.prototype.lengthSquared = function () {
  671. return (this.x * this.x + this.y * this.y + this.z * this.z);
  672. };
  673. // Methods
  674. Vector3.prototype.normalize = function () {
  675. var len = this.length();
  676. if (len === 0 || len === 1.0)
  677. return this;
  678. var num = 1.0 / len;
  679. this.x *= num;
  680. this.y *= num;
  681. this.z *= num;
  682. return this;
  683. };
  684. Vector3.prototype.clone = function () {
  685. return new Vector3(this.x, this.y, this.z);
  686. };
  687. Vector3.prototype.copyFrom = function (source) {
  688. this.x = source.x;
  689. this.y = source.y;
  690. this.z = source.z;
  691. return this;
  692. };
  693. Vector3.prototype.copyFromFloats = function (x, y, z) {
  694. this.x = x;
  695. this.y = y;
  696. this.z = z;
  697. return this;
  698. };
  699. // Statics
  700. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  701. var d0 = Vector3.Dot(vector0, axis) - size;
  702. var d1 = Vector3.Dot(vector1, axis) - size;
  703. var s = d0 / (d0 - d1);
  704. return s;
  705. };
  706. Vector3.FromArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromFloatArray = function (array, offset) {
  713. if (!offset) {
  714. offset = 0;
  715. }
  716. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  717. };
  718. Vector3.FromArrayToRef = function (array, offset, result) {
  719. result.x = array[offset];
  720. result.y = array[offset + 1];
  721. result.z = array[offset + 2];
  722. };
  723. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  724. result.x = array[offset];
  725. result.y = array[offset + 1];
  726. result.z = array[offset + 2];
  727. };
  728. Vector3.FromFloatsToRef = function (x, y, z, result) {
  729. result.x = x;
  730. result.y = y;
  731. result.z = z;
  732. };
  733. Vector3.Zero = function () {
  734. return new Vector3(0, 0, 0);
  735. };
  736. Vector3.Up = function () {
  737. return new Vector3(0, 1.0, 0);
  738. };
  739. Vector3.TransformCoordinates = function (vector, transformation) {
  740. var result = Vector3.Zero();
  741. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  742. return result;
  743. };
  744. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  745. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  746. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  747. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  748. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  749. result.x = x / w;
  750. result.y = y / w;
  751. result.z = z / w;
  752. };
  753. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  754. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  755. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  756. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  757. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  758. result.x = rx / rw;
  759. result.y = ry / rw;
  760. result.z = rz / rw;
  761. };
  762. Vector3.TransformNormal = function (vector, transformation) {
  763. var result = Vector3.Zero();
  764. Vector3.TransformNormalToRef(vector, transformation, result);
  765. return result;
  766. };
  767. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  768. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  769. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  770. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  771. };
  772. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  773. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  774. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  775. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  776. };
  777. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  778. var squared = amount * amount;
  779. var cubed = amount * squared;
  780. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  781. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  782. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  783. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  784. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  785. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  786. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  787. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  788. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  789. return new Vector3(x, y, z);
  790. };
  791. Vector3.Clamp = function (value, min, max) {
  792. var x = value.x;
  793. x = (x > max.x) ? max.x : x;
  794. x = (x < min.x) ? min.x : x;
  795. var y = value.y;
  796. y = (y > max.y) ? max.y : y;
  797. y = (y < min.y) ? min.y : y;
  798. var z = value.z;
  799. z = (z > max.z) ? max.z : z;
  800. z = (z < min.z) ? min.z : z;
  801. return new Vector3(x, y, z);
  802. };
  803. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  804. var squared = amount * amount;
  805. var cubed = amount * squared;
  806. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  807. var part2 = (-2.0 * cubed) + (3.0 * squared);
  808. var part3 = (cubed - (2.0 * squared)) + amount;
  809. var part4 = cubed - squared;
  810. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  811. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  812. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Lerp = function (start, end, amount) {
  816. var x = start.x + ((end.x - start.x) * amount);
  817. var y = start.y + ((end.y - start.y) * amount);
  818. var z = start.z + ((end.z - start.z) * amount);
  819. return new Vector3(x, y, z);
  820. };
  821. Vector3.Dot = function (left, right) {
  822. return (left.x * right.x + left.y * right.y + left.z * right.z);
  823. };
  824. Vector3.Cross = function (left, right) {
  825. var result = Vector3.Zero();
  826. Vector3.CrossToRef(left, right, result);
  827. return result;
  828. };
  829. Vector3.CrossToRef = function (left, right, result) {
  830. result.x = left.y * right.z - left.z * right.y;
  831. result.y = left.z * right.x - left.x * right.z;
  832. result.z = left.x * right.y - left.y * right.x;
  833. };
  834. Vector3.Normalize = function (vector) {
  835. var result = Vector3.Zero();
  836. Vector3.NormalizeToRef(vector, result);
  837. return result;
  838. };
  839. Vector3.NormalizeToRef = function (vector, result) {
  840. result.copyFrom(vector);
  841. result.normalize();
  842. };
  843. Vector3.Project = function (vector, world, transform, viewport) {
  844. var cw = viewport.width;
  845. var ch = viewport.height;
  846. var cx = viewport.x;
  847. var cy = viewport.y;
  848. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  849. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  850. return Vector3.TransformCoordinates(vector, finalMatrix);
  851. };
  852. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  853. var matrix = world.multiply(transform);
  854. matrix.invert();
  855. source.x = source.x / viewportWidth * 2 - 1;
  856. source.y = -(source.y / viewportHeight * 2 - 1);
  857. var vector = Vector3.TransformCoordinates(source, matrix);
  858. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  859. if (MathTools.WithinEpsilon(num, 1.0)) {
  860. vector = vector.scale(1.0 / num);
  861. }
  862. return vector;
  863. };
  864. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  865. var matrix = world.multiply(view).multiply(projection);
  866. matrix.invert();
  867. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  868. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  869. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  870. if (MathTools.WithinEpsilon(num, 1.0)) {
  871. vector = vector.scale(1.0 / num);
  872. }
  873. return vector;
  874. };
  875. Vector3.Minimize = function (left, right) {
  876. var min = left.clone();
  877. min.MinimizeInPlace(right);
  878. return min;
  879. };
  880. Vector3.Maximize = function (left, right) {
  881. var max = left.clone();
  882. max.MaximizeInPlace(right);
  883. return max;
  884. };
  885. Vector3.Distance = function (value1, value2) {
  886. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  887. };
  888. Vector3.DistanceSquared = function (value1, value2) {
  889. var x = value1.x - value2.x;
  890. var y = value1.y - value2.y;
  891. var z = value1.z - value2.z;
  892. return (x * x) + (y * y) + (z * z);
  893. };
  894. Vector3.Center = function (value1, value2) {
  895. var center = value1.add(value2);
  896. center.scaleInPlace(0.5);
  897. return center;
  898. };
  899. /**
  900. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  901. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  902. * to something in order to rotate it from its local system to the given target system.
  903. */
  904. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  905. var rotation = Vector3.Zero();
  906. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  907. return rotation;
  908. };
  909. /**
  910. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  911. */
  912. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  913. var u = axis1.normalize();
  914. var w = axis3.normalize();
  915. // world axis
  916. var X = Axis.X;
  917. var Y = Axis.Y;
  918. // equation unknowns and vars
  919. var yaw = 0.0;
  920. var pitch = 0.0;
  921. var roll = 0.0;
  922. var x = 0.0;
  923. var y = 0.0;
  924. var z = 0.0;
  925. var t = 0.0;
  926. var sign = -1.0;
  927. var nbRevert = 0;
  928. var cross = Tmp.Vector3[0];
  929. var dot = 0.0;
  930. // step 1 : rotation around w
  931. // Rv3(u) = u1, and u1 belongs to plane xOz
  932. // Rv3(w) = w1 = w invariant
  933. var u1 = Tmp.Vector3[1];
  934. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  935. z = 1.0;
  936. }
  937. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  938. x = 1.0;
  939. }
  940. else {
  941. t = w.z / w.x;
  942. x = -t * Math.sqrt(1 / (1 + t * t));
  943. z = Math.sqrt(1 / (1 + t * t));
  944. }
  945. u1.x = x;
  946. u1.y = y;
  947. u1.z = z;
  948. u1.normalize();
  949. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  950. cross.normalize();
  951. if (Vector3.Dot(w, cross) < 0) {
  952. sign = 1.0;
  953. }
  954. dot = Vector3.Dot(u, u1);
  955. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  956. roll = Math.acos(dot) * sign;
  957. if (Vector3.Dot(u1, X) < 0) {
  958. roll = Math.PI + roll;
  959. u1 = u1.scaleInPlace(-1);
  960. nbRevert++;
  961. }
  962. // step 2 : rotate around u1
  963. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  964. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  965. var w2 = Tmp.Vector3[2];
  966. var v2 = Tmp.Vector3[3];
  967. x = 0.0;
  968. y = 0.0;
  969. z = 0.0;
  970. sign = -1.0;
  971. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  972. x = 1.0;
  973. }
  974. else {
  975. t = u1.z / u1.x;
  976. x = -t * Math.sqrt(1 / (1 + t * t));
  977. z = Math.sqrt(1 / (1 + t * t));
  978. }
  979. w2.x = x;
  980. w2.y = y;
  981. w2.z = z;
  982. w2.normalize();
  983. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  984. v2.normalize();
  985. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  986. cross.normalize();
  987. if (Vector3.Dot(u1, cross) < 0) {
  988. sign = 1.0;
  989. }
  990. dot = Vector3.Dot(w, w2);
  991. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  992. pitch = Math.acos(dot) * sign;
  993. if (Vector3.Dot(v2, Y) < 0) {
  994. pitch = Math.PI + pitch;
  995. nbRevert++;
  996. }
  997. // step 3 : rotate around v2
  998. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  999. sign = -1.0;
  1000. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1001. cross.normalize();
  1002. if (Vector3.Dot(cross, Y) < 0) {
  1003. sign = 1.0;
  1004. }
  1005. dot = Vector3.Dot(u1, X);
  1006. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1007. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1008. if (dot < 0 && nbRevert < 2) {
  1009. yaw = Math.PI + yaw;
  1010. }
  1011. ref.x = pitch;
  1012. ref.y = yaw;
  1013. ref.z = roll;
  1014. };
  1015. return Vector3;
  1016. })();
  1017. BABYLON.Vector3 = Vector3;
  1018. //Vector4 class created for EulerAngle class conversion to Quaternion
  1019. var Vector4 = (function () {
  1020. function Vector4(x, y, z, w) {
  1021. this.x = x;
  1022. this.y = y;
  1023. this.z = z;
  1024. this.w = w;
  1025. }
  1026. Vector4.prototype.toString = function () {
  1027. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1028. };
  1029. // Operators
  1030. Vector4.prototype.asArray = function () {
  1031. var result = [];
  1032. this.toArray(result, 0);
  1033. return result;
  1034. };
  1035. Vector4.prototype.toArray = function (array, index) {
  1036. if (index === undefined) {
  1037. index = 0;
  1038. }
  1039. array[index] = this.x;
  1040. array[index + 1] = this.y;
  1041. array[index + 2] = this.z;
  1042. array[index + 3] = this.w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.addInPlace = function (otherVector) {
  1046. this.x += otherVector.x;
  1047. this.y += otherVector.y;
  1048. this.z += otherVector.z;
  1049. this.w += otherVector.w;
  1050. return this;
  1051. };
  1052. Vector4.prototype.add = function (otherVector) {
  1053. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1054. };
  1055. Vector4.prototype.addToRef = function (otherVector, result) {
  1056. result.x = this.x + otherVector.x;
  1057. result.y = this.y + otherVector.y;
  1058. result.z = this.z + otherVector.z;
  1059. result.w = this.w + otherVector.w;
  1060. return this;
  1061. };
  1062. Vector4.prototype.subtractInPlace = function (otherVector) {
  1063. this.x -= otherVector.x;
  1064. this.y -= otherVector.y;
  1065. this.z -= otherVector.z;
  1066. this.w -= otherVector.w;
  1067. return this;
  1068. };
  1069. Vector4.prototype.subtract = function (otherVector) {
  1070. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1071. };
  1072. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1073. result.x = this.x - otherVector.x;
  1074. result.y = this.y - otherVector.y;
  1075. result.z = this.z - otherVector.z;
  1076. result.w = this.w - otherVector.w;
  1077. return this;
  1078. };
  1079. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1080. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1081. };
  1082. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1083. result.x = this.x - x;
  1084. result.y = this.y - y;
  1085. result.z = this.z - z;
  1086. result.w = this.w - w;
  1087. return this;
  1088. };
  1089. Vector4.prototype.negate = function () {
  1090. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1091. };
  1092. Vector4.prototype.scaleInPlace = function (scale) {
  1093. this.x *= scale;
  1094. this.y *= scale;
  1095. this.z *= scale;
  1096. this.w *= scale;
  1097. return this;
  1098. };
  1099. Vector4.prototype.scale = function (scale) {
  1100. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1101. };
  1102. Vector4.prototype.scaleToRef = function (scale, result) {
  1103. result.x = this.x * scale;
  1104. result.y = this.y * scale;
  1105. result.z = this.z * scale;
  1106. result.w = this.w * scale;
  1107. };
  1108. Vector4.prototype.equals = function (otherVector) {
  1109. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1110. };
  1111. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1112. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1113. return otherVector
  1114. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1115. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1116. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1117. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1118. };
  1119. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1120. return this.x === x && this.y === y && this.z === z && this.w === w;
  1121. };
  1122. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1123. this.x *= otherVector.x;
  1124. this.y *= otherVector.y;
  1125. this.z *= otherVector.z;
  1126. this.w *= otherVector.w;
  1127. return this;
  1128. };
  1129. Vector4.prototype.multiply = function (otherVector) {
  1130. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1131. };
  1132. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1133. result.x = this.x * otherVector.x;
  1134. result.y = this.y * otherVector.y;
  1135. result.z = this.z * otherVector.z;
  1136. result.w = this.w * otherVector.w;
  1137. return this;
  1138. };
  1139. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1140. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1141. };
  1142. Vector4.prototype.divide = function (otherVector) {
  1143. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1144. };
  1145. Vector4.prototype.divideToRef = function (otherVector, result) {
  1146. result.x = this.x / otherVector.x;
  1147. result.y = this.y / otherVector.y;
  1148. result.z = this.z / otherVector.z;
  1149. result.w = this.w / otherVector.w;
  1150. return this;
  1151. };
  1152. Vector4.prototype.MinimizeInPlace = function (other) {
  1153. if (other.x < this.x)
  1154. this.x = other.x;
  1155. if (other.y < this.y)
  1156. this.y = other.y;
  1157. if (other.z < this.z)
  1158. this.z = other.z;
  1159. if (other.w < this.w)
  1160. this.w = other.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.MaximizeInPlace = function (other) {
  1164. if (other.x > this.x)
  1165. this.x = other.x;
  1166. if (other.y > this.y)
  1167. this.y = other.y;
  1168. if (other.z > this.z)
  1169. this.z = other.z;
  1170. if (other.w > this.w)
  1171. this.w = other.w;
  1172. return this;
  1173. };
  1174. // Properties
  1175. Vector4.prototype.length = function () {
  1176. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1177. };
  1178. Vector4.prototype.lengthSquared = function () {
  1179. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1180. };
  1181. // Methods
  1182. Vector4.prototype.normalize = function () {
  1183. var len = this.length();
  1184. if (len === 0)
  1185. return this;
  1186. var num = 1.0 / len;
  1187. this.x *= num;
  1188. this.y *= num;
  1189. this.z *= num;
  1190. this.w *= num;
  1191. return this;
  1192. };
  1193. Vector4.prototype.toVector3 = function () {
  1194. return new Vector3(this.x, this.y, this.z);
  1195. };
  1196. Vector4.prototype.clone = function () {
  1197. return new Vector4(this.x, this.y, this.z, this.w);
  1198. };
  1199. Vector4.prototype.copyFrom = function (source) {
  1200. this.x = source.x;
  1201. this.y = source.y;
  1202. this.z = source.z;
  1203. this.w = source.w;
  1204. return this;
  1205. };
  1206. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1207. this.x = x;
  1208. this.y = y;
  1209. this.z = z;
  1210. this.w = w;
  1211. return this;
  1212. };
  1213. // Statics
  1214. Vector4.FromArray = function (array, offset) {
  1215. if (!offset) {
  1216. offset = 0;
  1217. }
  1218. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1219. };
  1220. Vector4.FromArrayToRef = function (array, offset, result) {
  1221. result.x = array[offset];
  1222. result.y = array[offset + 1];
  1223. result.z = array[offset + 2];
  1224. result.w = array[offset + 3];
  1225. };
  1226. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1227. result.x = array[offset];
  1228. result.y = array[offset + 1];
  1229. result.z = array[offset + 2];
  1230. result.w = array[offset + 3];
  1231. };
  1232. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1233. result.x = x;
  1234. result.y = y;
  1235. result.z = z;
  1236. result.w = w;
  1237. };
  1238. Vector4.Zero = function () {
  1239. return new Vector4(0, 0, 0, 0);
  1240. };
  1241. Vector4.Normalize = function (vector) {
  1242. var result = Vector4.Zero();
  1243. Vector4.NormalizeToRef(vector, result);
  1244. return result;
  1245. };
  1246. Vector4.NormalizeToRef = function (vector, result) {
  1247. result.copyFrom(vector);
  1248. result.normalize();
  1249. };
  1250. Vector4.Minimize = function (left, right) {
  1251. var min = left.clone();
  1252. min.MinimizeInPlace(right);
  1253. return min;
  1254. };
  1255. Vector4.Maximize = function (left, right) {
  1256. var max = left.clone();
  1257. max.MaximizeInPlace(right);
  1258. return max;
  1259. };
  1260. Vector4.Distance = function (value1, value2) {
  1261. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1262. };
  1263. Vector4.DistanceSquared = function (value1, value2) {
  1264. var x = value1.x - value2.x;
  1265. var y = value1.y - value2.y;
  1266. var z = value1.z - value2.z;
  1267. var w = value1.w - value2.w;
  1268. return (x * x) + (y * y) + (z * z) + (w * w);
  1269. };
  1270. Vector4.Center = function (value1, value2) {
  1271. var center = value1.add(value2);
  1272. center.scaleInPlace(0.5);
  1273. return center;
  1274. };
  1275. return Vector4;
  1276. })();
  1277. BABYLON.Vector4 = Vector4;
  1278. var Size = (function () {
  1279. function Size(width, height) {
  1280. this.width = width;
  1281. this.height = height;
  1282. }
  1283. Size.prototype.clone = function () {
  1284. return new Size(this.width, this.height);
  1285. };
  1286. Size.prototype.equals = function (other) {
  1287. if (!other) {
  1288. return false;
  1289. }
  1290. return (this.width === other.width) && (this.height === other.height);
  1291. };
  1292. Object.defineProperty(Size.prototype, "surface", {
  1293. get: function () {
  1294. return this.width * this.height;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Size.Zero = function () {
  1300. return new Size(0, 0);
  1301. };
  1302. return Size;
  1303. })();
  1304. BABYLON.Size = Size;
  1305. var Quaternion = (function () {
  1306. function Quaternion(x, y, z, w) {
  1307. if (x === void 0) { x = 0; }
  1308. if (y === void 0) { y = 0; }
  1309. if (z === void 0) { z = 0; }
  1310. if (w === void 0) { w = 1; }
  1311. this.x = x;
  1312. this.y = y;
  1313. this.z = z;
  1314. this.w = w;
  1315. }
  1316. Quaternion.prototype.toString = function () {
  1317. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1318. };
  1319. Quaternion.prototype.asArray = function () {
  1320. return [this.x, this.y, this.z, this.w];
  1321. };
  1322. Quaternion.prototype.equals = function (otherQuaternion) {
  1323. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1324. };
  1325. Quaternion.prototype.clone = function () {
  1326. return new Quaternion(this.x, this.y, this.z, this.w);
  1327. };
  1328. Quaternion.prototype.copyFrom = function (other) {
  1329. this.x = other.x;
  1330. this.y = other.y;
  1331. this.z = other.z;
  1332. this.w = other.w;
  1333. return this;
  1334. };
  1335. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1336. this.x = x;
  1337. this.y = y;
  1338. this.z = z;
  1339. this.w = w;
  1340. return this;
  1341. };
  1342. Quaternion.prototype.add = function (other) {
  1343. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1344. };
  1345. Quaternion.prototype.subtract = function (other) {
  1346. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1347. };
  1348. Quaternion.prototype.scale = function (value) {
  1349. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1350. };
  1351. Quaternion.prototype.multiply = function (q1) {
  1352. var result = new Quaternion(0, 0, 0, 1.0);
  1353. this.multiplyToRef(q1, result);
  1354. return result;
  1355. };
  1356. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1357. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1358. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1359. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1360. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1361. result.copyFromFloats(x, y, z, w);
  1362. return this;
  1363. };
  1364. Quaternion.prototype.multiplyInPlace = function (q1) {
  1365. this.multiplyToRef(q1, this);
  1366. return this;
  1367. };
  1368. Quaternion.prototype.conjugateToRef = function (ref) {
  1369. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1370. return this;
  1371. };
  1372. Quaternion.prototype.conjugateInPlace = function () {
  1373. this.x *= -1;
  1374. this.y *= -1;
  1375. this.z *= -1;
  1376. return this;
  1377. };
  1378. Quaternion.prototype.conjugate = function () {
  1379. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1380. return result;
  1381. };
  1382. Quaternion.prototype.length = function () {
  1383. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1384. };
  1385. Quaternion.prototype.normalize = function () {
  1386. var length = 1.0 / this.length();
  1387. this.x *= length;
  1388. this.y *= length;
  1389. this.z *= length;
  1390. this.w *= length;
  1391. return this;
  1392. };
  1393. Quaternion.prototype.toEulerAngles = function (order) {
  1394. if (order === void 0) { order = "YZX"; }
  1395. var result = Vector3.Zero();
  1396. this.toEulerAnglesToRef(result, order);
  1397. return result;
  1398. };
  1399. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1400. if (order === void 0) { order = "YZX"; }
  1401. var heading, attitude, bank;
  1402. var x = this.x, y = this.y, z = this.z, w = this.w;
  1403. switch (order) {
  1404. case "YZX":
  1405. var test = x * y + z * w;
  1406. if (test > 0.499) {
  1407. heading = 2 * Math.atan2(x, w);
  1408. attitude = Math.PI / 2;
  1409. bank = 0;
  1410. }
  1411. if (test < -0.499) {
  1412. heading = -2 * Math.atan2(x, w);
  1413. attitude = -Math.PI / 2;
  1414. bank = 0;
  1415. }
  1416. if (isNaN(heading)) {
  1417. var sqx = x * x;
  1418. var sqy = y * y;
  1419. var sqz = z * z;
  1420. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1421. attitude = Math.asin(2 * test); // attitude
  1422. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1423. }
  1424. break;
  1425. default:
  1426. throw new Error("Euler order " + order + " not supported yet.");
  1427. }
  1428. result.y = heading;
  1429. result.z = attitude;
  1430. result.x = bank;
  1431. return this;
  1432. };
  1433. ;
  1434. Quaternion.prototype.toRotationMatrix = function (result) {
  1435. var xx = this.x * this.x;
  1436. var yy = this.y * this.y;
  1437. var zz = this.z * this.z;
  1438. var xy = this.x * this.y;
  1439. var zw = this.z * this.w;
  1440. var zx = this.z * this.x;
  1441. var yw = this.y * this.w;
  1442. var yz = this.y * this.z;
  1443. var xw = this.x * this.w;
  1444. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1445. result.m[1] = 2.0 * (xy + zw);
  1446. result.m[2] = 2.0 * (zx - yw);
  1447. result.m[3] = 0;
  1448. result.m[4] = 2.0 * (xy - zw);
  1449. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1450. result.m[6] = 2.0 * (yz + xw);
  1451. result.m[7] = 0;
  1452. result.m[8] = 2.0 * (zx + yw);
  1453. result.m[9] = 2.0 * (yz - xw);
  1454. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1455. result.m[11] = 0;
  1456. result.m[12] = 0;
  1457. result.m[13] = 0;
  1458. result.m[14] = 0;
  1459. result.m[15] = 1.0;
  1460. return this;
  1461. };
  1462. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1463. Quaternion.FromRotationMatrixToRef(matrix, this);
  1464. return this;
  1465. };
  1466. // Statics
  1467. Quaternion.FromRotationMatrix = function (matrix) {
  1468. var result = new Quaternion();
  1469. Quaternion.FromRotationMatrixToRef(matrix, result);
  1470. return result;
  1471. };
  1472. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1473. var data = matrix.m;
  1474. var m11 = data[0], m12 = data[4], m13 = data[8];
  1475. var m21 = data[1], m22 = data[5], m23 = data[9];
  1476. var m31 = data[2], m32 = data[6], m33 = data[10];
  1477. var trace = m11 + m22 + m33;
  1478. var s;
  1479. if (trace > 0) {
  1480. s = 0.5 / Math.sqrt(trace + 1.0);
  1481. result.w = 0.25 / s;
  1482. result.x = (m32 - m23) * s;
  1483. result.y = (m13 - m31) * s;
  1484. result.z = (m21 - m12) * s;
  1485. }
  1486. else if (m11 > m22 && m11 > m33) {
  1487. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1488. result.w = (m32 - m23) / s;
  1489. result.x = 0.25 * s;
  1490. result.y = (m12 + m21) / s;
  1491. result.z = (m13 + m31) / s;
  1492. }
  1493. else if (m22 > m33) {
  1494. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1495. result.w = (m13 - m31) / s;
  1496. result.x = (m12 + m21) / s;
  1497. result.y = 0.25 * s;
  1498. result.z = (m23 + m32) / s;
  1499. }
  1500. else {
  1501. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1502. result.w = (m21 - m12) / s;
  1503. result.x = (m13 + m31) / s;
  1504. result.y = (m23 + m32) / s;
  1505. result.z = 0.25 * s;
  1506. }
  1507. };
  1508. Quaternion.Inverse = function (q) {
  1509. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1510. };
  1511. Quaternion.Identity = function () {
  1512. return new Quaternion(0, 0, 0, 1);
  1513. };
  1514. Quaternion.RotationAxis = function (axis, angle) {
  1515. var result = new Quaternion();
  1516. var sin = Math.sin(angle / 2);
  1517. axis.normalize();
  1518. result.w = Math.cos(angle / 2);
  1519. result.x = axis.x * sin;
  1520. result.y = axis.y * sin;
  1521. result.z = axis.z * sin;
  1522. return result;
  1523. };
  1524. Quaternion.FromArray = function (array, offset) {
  1525. if (!offset) {
  1526. offset = 0;
  1527. }
  1528. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1529. };
  1530. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1531. var result = new Quaternion();
  1532. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1533. return result;
  1534. };
  1535. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1536. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1537. var halfRoll = roll * 0.5;
  1538. var halfPitch = pitch * 0.5;
  1539. var halfYaw = yaw * 0.5;
  1540. var sinRoll = Math.sin(halfRoll);
  1541. var cosRoll = Math.cos(halfRoll);
  1542. var sinPitch = Math.sin(halfPitch);
  1543. var cosPitch = Math.cos(halfPitch);
  1544. var sinYaw = Math.sin(halfYaw);
  1545. var cosYaw = Math.cos(halfYaw);
  1546. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1547. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1548. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1549. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1550. };
  1551. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1552. var result = new Quaternion();
  1553. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1554. return result;
  1555. };
  1556. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1557. // Produces a quaternion from Euler angles in the z-x-z orientation
  1558. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1559. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1560. var halfBeta = beta * 0.5;
  1561. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1562. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1563. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1564. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1565. };
  1566. Quaternion.Slerp = function (left, right, amount) {
  1567. var num2;
  1568. var num3;
  1569. var num = amount;
  1570. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1571. var flag = false;
  1572. if (num4 < 0) {
  1573. flag = true;
  1574. num4 = -num4;
  1575. }
  1576. if (num4 > 0.999999) {
  1577. num3 = 1 - num;
  1578. num2 = flag ? -num : num;
  1579. }
  1580. else {
  1581. var num5 = Math.acos(num4);
  1582. var num6 = (1.0 / Math.sin(num5));
  1583. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1584. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1585. }
  1586. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1587. };
  1588. return Quaternion;
  1589. })();
  1590. BABYLON.Quaternion = Quaternion;
  1591. var Matrix = (function () {
  1592. function Matrix() {
  1593. this.m = new Float32Array(16);
  1594. }
  1595. // Properties
  1596. Matrix.prototype.isIdentity = function () {
  1597. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1598. return false;
  1599. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1600. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1601. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1602. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1603. return false;
  1604. return true;
  1605. };
  1606. Matrix.prototype.determinant = function () {
  1607. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1608. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1609. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1610. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1611. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1612. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1613. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1614. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1615. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1616. };
  1617. // Methods
  1618. Matrix.prototype.toArray = function () {
  1619. return this.m;
  1620. };
  1621. Matrix.prototype.asArray = function () {
  1622. return this.toArray();
  1623. };
  1624. Matrix.prototype.invert = function () {
  1625. this.invertToRef(this);
  1626. return this;
  1627. };
  1628. Matrix.prototype.reset = function () {
  1629. for (var index = 0; index < 16; index++) {
  1630. this.m[index] = 0;
  1631. }
  1632. return this;
  1633. };
  1634. Matrix.prototype.add = function (other) {
  1635. var result = new Matrix();
  1636. this.addToRef(other, result);
  1637. return result;
  1638. };
  1639. Matrix.prototype.addToRef = function (other, result) {
  1640. for (var index = 0; index < 16; index++) {
  1641. result.m[index] = this.m[index] + other.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.addToSelf = function (other) {
  1646. for (var index = 0; index < 16; index++) {
  1647. this.m[index] += other.m[index];
  1648. }
  1649. return this;
  1650. };
  1651. Matrix.prototype.invertToRef = function (other) {
  1652. var l1 = this.m[0];
  1653. var l2 = this.m[1];
  1654. var l3 = this.m[2];
  1655. var l4 = this.m[3];
  1656. var l5 = this.m[4];
  1657. var l6 = this.m[5];
  1658. var l7 = this.m[6];
  1659. var l8 = this.m[7];
  1660. var l9 = this.m[8];
  1661. var l10 = this.m[9];
  1662. var l11 = this.m[10];
  1663. var l12 = this.m[11];
  1664. var l13 = this.m[12];
  1665. var l14 = this.m[13];
  1666. var l15 = this.m[14];
  1667. var l16 = this.m[15];
  1668. var l17 = (l11 * l16) - (l12 * l15);
  1669. var l18 = (l10 * l16) - (l12 * l14);
  1670. var l19 = (l10 * l15) - (l11 * l14);
  1671. var l20 = (l9 * l16) - (l12 * l13);
  1672. var l21 = (l9 * l15) - (l11 * l13);
  1673. var l22 = (l9 * l14) - (l10 * l13);
  1674. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1675. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1676. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1677. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1678. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1679. var l28 = (l7 * l16) - (l8 * l15);
  1680. var l29 = (l6 * l16) - (l8 * l14);
  1681. var l30 = (l6 * l15) - (l7 * l14);
  1682. var l31 = (l5 * l16) - (l8 * l13);
  1683. var l32 = (l5 * l15) - (l7 * l13);
  1684. var l33 = (l5 * l14) - (l6 * l13);
  1685. var l34 = (l7 * l12) - (l8 * l11);
  1686. var l35 = (l6 * l12) - (l8 * l10);
  1687. var l36 = (l6 * l11) - (l7 * l10);
  1688. var l37 = (l5 * l12) - (l8 * l9);
  1689. var l38 = (l5 * l11) - (l7 * l9);
  1690. var l39 = (l5 * l10) - (l6 * l9);
  1691. other.m[0] = l23 * l27;
  1692. other.m[4] = l24 * l27;
  1693. other.m[8] = l25 * l27;
  1694. other.m[12] = l26 * l27;
  1695. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1696. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1697. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1698. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1699. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1700. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1701. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1702. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1703. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1704. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1705. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1706. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1707. return this;
  1708. };
  1709. Matrix.prototype.setTranslation = function (vector3) {
  1710. this.m[12] = vector3.x;
  1711. this.m[13] = vector3.y;
  1712. this.m[14] = vector3.z;
  1713. return this;
  1714. };
  1715. Matrix.prototype.getTranslation = function () {
  1716. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1717. };
  1718. Matrix.prototype.multiply = function (other) {
  1719. var result = new Matrix();
  1720. this.multiplyToRef(other, result);
  1721. return result;
  1722. };
  1723. Matrix.prototype.copyFrom = function (other) {
  1724. for (var index = 0; index < 16; index++) {
  1725. this.m[index] = other.m[index];
  1726. }
  1727. return this;
  1728. };
  1729. Matrix.prototype.copyToArray = function (array, offset) {
  1730. if (offset === void 0) { offset = 0; }
  1731. for (var index = 0; index < 16; index++) {
  1732. array[offset + index] = this.m[index];
  1733. }
  1734. return this;
  1735. };
  1736. Matrix.prototype.multiplyToRef = function (other, result) {
  1737. this.multiplyToArray(other, result.m, 0);
  1738. return this;
  1739. };
  1740. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1741. var tm0 = this.m[0];
  1742. var tm1 = this.m[1];
  1743. var tm2 = this.m[2];
  1744. var tm3 = this.m[3];
  1745. var tm4 = this.m[4];
  1746. var tm5 = this.m[5];
  1747. var tm6 = this.m[6];
  1748. var tm7 = this.m[7];
  1749. var tm8 = this.m[8];
  1750. var tm9 = this.m[9];
  1751. var tm10 = this.m[10];
  1752. var tm11 = this.m[11];
  1753. var tm12 = this.m[12];
  1754. var tm13 = this.m[13];
  1755. var tm14 = this.m[14];
  1756. var tm15 = this.m[15];
  1757. var om0 = other.m[0];
  1758. var om1 = other.m[1];
  1759. var om2 = other.m[2];
  1760. var om3 = other.m[3];
  1761. var om4 = other.m[4];
  1762. var om5 = other.m[5];
  1763. var om6 = other.m[6];
  1764. var om7 = other.m[7];
  1765. var om8 = other.m[8];
  1766. var om9 = other.m[9];
  1767. var om10 = other.m[10];
  1768. var om11 = other.m[11];
  1769. var om12 = other.m[12];
  1770. var om13 = other.m[13];
  1771. var om14 = other.m[14];
  1772. var om15 = other.m[15];
  1773. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1774. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1775. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1776. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1777. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1778. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1779. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1780. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1781. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1782. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1783. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1784. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1785. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1786. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1787. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1788. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1789. return this;
  1790. };
  1791. Matrix.prototype.equals = function (value) {
  1792. return value &&
  1793. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1794. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1795. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1796. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1797. };
  1798. Matrix.prototype.clone = function () {
  1799. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1800. };
  1801. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1802. translation.x = this.m[12];
  1803. translation.y = this.m[13];
  1804. translation.z = this.m[14];
  1805. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1806. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1807. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1808. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1809. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1810. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1811. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1812. rotation.x = 0;
  1813. rotation.y = 0;
  1814. rotation.z = 0;
  1815. rotation.w = 1;
  1816. return false;
  1817. }
  1818. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1819. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1820. return true;
  1821. };
  1822. // Statics
  1823. Matrix.FromArray = function (array, offset) {
  1824. var result = new Matrix();
  1825. if (!offset) {
  1826. offset = 0;
  1827. }
  1828. Matrix.FromArrayToRef(array, offset, result);
  1829. return result;
  1830. };
  1831. Matrix.FromArrayToRef = function (array, offset, result) {
  1832. for (var index = 0; index < 16; index++) {
  1833. result.m[index] = array[index + offset];
  1834. }
  1835. };
  1836. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1837. for (var index = 0; index < 16; index++) {
  1838. result.m[index] = array[index + offset] * scale;
  1839. }
  1840. };
  1841. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1842. result.m[0] = initialM11;
  1843. result.m[1] = initialM12;
  1844. result.m[2] = initialM13;
  1845. result.m[3] = initialM14;
  1846. result.m[4] = initialM21;
  1847. result.m[5] = initialM22;
  1848. result.m[6] = initialM23;
  1849. result.m[7] = initialM24;
  1850. result.m[8] = initialM31;
  1851. result.m[9] = initialM32;
  1852. result.m[10] = initialM33;
  1853. result.m[11] = initialM34;
  1854. result.m[12] = initialM41;
  1855. result.m[13] = initialM42;
  1856. result.m[14] = initialM43;
  1857. result.m[15] = initialM44;
  1858. };
  1859. Matrix.prototype.getRow = function (index) {
  1860. if (index < 0 || index > 3) {
  1861. return null;
  1862. }
  1863. var i = index * 4;
  1864. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  1865. };
  1866. Matrix.prototype.setRow = function (index, row) {
  1867. if (index < 0 || index > 3) {
  1868. return this;
  1869. }
  1870. var i = index * 4;
  1871. this.m[i + 0] = row.x;
  1872. this.m[i + 1] = row.y;
  1873. this.m[i + 2] = row.z;
  1874. this.m[i + 3] = row.w;
  1875. return this;
  1876. };
  1877. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1878. var result = new Matrix();
  1879. result.m[0] = initialM11;
  1880. result.m[1] = initialM12;
  1881. result.m[2] = initialM13;
  1882. result.m[3] = initialM14;
  1883. result.m[4] = initialM21;
  1884. result.m[5] = initialM22;
  1885. result.m[6] = initialM23;
  1886. result.m[7] = initialM24;
  1887. result.m[8] = initialM31;
  1888. result.m[9] = initialM32;
  1889. result.m[10] = initialM33;
  1890. result.m[11] = initialM34;
  1891. result.m[12] = initialM41;
  1892. result.m[13] = initialM42;
  1893. result.m[14] = initialM43;
  1894. result.m[15] = initialM44;
  1895. return result;
  1896. };
  1897. Matrix.Compose = function (scale, rotation, translation) {
  1898. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1899. var rotationMatrix = Matrix.Identity();
  1900. rotation.toRotationMatrix(rotationMatrix);
  1901. result = result.multiply(rotationMatrix);
  1902. result.setTranslation(translation);
  1903. return result;
  1904. };
  1905. Matrix.Identity = function () {
  1906. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1907. };
  1908. Matrix.IdentityToRef = function (result) {
  1909. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1910. };
  1911. Matrix.Zero = function () {
  1912. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1913. };
  1914. Matrix.RotationX = function (angle) {
  1915. var result = new Matrix();
  1916. Matrix.RotationXToRef(angle, result);
  1917. return result;
  1918. };
  1919. Matrix.Invert = function (source) {
  1920. var result = new Matrix();
  1921. source.invertToRef(result);
  1922. return result;
  1923. };
  1924. Matrix.RotationXToRef = function (angle, result) {
  1925. var s = Math.sin(angle);
  1926. var c = Math.cos(angle);
  1927. result.m[0] = 1.0;
  1928. result.m[15] = 1.0;
  1929. result.m[5] = c;
  1930. result.m[10] = c;
  1931. result.m[9] = -s;
  1932. result.m[6] = s;
  1933. result.m[1] = 0;
  1934. result.m[2] = 0;
  1935. result.m[3] = 0;
  1936. result.m[4] = 0;
  1937. result.m[7] = 0;
  1938. result.m[8] = 0;
  1939. result.m[11] = 0;
  1940. result.m[12] = 0;
  1941. result.m[13] = 0;
  1942. result.m[14] = 0;
  1943. };
  1944. Matrix.RotationY = function (angle) {
  1945. var result = new Matrix();
  1946. Matrix.RotationYToRef(angle, result);
  1947. return result;
  1948. };
  1949. Matrix.RotationYToRef = function (angle, result) {
  1950. var s = Math.sin(angle);
  1951. var c = Math.cos(angle);
  1952. result.m[5] = 1.0;
  1953. result.m[15] = 1.0;
  1954. result.m[0] = c;
  1955. result.m[2] = -s;
  1956. result.m[8] = s;
  1957. result.m[10] = c;
  1958. result.m[1] = 0;
  1959. result.m[3] = 0;
  1960. result.m[4] = 0;
  1961. result.m[6] = 0;
  1962. result.m[7] = 0;
  1963. result.m[9] = 0;
  1964. result.m[11] = 0;
  1965. result.m[12] = 0;
  1966. result.m[13] = 0;
  1967. result.m[14] = 0;
  1968. };
  1969. Matrix.RotationZ = function (angle) {
  1970. var result = new Matrix();
  1971. Matrix.RotationZToRef(angle, result);
  1972. return result;
  1973. };
  1974. Matrix.RotationZToRef = function (angle, result) {
  1975. var s = Math.sin(angle);
  1976. var c = Math.cos(angle);
  1977. result.m[10] = 1.0;
  1978. result.m[15] = 1.0;
  1979. result.m[0] = c;
  1980. result.m[1] = s;
  1981. result.m[4] = -s;
  1982. result.m[5] = c;
  1983. result.m[2] = 0;
  1984. result.m[3] = 0;
  1985. result.m[6] = 0;
  1986. result.m[7] = 0;
  1987. result.m[8] = 0;
  1988. result.m[9] = 0;
  1989. result.m[11] = 0;
  1990. result.m[12] = 0;
  1991. result.m[13] = 0;
  1992. result.m[14] = 0;
  1993. };
  1994. Matrix.RotationAxis = function (axis, angle) {
  1995. var result = Matrix.Zero();
  1996. Matrix.RotationAxisToRef(axis, angle, result);
  1997. return result;
  1998. };
  1999. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2000. var s = Math.sin(-angle);
  2001. var c = Math.cos(-angle);
  2002. var c1 = 1 - c;
  2003. axis.normalize();
  2004. result.m[0] = (axis.x * axis.x) * c1 + c;
  2005. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2006. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2007. result.m[3] = 0.0;
  2008. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2009. result.m[5] = (axis.y * axis.y) * c1 + c;
  2010. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2011. result.m[7] = 0.0;
  2012. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2013. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2014. result.m[10] = (axis.z * axis.z) * c1 + c;
  2015. result.m[11] = 0.0;
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2019. var result = new Matrix();
  2020. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2021. return result;
  2022. };
  2023. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2024. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2025. this._tempQuaternion.toRotationMatrix(result);
  2026. };
  2027. Matrix.Scaling = function (x, y, z) {
  2028. var result = Matrix.Zero();
  2029. Matrix.ScalingToRef(x, y, z, result);
  2030. return result;
  2031. };
  2032. Matrix.ScalingToRef = function (x, y, z, result) {
  2033. result.m[0] = x;
  2034. result.m[1] = 0;
  2035. result.m[2] = 0;
  2036. result.m[3] = 0;
  2037. result.m[4] = 0;
  2038. result.m[5] = y;
  2039. result.m[6] = 0;
  2040. result.m[7] = 0;
  2041. result.m[8] = 0;
  2042. result.m[9] = 0;
  2043. result.m[10] = z;
  2044. result.m[11] = 0;
  2045. result.m[12] = 0;
  2046. result.m[13] = 0;
  2047. result.m[14] = 0;
  2048. result.m[15] = 1.0;
  2049. };
  2050. Matrix.Translation = function (x, y, z) {
  2051. var result = Matrix.Identity();
  2052. Matrix.TranslationToRef(x, y, z, result);
  2053. return result;
  2054. };
  2055. Matrix.TranslationToRef = function (x, y, z, result) {
  2056. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2057. };
  2058. Matrix.Lerp = function (startValue, endValue, gradient) {
  2059. var result = Matrix.Zero();
  2060. for (var index = 0; index < 16; index++) {
  2061. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2062. }
  2063. return result;
  2064. };
  2065. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2066. var startScale = new Vector3(0, 0, 0);
  2067. var startRotation = new Quaternion();
  2068. var startTranslation = new Vector3(0, 0, 0);
  2069. startValue.decompose(startScale, startRotation, startTranslation);
  2070. var endScale = new Vector3(0, 0, 0);
  2071. var endRotation = new Quaternion();
  2072. var endTranslation = new Vector3(0, 0, 0);
  2073. endValue.decompose(endScale, endRotation, endTranslation);
  2074. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2075. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2076. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2077. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2078. };
  2079. Matrix.LookAtLH = function (eye, target, up) {
  2080. var result = Matrix.Zero();
  2081. Matrix.LookAtLHToRef(eye, target, up, result);
  2082. return result;
  2083. };
  2084. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2085. // Z axis
  2086. target.subtractToRef(eye, this._zAxis);
  2087. this._zAxis.normalize();
  2088. // X axis
  2089. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2090. if (this._xAxis.lengthSquared() === 0) {
  2091. this._xAxis.x = 1.0;
  2092. }
  2093. else {
  2094. this._xAxis.normalize();
  2095. }
  2096. // Y axis
  2097. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2098. this._yAxis.normalize();
  2099. // Eye angles
  2100. var ex = -Vector3.Dot(this._xAxis, eye);
  2101. var ey = -Vector3.Dot(this._yAxis, eye);
  2102. var ez = -Vector3.Dot(this._zAxis, eye);
  2103. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2104. };
  2105. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2106. var matrix = Matrix.Zero();
  2107. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2108. return matrix;
  2109. };
  2110. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2111. var hw = 2.0 / width;
  2112. var hh = 2.0 / height;
  2113. var id = 1.0 / (zfar - znear);
  2114. var nid = znear / (znear - zfar);
  2115. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2116. };
  2117. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2118. var matrix = Matrix.Zero();
  2119. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2120. return matrix;
  2121. };
  2122. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2123. result.m[0] = 2.0 / (right - left);
  2124. result.m[1] = result.m[2] = result.m[3] = 0;
  2125. result.m[5] = 2.0 / (top - bottom);
  2126. result.m[4] = result.m[6] = result.m[7] = 0;
  2127. result.m[10] = -1.0 / (znear - zfar);
  2128. result.m[8] = result.m[9] = result.m[11] = 0;
  2129. result.m[12] = (left + right) / (left - right);
  2130. result.m[13] = (top + bottom) / (bottom - top);
  2131. result.m[14] = znear / (znear - zfar);
  2132. result.m[15] = 1.0;
  2133. };
  2134. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2135. var matrix = Matrix.Zero();
  2136. matrix.m[0] = (2.0 * znear) / width;
  2137. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2138. matrix.m[5] = (2.0 * znear) / height;
  2139. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2140. matrix.m[10] = -zfar / (znear - zfar);
  2141. matrix.m[8] = matrix.m[9] = 0.0;
  2142. matrix.m[11] = 1.0;
  2143. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2144. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2145. return matrix;
  2146. };
  2147. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2148. var matrix = Matrix.Zero();
  2149. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2150. return matrix;
  2151. };
  2152. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2153. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2154. var tan = 1.0 / (Math.tan(fov * 0.5));
  2155. if (isVerticalFovFixed) {
  2156. result.m[0] = tan / aspect;
  2157. }
  2158. else {
  2159. result.m[0] = tan;
  2160. }
  2161. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2162. if (isVerticalFovFixed) {
  2163. result.m[5] = tan;
  2164. }
  2165. else {
  2166. result.m[5] = tan * aspect;
  2167. }
  2168. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2169. result.m[8] = result.m[9] = 0.0;
  2170. result.m[10] = -zfar / (znear - zfar);
  2171. result.m[11] = 1.0;
  2172. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2173. result.m[14] = (znear * zfar) / (znear - zfar);
  2174. };
  2175. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2176. var cw = viewport.width;
  2177. var ch = viewport.height;
  2178. var cx = viewport.x;
  2179. var cy = viewport.y;
  2180. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2181. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2182. };
  2183. Matrix.GetAsMatrix2x2 = function (matrix) {
  2184. return new Float32Array([
  2185. matrix.m[0], matrix.m[1],
  2186. matrix.m[4], matrix.m[5]
  2187. ]);
  2188. };
  2189. Matrix.GetAsMatrix3x3 = function (matrix) {
  2190. return new Float32Array([
  2191. matrix.m[0], matrix.m[1], matrix.m[2],
  2192. matrix.m[4], matrix.m[5], matrix.m[6],
  2193. matrix.m[8], matrix.m[9], matrix.m[10]
  2194. ]);
  2195. };
  2196. Matrix.Transpose = function (matrix) {
  2197. var result = new Matrix();
  2198. result.m[0] = matrix.m[0];
  2199. result.m[1] = matrix.m[4];
  2200. result.m[2] = matrix.m[8];
  2201. result.m[3] = matrix.m[12];
  2202. result.m[4] = matrix.m[1];
  2203. result.m[5] = matrix.m[5];
  2204. result.m[6] = matrix.m[9];
  2205. result.m[7] = matrix.m[13];
  2206. result.m[8] = matrix.m[2];
  2207. result.m[9] = matrix.m[6];
  2208. result.m[10] = matrix.m[10];
  2209. result.m[11] = matrix.m[14];
  2210. result.m[12] = matrix.m[3];
  2211. result.m[13] = matrix.m[7];
  2212. result.m[14] = matrix.m[11];
  2213. result.m[15] = matrix.m[15];
  2214. return result;
  2215. };
  2216. Matrix.Reflection = function (plane) {
  2217. var matrix = new Matrix();
  2218. Matrix.ReflectionToRef(plane, matrix);
  2219. return matrix;
  2220. };
  2221. Matrix.ReflectionToRef = function (plane, result) {
  2222. plane.normalize();
  2223. var x = plane.normal.x;
  2224. var y = plane.normal.y;
  2225. var z = plane.normal.z;
  2226. var temp = -2 * x;
  2227. var temp2 = -2 * y;
  2228. var temp3 = -2 * z;
  2229. result.m[0] = (temp * x) + 1;
  2230. result.m[1] = temp2 * x;
  2231. result.m[2] = temp3 * x;
  2232. result.m[3] = 0.0;
  2233. result.m[4] = temp * y;
  2234. result.m[5] = (temp2 * y) + 1;
  2235. result.m[6] = temp3 * y;
  2236. result.m[7] = 0.0;
  2237. result.m[8] = temp * z;
  2238. result.m[9] = temp2 * z;
  2239. result.m[10] = (temp3 * z) + 1;
  2240. result.m[11] = 0.0;
  2241. result.m[12] = temp * plane.d;
  2242. result.m[13] = temp2 * plane.d;
  2243. result.m[14] = temp3 * plane.d;
  2244. result.m[15] = 1.0;
  2245. };
  2246. Matrix._tempQuaternion = new Quaternion();
  2247. Matrix._xAxis = Vector3.Zero();
  2248. Matrix._yAxis = Vector3.Zero();
  2249. Matrix._zAxis = Vector3.Zero();
  2250. return Matrix;
  2251. })();
  2252. BABYLON.Matrix = Matrix;
  2253. var Plane = (function () {
  2254. function Plane(a, b, c, d) {
  2255. this.normal = new Vector3(a, b, c);
  2256. this.d = d;
  2257. }
  2258. Plane.prototype.asArray = function () {
  2259. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2260. };
  2261. // Methods
  2262. Plane.prototype.clone = function () {
  2263. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2264. };
  2265. Plane.prototype.normalize = function () {
  2266. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2267. var magnitude = 0;
  2268. if (norm !== 0) {
  2269. magnitude = 1.0 / norm;
  2270. }
  2271. this.normal.x *= magnitude;
  2272. this.normal.y *= magnitude;
  2273. this.normal.z *= magnitude;
  2274. this.d *= magnitude;
  2275. return this;
  2276. };
  2277. Plane.prototype.transform = function (transformation) {
  2278. var transposedMatrix = Matrix.Transpose(transformation);
  2279. var x = this.normal.x;
  2280. var y = this.normal.y;
  2281. var z = this.normal.z;
  2282. var d = this.d;
  2283. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2284. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2285. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2286. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2287. return new Plane(normalX, normalY, normalZ, finalD);
  2288. };
  2289. Plane.prototype.dotCoordinate = function (point) {
  2290. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2291. };
  2292. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2293. var x1 = point2.x - point1.x;
  2294. var y1 = point2.y - point1.y;
  2295. var z1 = point2.z - point1.z;
  2296. var x2 = point3.x - point1.x;
  2297. var y2 = point3.y - point1.y;
  2298. var z2 = point3.z - point1.z;
  2299. var yz = (y1 * z2) - (z1 * y2);
  2300. var xz = (z1 * x2) - (x1 * z2);
  2301. var xy = (x1 * y2) - (y1 * x2);
  2302. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2303. var invPyth;
  2304. if (pyth !== 0) {
  2305. invPyth = 1.0 / pyth;
  2306. }
  2307. else {
  2308. invPyth = 0;
  2309. }
  2310. this.normal.x = yz * invPyth;
  2311. this.normal.y = xz * invPyth;
  2312. this.normal.z = xy * invPyth;
  2313. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2314. return this;
  2315. };
  2316. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2317. var dot = Vector3.Dot(this.normal, direction);
  2318. return (dot <= epsilon);
  2319. };
  2320. Plane.prototype.signedDistanceTo = function (point) {
  2321. return Vector3.Dot(point, this.normal) + this.d;
  2322. };
  2323. // Statics
  2324. Plane.FromArray = function (array) {
  2325. return new Plane(array[0], array[1], array[2], array[3]);
  2326. };
  2327. Plane.FromPoints = function (point1, point2, point3) {
  2328. var result = new Plane(0, 0, 0, 0);
  2329. result.copyFromPoints(point1, point2, point3);
  2330. return result;
  2331. };
  2332. Plane.FromPositionAndNormal = function (origin, normal) {
  2333. var result = new Plane(0, 0, 0, 0);
  2334. normal.normalize();
  2335. result.normal = normal;
  2336. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2337. return result;
  2338. };
  2339. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2340. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2341. return Vector3.Dot(point, normal) + d;
  2342. };
  2343. return Plane;
  2344. })();
  2345. BABYLON.Plane = Plane;
  2346. var Viewport = (function () {
  2347. function Viewport(x, y, width, height) {
  2348. this.x = x;
  2349. this.y = y;
  2350. this.width = width;
  2351. this.height = height;
  2352. }
  2353. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2354. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2355. };
  2356. return Viewport;
  2357. })();
  2358. BABYLON.Viewport = Viewport;
  2359. var Frustum = (function () {
  2360. function Frustum() {
  2361. }
  2362. Frustum.GetPlanes = function (transform) {
  2363. var frustumPlanes = [];
  2364. for (var index = 0; index < 6; index++) {
  2365. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2366. }
  2367. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2368. return frustumPlanes;
  2369. };
  2370. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2371. // Near
  2372. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2373. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2374. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2375. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2376. frustumPlanes[0].normalize();
  2377. // Far
  2378. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2379. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2380. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2381. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2382. frustumPlanes[1].normalize();
  2383. // Left
  2384. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2385. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2386. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2387. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2388. frustumPlanes[2].normalize();
  2389. // Right
  2390. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2391. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2392. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2393. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2394. frustumPlanes[3].normalize();
  2395. // Top
  2396. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2397. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2398. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2399. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2400. frustumPlanes[4].normalize();
  2401. // Bottom
  2402. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2403. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2404. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2405. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2406. frustumPlanes[5].normalize();
  2407. };
  2408. return Frustum;
  2409. })();
  2410. BABYLON.Frustum = Frustum;
  2411. (function (Space) {
  2412. Space[Space["LOCAL"] = 0] = "LOCAL";
  2413. Space[Space["WORLD"] = 1] = "WORLD";
  2414. })(BABYLON.Space || (BABYLON.Space = {}));
  2415. var Space = BABYLON.Space;
  2416. var Axis = (function () {
  2417. function Axis() {
  2418. }
  2419. Axis.X = new Vector3(1, 0, 0);
  2420. Axis.Y = new Vector3(0, 1, 0);
  2421. Axis.Z = new Vector3(0, 0, 1);
  2422. return Axis;
  2423. })();
  2424. BABYLON.Axis = Axis;
  2425. ;
  2426. var BezierCurve = (function () {
  2427. function BezierCurve() {
  2428. }
  2429. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2430. // Extract X (which is equal to time here)
  2431. var f0 = 1 - 3 * x2 + 3 * x1;
  2432. var f1 = 3 * x2 - 6 * x1;
  2433. var f2 = 3 * x1;
  2434. var refinedT = t;
  2435. for (var i = 0; i < 5; i++) {
  2436. var refinedT2 = refinedT * refinedT;
  2437. var refinedT3 = refinedT2 * refinedT;
  2438. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2439. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2440. refinedT -= (x - t) * slope;
  2441. refinedT = Math.min(1, Math.max(0, refinedT));
  2442. }
  2443. // Resolve cubic bezier for the given x
  2444. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2445. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2446. Math.pow(refinedT, 3);
  2447. };
  2448. return BezierCurve;
  2449. })();
  2450. BABYLON.BezierCurve = BezierCurve;
  2451. (function (Orientation) {
  2452. Orientation[Orientation["CW"] = 0] = "CW";
  2453. Orientation[Orientation["CCW"] = 1] = "CCW";
  2454. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2455. var Orientation = BABYLON.Orientation;
  2456. var Angle = (function () {
  2457. function Angle(radians) {
  2458. var _this = this;
  2459. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2460. this.radians = function () { return _this._radians; };
  2461. this._radians = radians;
  2462. if (this._radians < 0)
  2463. this._radians += (2 * Math.PI);
  2464. }
  2465. Angle.BetweenTwoPoints = function (a, b) {
  2466. var delta = b.subtract(a);
  2467. var theta = Math.atan2(delta.y, delta.x);
  2468. return new Angle(theta);
  2469. };
  2470. Angle.FromRadians = function (radians) {
  2471. return new Angle(radians);
  2472. };
  2473. Angle.FromDegrees = function (degrees) {
  2474. return new Angle(degrees * Math.PI / 180);
  2475. };
  2476. return Angle;
  2477. })();
  2478. BABYLON.Angle = Angle;
  2479. var Arc2 = (function () {
  2480. function Arc2(startPoint, midPoint, endPoint) {
  2481. this.startPoint = startPoint;
  2482. this.midPoint = midPoint;
  2483. this.endPoint = endPoint;
  2484. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2485. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2486. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2487. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2488. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2489. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2490. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2491. var a1 = this.startAngle.degrees();
  2492. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2493. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2494. // angles correction
  2495. if (a2 - a1 > +180.0)
  2496. a2 -= 360.0;
  2497. if (a2 - a1 < -180.0)
  2498. a2 += 360.0;
  2499. if (a3 - a2 > +180.0)
  2500. a3 -= 360.0;
  2501. if (a3 - a2 < -180.0)
  2502. a3 += 360.0;
  2503. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2504. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2505. }
  2506. return Arc2;
  2507. })();
  2508. BABYLON.Arc2 = Arc2;
  2509. var Path2 = (function () {
  2510. function Path2(x, y) {
  2511. this._points = new Array();
  2512. this._length = 0;
  2513. this.closed = false;
  2514. this._points.push(new Vector2(x, y));
  2515. }
  2516. Path2.prototype.addLineTo = function (x, y) {
  2517. if (closed) {
  2518. //Tools.Error("cannot add lines to closed paths");
  2519. return this;
  2520. }
  2521. var newPoint = new Vector2(x, y);
  2522. var previousPoint = this._points[this._points.length - 1];
  2523. this._points.push(newPoint);
  2524. this._length += newPoint.subtract(previousPoint).length();
  2525. return this;
  2526. };
  2527. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2528. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2529. if (closed) {
  2530. //Tools.Error("cannot add arcs to closed paths");
  2531. return this;
  2532. }
  2533. var startPoint = this._points[this._points.length - 1];
  2534. var midPoint = new Vector2(midX, midY);
  2535. var endPoint = new Vector2(endX, endY);
  2536. var arc = new Arc2(startPoint, midPoint, endPoint);
  2537. var increment = arc.angle.radians() / numberOfSegments;
  2538. if (arc.orientation === Orientation.CW)
  2539. increment *= -1;
  2540. var currentAngle = arc.startAngle.radians() + increment;
  2541. for (var i = 0; i < numberOfSegments; i++) {
  2542. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2543. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2544. this.addLineTo(x, y);
  2545. currentAngle += increment;
  2546. }
  2547. return this;
  2548. };
  2549. Path2.prototype.close = function () {
  2550. this.closed = true;
  2551. return this;
  2552. };
  2553. Path2.prototype.length = function () {
  2554. var result = this._length;
  2555. if (!this.closed) {
  2556. var lastPoint = this._points[this._points.length - 1];
  2557. var firstPoint = this._points[0];
  2558. result += (firstPoint.subtract(lastPoint).length());
  2559. }
  2560. return result;
  2561. };
  2562. Path2.prototype.getPoints = function () {
  2563. return this._points;
  2564. };
  2565. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2566. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2567. //Tools.Error("normalized length position should be between 0 and 1.");
  2568. return Vector2.Zero();
  2569. }
  2570. var lengthPosition = normalizedLengthPosition * this.length();
  2571. var previousOffset = 0;
  2572. for (var i = 0; i < this._points.length; i++) {
  2573. var j = (i + 1) % this._points.length;
  2574. var a = this._points[i];
  2575. var b = this._points[j];
  2576. var bToA = b.subtract(a);
  2577. var nextOffset = (bToA.length() + previousOffset);
  2578. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2579. var dir = bToA.normalize();
  2580. var localOffset = lengthPosition - previousOffset;
  2581. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2582. }
  2583. previousOffset = nextOffset;
  2584. }
  2585. //Tools.Error("internal error");
  2586. return Vector2.Zero();
  2587. };
  2588. Path2.StartingAt = function (x, y) {
  2589. return new Path2(x, y);
  2590. };
  2591. return Path2;
  2592. })();
  2593. BABYLON.Path2 = Path2;
  2594. var Path3D = (function () {
  2595. /**
  2596. * new Path3D(path, normal, raw)
  2597. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2598. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2599. * path : an array of Vector3, the curve axis of the Path3D
  2600. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2601. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2602. */
  2603. function Path3D(path, firstNormal, raw) {
  2604. this.path = path;
  2605. this._curve = new Array();
  2606. this._distances = new Array();
  2607. this._tangents = new Array();
  2608. this._normals = new Array();
  2609. this._binormals = new Array();
  2610. for (var p = 0; p < path.length; p++) {
  2611. this._curve[p] = path[p].clone(); // hard copy
  2612. }
  2613. this._raw = raw || false;
  2614. this._compute(firstNormal);
  2615. }
  2616. /**
  2617. * Returns the Path3D array of successive Vector3 designing its curve.
  2618. */
  2619. Path3D.prototype.getCurve = function () {
  2620. return this._curve;
  2621. };
  2622. /**
  2623. * Returns an array populated with tangent vectors on each Path3D curve point.
  2624. */
  2625. Path3D.prototype.getTangents = function () {
  2626. return this._tangents;
  2627. };
  2628. /**
  2629. * Returns an array populated with normal vectors on each Path3D curve point.
  2630. */
  2631. Path3D.prototype.getNormals = function () {
  2632. return this._normals;
  2633. };
  2634. /**
  2635. * Returns an array populated with binormal vectors on each Path3D curve point.
  2636. */
  2637. Path3D.prototype.getBinormals = function () {
  2638. return this._binormals;
  2639. };
  2640. /**
  2641. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2642. */
  2643. Path3D.prototype.getDistances = function () {
  2644. return this._distances;
  2645. };
  2646. /**
  2647. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2648. * Returns the same object updated.
  2649. */
  2650. Path3D.prototype.update = function (path, firstNormal) {
  2651. for (var p = 0; p < path.length; p++) {
  2652. this._curve[p].x = path[p].x;
  2653. this._curve[p].y = path[p].y;
  2654. this._curve[p].z = path[p].z;
  2655. }
  2656. this._compute(firstNormal);
  2657. return this;
  2658. };
  2659. // private function compute() : computes tangents, normals and binormals
  2660. Path3D.prototype._compute = function (firstNormal) {
  2661. var l = this._curve.length;
  2662. // first and last tangents
  2663. this._tangents[0] = this._getFirstNonNullVector(0);
  2664. if (!this._raw) {
  2665. this._tangents[0].normalize();
  2666. }
  2667. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2668. if (!this._raw) {
  2669. this._tangents[l - 1].normalize();
  2670. }
  2671. // normals and binormals at first point : arbitrary vector with _normalVector()
  2672. var tg0 = this._tangents[0];
  2673. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2674. this._normals[0] = pp0;
  2675. if (!this._raw) {
  2676. this._normals[0].normalize();
  2677. }
  2678. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2679. if (!this._raw) {
  2680. this._binormals[0].normalize();
  2681. }
  2682. this._distances[0] = 0;
  2683. // normals and binormals : next points
  2684. var prev; // previous vector (segment)
  2685. var cur; // current vector (segment)
  2686. var curTang; // current tangent
  2687. // previous normal
  2688. var prevBinor; // previous binormal
  2689. for (var i = 1; i < l; i++) {
  2690. // tangents
  2691. prev = this._getLastNonNullVector(i);
  2692. if (i < l - 1) {
  2693. cur = this._getFirstNonNullVector(i);
  2694. this._tangents[i] = prev.add(cur);
  2695. this._tangents[i].normalize();
  2696. }
  2697. this._distances[i] = this._distances[i - 1] + prev.length();
  2698. // normals and binormals
  2699. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2700. curTang = this._tangents[i];
  2701. prevBinor = this._binormals[i - 1];
  2702. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2703. if (!this._raw) {
  2704. this._normals[i].normalize();
  2705. }
  2706. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2707. if (!this._raw) {
  2708. this._binormals[i].normalize();
  2709. }
  2710. }
  2711. };
  2712. // private function getFirstNonNullVector(index)
  2713. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2714. Path3D.prototype._getFirstNonNullVector = function (index) {
  2715. var i = 1;
  2716. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2717. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2718. i++;
  2719. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2720. }
  2721. return nNVector;
  2722. };
  2723. // private function getLastNonNullVector(index)
  2724. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2725. Path3D.prototype._getLastNonNullVector = function (index) {
  2726. var i = 1;
  2727. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2728. while (nLVector.length() === 0 && index > i + 1) {
  2729. i++;
  2730. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2731. }
  2732. return nLVector;
  2733. };
  2734. // private function normalVector(v0, vt, va) :
  2735. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2736. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2737. Path3D.prototype._normalVector = function (v0, vt, va) {
  2738. var normal0;
  2739. if (va === undefined || va === null) {
  2740. var point;
  2741. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2742. point = new Vector3(0, -1, 0);
  2743. }
  2744. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2745. point = new Vector3(1, 0, 0);
  2746. }
  2747. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2748. point = new Vector3(0, 0, 1);
  2749. }
  2750. normal0 = Vector3.Cross(vt, point);
  2751. }
  2752. else {
  2753. normal0 = Vector3.Cross(vt, va);
  2754. Vector3.CrossToRef(normal0, vt, normal0);
  2755. }
  2756. normal0.normalize();
  2757. return normal0;
  2758. };
  2759. return Path3D;
  2760. })();
  2761. BABYLON.Path3D = Path3D;
  2762. var Curve3 = (function () {
  2763. /**
  2764. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2765. * A Curve3 is designed from a series of successive Vector3.
  2766. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2767. */
  2768. function Curve3(points) {
  2769. this._length = 0;
  2770. this._points = points;
  2771. this._length = this._computeLength(points);
  2772. }
  2773. /**
  2774. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2775. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2776. * @param v1 (Vector3) the control point
  2777. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2778. * @param nbPoints (integer) the wanted number of points in the curve
  2779. */
  2780. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2781. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2782. var bez = new Array();
  2783. var equation = function (t, val0, val1, val2) {
  2784. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2785. return res;
  2786. };
  2787. for (var i = 0; i <= nbPoints; i++) {
  2788. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2789. }
  2790. return new Curve3(bez);
  2791. };
  2792. /**
  2793. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2794. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2795. * @param v1 (Vector3) the first control point
  2796. * @param v2 (Vector3) the second control point
  2797. * @param v3 (Vector3) the end point of the Cubic Bezier
  2798. * @param nbPoints (integer) the wanted number of points in the curve
  2799. */
  2800. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2801. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2802. var bez = new Array();
  2803. var equation = function (t, val0, val1, val2, val3) {
  2804. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2805. return res;
  2806. };
  2807. for (var i = 0; i <= nbPoints; i++) {
  2808. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2809. }
  2810. return new Curve3(bez);
  2811. };
  2812. /**
  2813. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2814. * @param p1 (Vector3) the origin point of the Hermite Spline
  2815. * @param t1 (Vector3) the tangent vector at the origin point
  2816. * @param p2 (Vector3) the end point of the Hermite Spline
  2817. * @param t2 (Vector3) the tangent vector at the end point
  2818. * @param nbPoints (integer) the wanted number of points in the curve
  2819. */
  2820. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2821. var hermite = new Array();
  2822. var step = 1 / nbPoints;
  2823. for (var i = 0; i <= nbPoints; i++) {
  2824. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2825. }
  2826. return new Curve3(hermite);
  2827. };
  2828. /**
  2829. * Returns the Curve3 stored array of successive Vector3
  2830. */
  2831. Curve3.prototype.getPoints = function () {
  2832. return this._points;
  2833. };
  2834. /**
  2835. * Returns the computed length (float) of the curve.
  2836. */
  2837. Curve3.prototype.length = function () {
  2838. return this._length;
  2839. };
  2840. /**
  2841. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2842. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2843. * curveA and curveB keep unchanged.
  2844. */
  2845. Curve3.prototype.continue = function (curve) {
  2846. var lastPoint = this._points[this._points.length - 1];
  2847. var continuedPoints = this._points.slice();
  2848. var curvePoints = curve.getPoints();
  2849. for (var i = 1; i < curvePoints.length; i++) {
  2850. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2851. }
  2852. var continuedCurve = new Curve3(continuedPoints);
  2853. return continuedCurve;
  2854. };
  2855. Curve3.prototype._computeLength = function (path) {
  2856. var l = 0;
  2857. for (var i = 1; i < path.length; i++) {
  2858. l += (path[i].subtract(path[i - 1])).length();
  2859. }
  2860. return l;
  2861. };
  2862. return Curve3;
  2863. })();
  2864. BABYLON.Curve3 = Curve3;
  2865. // SphericalHarmonics
  2866. var SphericalHarmonics = (function () {
  2867. function SphericalHarmonics() {
  2868. this.L00 = Vector3.Zero();
  2869. this.L1_1 = Vector3.Zero();
  2870. this.L10 = Vector3.Zero();
  2871. this.L11 = Vector3.Zero();
  2872. this.L2_2 = Vector3.Zero();
  2873. this.L2_1 = Vector3.Zero();
  2874. this.L20 = Vector3.Zero();
  2875. this.L21 = Vector3.Zero();
  2876. this.L22 = Vector3.Zero();
  2877. }
  2878. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2879. var colorVector = new Vector3(color.r, color.g, color.b);
  2880. var c = colorVector.scale(deltaSolidAngle);
  2881. this.L00 = this.L00.add(c.scale(0.282095));
  2882. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2883. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2884. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2885. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2886. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2887. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2888. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2889. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2890. };
  2891. SphericalHarmonics.prototype.scale = function (scale) {
  2892. this.L00 = this.L00.scale(scale);
  2893. this.L1_1 = this.L1_1.scale(scale);
  2894. this.L10 = this.L10.scale(scale);
  2895. this.L11 = this.L11.scale(scale);
  2896. this.L2_2 = this.L2_2.scale(scale);
  2897. this.L2_1 = this.L2_1.scale(scale);
  2898. this.L20 = this.L20.scale(scale);
  2899. this.L21 = this.L21.scale(scale);
  2900. this.L22 = this.L22.scale(scale);
  2901. };
  2902. return SphericalHarmonics;
  2903. })();
  2904. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2905. // SphericalPolynomial
  2906. var SphericalPolynomial = (function () {
  2907. function SphericalPolynomial() {
  2908. this.x = Vector3.Zero();
  2909. this.y = Vector3.Zero();
  2910. this.z = Vector3.Zero();
  2911. this.xx = Vector3.Zero();
  2912. this.yy = Vector3.Zero();
  2913. this.zz = Vector3.Zero();
  2914. this.xy = Vector3.Zero();
  2915. this.yz = Vector3.Zero();
  2916. this.zx = Vector3.Zero();
  2917. }
  2918. SphericalPolynomial.prototype.addAmbient = function (color) {
  2919. var colorVector = new Vector3(color.r, color.g, color.b);
  2920. this.xx = this.xx.add(colorVector);
  2921. this.yy = this.yy.add(colorVector);
  2922. this.zz = this.zz.add(colorVector);
  2923. };
  2924. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2925. var result = new SphericalPolynomial();
  2926. result.x = harmonics.L11.scale(1.02333);
  2927. result.y = harmonics.L1_1.scale(1.02333);
  2928. result.z = harmonics.L10.scale(1.02333);
  2929. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2930. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2931. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2932. result.yz = harmonics.L2_1.scale(0.858086);
  2933. result.zx = harmonics.L21.scale(0.858086);
  2934. result.xy = harmonics.L2_2.scale(0.858086);
  2935. return result;
  2936. };
  2937. return SphericalPolynomial;
  2938. })();
  2939. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2940. // Vertex formats
  2941. var PositionNormalVertex = (function () {
  2942. function PositionNormalVertex(position, normal) {
  2943. if (position === void 0) { position = Vector3.Zero(); }
  2944. if (normal === void 0) { normal = Vector3.Up(); }
  2945. this.position = position;
  2946. this.normal = normal;
  2947. }
  2948. PositionNormalVertex.prototype.clone = function () {
  2949. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2950. };
  2951. return PositionNormalVertex;
  2952. })();
  2953. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2954. var PositionNormalTextureVertex = (function () {
  2955. function PositionNormalTextureVertex(position, normal, uv) {
  2956. if (position === void 0) { position = Vector3.Zero(); }
  2957. if (normal === void 0) { normal = Vector3.Up(); }
  2958. if (uv === void 0) { uv = Vector2.Zero(); }
  2959. this.position = position;
  2960. this.normal = normal;
  2961. this.uv = uv;
  2962. }
  2963. PositionNormalTextureVertex.prototype.clone = function () {
  2964. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2965. };
  2966. return PositionNormalTextureVertex;
  2967. })();
  2968. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2969. // Temporary pre-allocated objects for engine internal use
  2970. // usage in any internal function :
  2971. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2972. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2973. var Tmp = (function () {
  2974. function Tmp() {
  2975. }
  2976. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2977. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2978. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2979. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2980. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2981. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2982. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2983. Matrix.Zero(), Matrix.Zero(),
  2984. Matrix.Zero(), Matrix.Zero(),
  2985. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2986. return Tmp;
  2987. })();
  2988. BABYLON.Tmp = Tmp;
  2989. })(BABYLON || (BABYLON = {}));
  2990. var BABYLON;
  2991. (function (BABYLON) {
  2992. function generateSerializableMember(type, sourceName) {
  2993. return function (target, propertyKey) {
  2994. if (!target.__serializableMembers) {
  2995. target.__serializableMembers = {};
  2996. }
  2997. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2998. };
  2999. }
  3000. function serialize(sourceName) {
  3001. return generateSerializableMember(0, sourceName); // value member
  3002. }
  3003. BABYLON.serialize = serialize;
  3004. function serializeAsTexture(sourceName) {
  3005. return generateSerializableMember(1, sourceName); // texture member
  3006. }
  3007. BABYLON.serializeAsTexture = serializeAsTexture;
  3008. function serializeAsColor3(sourceName) {
  3009. return generateSerializableMember(2, sourceName); // color3 member
  3010. }
  3011. BABYLON.serializeAsColor3 = serializeAsColor3;
  3012. function serializeAsFresnelParameters(sourceName) {
  3013. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3014. }
  3015. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3016. function serializeAsVector2(sourceName) {
  3017. return generateSerializableMember(4, sourceName); // vector2 member
  3018. }
  3019. BABYLON.serializeAsVector2 = serializeAsVector2;
  3020. function serializeAsVector3(sourceName) {
  3021. return generateSerializableMember(5, sourceName); // vector3 member
  3022. }
  3023. BABYLON.serializeAsVector3 = serializeAsVector3;
  3024. function serializeAsMeshReference(sourceName) {
  3025. return generateSerializableMember(6, sourceName); // mesh reference member
  3026. }
  3027. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3028. var SerializationHelper = (function () {
  3029. function SerializationHelper() {
  3030. }
  3031. SerializationHelper.Serialize = function (entity, serializationObject) {
  3032. if (!serializationObject) {
  3033. serializationObject = {};
  3034. }
  3035. // Tags
  3036. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3037. // Properties
  3038. for (var property in entity.__serializableMembers) {
  3039. var propertyDescriptor = entity.__serializableMembers[property];
  3040. var targetPropertyName = propertyDescriptor.sourceName || property;
  3041. var propertyType = propertyDescriptor.type;
  3042. var sourceProperty = entity[property];
  3043. if (sourceProperty !== undefined && sourceProperty !== null) {
  3044. switch (propertyType) {
  3045. case 0:
  3046. serializationObject[targetPropertyName] = sourceProperty;
  3047. break;
  3048. case 1:
  3049. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3050. break;
  3051. case 2:
  3052. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3053. break;
  3054. case 3:
  3055. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3056. break;
  3057. case 4:
  3058. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3059. break;
  3060. case 5:
  3061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3062. break;
  3063. case 6:
  3064. serializationObject[targetPropertyName] = sourceProperty.id;
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. return serializationObject;
  3070. };
  3071. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3072. var destination = creationFunction();
  3073. // Tags
  3074. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3075. // Properties
  3076. for (var property in destination.__serializableMembers) {
  3077. var propertyDescriptor = destination.__serializableMembers[property];
  3078. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3079. var propertyType = propertyDescriptor.type;
  3080. if (sourceProperty !== undefined && sourceProperty !== null) {
  3081. switch (propertyType) {
  3082. case 0:
  3083. destination[property] = sourceProperty;
  3084. break;
  3085. case 1:
  3086. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3087. break;
  3088. case 2:
  3089. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3090. break;
  3091. case 3:
  3092. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3093. break;
  3094. case 4:
  3095. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3096. break;
  3097. case 5:
  3098. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3099. break;
  3100. case 6:
  3101. destination[property] = scene.getLastMeshByID(sourceProperty);
  3102. break;
  3103. }
  3104. }
  3105. }
  3106. return destination;
  3107. };
  3108. SerializationHelper.Clone = function (creationFunction, source) {
  3109. var destination = creationFunction();
  3110. // Tags
  3111. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3112. // Properties
  3113. for (var property in destination.__serializableMembers) {
  3114. var propertyDescriptor = destination.__serializableMembers[property];
  3115. var sourceProperty = source[property];
  3116. var propertyType = propertyDescriptor.type;
  3117. if (sourceProperty !== undefined && sourceProperty !== null) {
  3118. switch (propertyType) {
  3119. case 0: // Value
  3120. case 6:
  3121. destination[property] = sourceProperty;
  3122. break;
  3123. case 1: // Texture
  3124. case 2: // Color3
  3125. case 3: // FresnelParameters
  3126. case 4: // Vector2
  3127. case 5:
  3128. destination[property] = sourceProperty.clone();
  3129. break;
  3130. }
  3131. }
  3132. }
  3133. return destination;
  3134. };
  3135. return SerializationHelper;
  3136. })();
  3137. BABYLON.SerializationHelper = SerializationHelper;
  3138. })(BABYLON || (BABYLON = {}));
  3139. var BABYLON;
  3140. (function (BABYLON) {
  3141. /**
  3142. * A class serves as a medium between the observable and its observers
  3143. */
  3144. var EventState = (function () {
  3145. /**
  3146. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3147. */
  3148. function EventState(mask, skipNextObservers) {
  3149. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3150. this.mask = mask;
  3151. this.skipNextObservers = skipNextObservers;
  3152. }
  3153. return EventState;
  3154. })();
  3155. BABYLON.EventState = EventState;
  3156. /**
  3157. * Represent an Observer registered to a given Observable object.
  3158. */
  3159. var Observer = (function () {
  3160. function Observer(callback, mask) {
  3161. this.callback = callback;
  3162. this.mask = mask;
  3163. }
  3164. return Observer;
  3165. })();
  3166. BABYLON.Observer = Observer;
  3167. /**
  3168. * The Observable class is a simple implementation of the Observable pattern.
  3169. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  3170. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3171. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  3172. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  3173. */
  3174. var Observable = (function () {
  3175. function Observable() {
  3176. this._observers = new Array();
  3177. }
  3178. /**
  3179. * Create a new Observer with the specified callback
  3180. * @param callback the callback that will be executed for that Observer
  3181. * @param mask the mask used to filter observers
  3182. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3183. */
  3184. Observable.prototype.add = function (callback, mask, insertFirst) {
  3185. if (mask === void 0) { mask = -1; }
  3186. if (insertFirst === void 0) { insertFirst = false; }
  3187. if (!callback) {
  3188. return null;
  3189. }
  3190. var observer = new Observer(callback, mask);
  3191. if (insertFirst) {
  3192. this._observers.unshift(observer);
  3193. }
  3194. else {
  3195. this._observers.push(observer);
  3196. }
  3197. return observer;
  3198. };
  3199. /**
  3200. * Remove an Observer from the Observable object
  3201. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3202. */
  3203. Observable.prototype.remove = function (observer) {
  3204. var index = this._observers.indexOf(observer);
  3205. if (index !== -1) {
  3206. this._observers.splice(index, 1);
  3207. return true;
  3208. }
  3209. return false;
  3210. };
  3211. /**
  3212. * Remove a callback from the Observable object
  3213. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3214. */
  3215. Observable.prototype.removeCallback = function (callback) {
  3216. for (var index = 0; index < this._observers.length; index++) {
  3217. if (this._observers[index].callback === callback) {
  3218. this._observers.splice(index, 1);
  3219. return true;
  3220. }
  3221. }
  3222. return false;
  3223. };
  3224. /**
  3225. * Notify all Observers by calling their respective callback with the given data
  3226. * @param eventData
  3227. * @param mask
  3228. */
  3229. Observable.prototype.notifyObservers = function (eventData, mask) {
  3230. if (mask === void 0) { mask = -1; }
  3231. var state = new EventState(mask);
  3232. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3233. var obs = _a[_i];
  3234. if (obs.mask & mask) {
  3235. obs.callback(eventData, state);
  3236. }
  3237. if (state.skipNextObservers) {
  3238. break;
  3239. }
  3240. }
  3241. };
  3242. /**
  3243. * return true is the Observable has at least one Observer registered
  3244. */
  3245. Observable.prototype.hasObservers = function () {
  3246. return this._observers.length > 0;
  3247. };
  3248. /**
  3249. * Clear the list of observers
  3250. */
  3251. Observable.prototype.clear = function () {
  3252. this._observers = new Array();
  3253. };
  3254. /**
  3255. * Clone the current observable
  3256. */
  3257. Observable.prototype.clone = function () {
  3258. var result = new Observable();
  3259. result._observers = this._observers.slice(0);
  3260. return result;
  3261. };
  3262. return Observable;
  3263. })();
  3264. BABYLON.Observable = Observable;
  3265. })(BABYLON || (BABYLON = {}));
  3266. var BABYLON;
  3267. (function (BABYLON) {
  3268. var Database = (function () {
  3269. function Database(urlToScene, callbackManifestChecked) {
  3270. // Handling various flavors of prefixed version of IndexedDB
  3271. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3272. this.callbackManifestChecked = callbackManifestChecked;
  3273. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3274. this.db = null;
  3275. this.enableSceneOffline = false;
  3276. this.enableTexturesOffline = false;
  3277. this.manifestVersionFound = 0;
  3278. this.mustUpdateRessources = false;
  3279. this.hasReachedQuota = false;
  3280. if (!Database.IDBStorageEnabled) {
  3281. this.callbackManifestChecked(true);
  3282. }
  3283. else {
  3284. this.checkManifestFile();
  3285. }
  3286. }
  3287. Database.prototype.checkManifestFile = function () {
  3288. var _this = this;
  3289. function noManifestFile() {
  3290. that.enableSceneOffline = false;
  3291. that.enableTexturesOffline = false;
  3292. that.callbackManifestChecked(false);
  3293. }
  3294. var that = this;
  3295. var timeStampUsed = false;
  3296. var manifestURL = this.currentSceneUrl + ".manifest";
  3297. var xhr = new XMLHttpRequest();
  3298. if (navigator.onLine) {
  3299. // Adding a timestamp to by-pass browsers' cache
  3300. timeStampUsed = true;
  3301. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3302. }
  3303. xhr.open("GET", manifestURL, true);
  3304. xhr.addEventListener("load", function () {
  3305. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3306. try {
  3307. var manifestFile = JSON.parse(xhr.response);
  3308. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3309. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3310. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3311. _this.manifestVersionFound = manifestFile.version;
  3312. }
  3313. if (_this.callbackManifestChecked) {
  3314. _this.callbackManifestChecked(true);
  3315. }
  3316. }
  3317. catch (ex) {
  3318. noManifestFile();
  3319. }
  3320. }
  3321. else {
  3322. noManifestFile();
  3323. }
  3324. }, false);
  3325. xhr.addEventListener("error", function (event) {
  3326. if (timeStampUsed) {
  3327. timeStampUsed = false;
  3328. // Let's retry without the timeStamp
  3329. // It could fail when coupled with HTML5 Offline API
  3330. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3331. xhr.open("GET", retryManifestURL, true);
  3332. xhr.send();
  3333. }
  3334. else {
  3335. noManifestFile();
  3336. }
  3337. }, false);
  3338. try {
  3339. xhr.send();
  3340. }
  3341. catch (ex) {
  3342. BABYLON.Tools.Error("Error on XHR send request.");
  3343. that.callbackManifestChecked(false);
  3344. }
  3345. };
  3346. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3347. var _this = this;
  3348. function handleError() {
  3349. that.isSupported = false;
  3350. if (errorCallback)
  3351. errorCallback();
  3352. }
  3353. var that = this;
  3354. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3355. // Your browser doesn't support IndexedDB
  3356. this.isSupported = false;
  3357. if (errorCallback)
  3358. errorCallback();
  3359. }
  3360. else {
  3361. // If the DB hasn't been opened or created yet
  3362. if (!this.db) {
  3363. this.hasReachedQuota = false;
  3364. this.isSupported = true;
  3365. var request = this.idbFactory.open("babylonjs", 1);
  3366. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3367. request.onerror = function (event) {
  3368. handleError();
  3369. };
  3370. // executes when a version change transaction cannot complete due to other active transactions
  3371. request.onblocked = function (event) {
  3372. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3373. handleError();
  3374. };
  3375. // DB has been opened successfully
  3376. request.onsuccess = function (event) {
  3377. _this.db = request.result;
  3378. successCallback();
  3379. };
  3380. // Initialization of the DB. Creating Scenes & Textures stores
  3381. request.onupgradeneeded = function (event) {
  3382. _this.db = (event.target).result;
  3383. try {
  3384. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3385. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3386. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3387. }
  3388. catch (ex) {
  3389. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3390. handleError();
  3391. }
  3392. };
  3393. }
  3394. else {
  3395. if (successCallback)
  3396. successCallback();
  3397. }
  3398. }
  3399. };
  3400. Database.prototype.loadImageFromDB = function (url, image) {
  3401. var _this = this;
  3402. var completeURL = Database.ReturnFullUrlLocation(url);
  3403. var saveAndLoadImage = function () {
  3404. if (!_this.hasReachedQuota && _this.db !== null) {
  3405. // the texture is not yet in the DB, let's try to save it
  3406. _this._saveImageIntoDBAsync(completeURL, image);
  3407. }
  3408. else {
  3409. image.src = url;
  3410. }
  3411. };
  3412. if (!this.mustUpdateRessources) {
  3413. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3414. }
  3415. else {
  3416. saveAndLoadImage();
  3417. }
  3418. };
  3419. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3420. if (this.isSupported && this.db !== null) {
  3421. var texture;
  3422. var transaction = this.db.transaction(["textures"]);
  3423. transaction.onabort = function (event) {
  3424. image.src = url;
  3425. };
  3426. transaction.oncomplete = function (event) {
  3427. var blobTextureURL;
  3428. if (texture) {
  3429. var URL = window.URL || window.webkitURL;
  3430. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3431. image.onerror = function () {
  3432. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3433. image.src = url;
  3434. };
  3435. image.src = blobTextureURL;
  3436. }
  3437. else {
  3438. notInDBCallback();
  3439. }
  3440. };
  3441. var getRequest = transaction.objectStore("textures").get(url);
  3442. getRequest.onsuccess = function (event) {
  3443. texture = (event.target).result;
  3444. };
  3445. getRequest.onerror = function (event) {
  3446. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3447. image.src = url;
  3448. };
  3449. }
  3450. else {
  3451. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3452. image.src = url;
  3453. }
  3454. };
  3455. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3456. var _this = this;
  3457. if (this.isSupported) {
  3458. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3459. var generateBlobUrl = function () {
  3460. var blobTextureURL;
  3461. if (blob) {
  3462. var URL = window.URL || window.webkitURL;
  3463. try {
  3464. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3465. }
  3466. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3467. catch (ex) {
  3468. blobTextureURL = URL.createObjectURL(blob);
  3469. }
  3470. }
  3471. image.src = blobTextureURL;
  3472. };
  3473. if (Database.IsUASupportingBlobStorage) {
  3474. var xhr = new XMLHttpRequest(), blob;
  3475. xhr.open("GET", url, true);
  3476. xhr.responseType = "blob";
  3477. xhr.addEventListener("load", function () {
  3478. if (xhr.status === 200) {
  3479. // Blob as response (XHR2)
  3480. blob = xhr.response;
  3481. var transaction = _this.db.transaction(["textures"], "readwrite");
  3482. // the transaction could abort because of a QuotaExceededError error
  3483. transaction.onabort = function (event) {
  3484. try {
  3485. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3486. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3487. this.hasReachedQuota = true;
  3488. }
  3489. }
  3490. catch (ex) { }
  3491. generateBlobUrl();
  3492. };
  3493. transaction.oncomplete = function (event) {
  3494. generateBlobUrl();
  3495. };
  3496. var newTexture = { textureUrl: url, data: blob };
  3497. try {
  3498. // Put the blob into the dabase
  3499. var addRequest = transaction.objectStore("textures").put(newTexture);
  3500. addRequest.onsuccess = function (event) {
  3501. };
  3502. addRequest.onerror = function (event) {
  3503. generateBlobUrl();
  3504. };
  3505. }
  3506. catch (ex) {
  3507. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3508. if (ex.code === 25) {
  3509. Database.IsUASupportingBlobStorage = false;
  3510. }
  3511. image.src = url;
  3512. }
  3513. }
  3514. else {
  3515. image.src = url;
  3516. }
  3517. }, false);
  3518. xhr.addEventListener("error", function (event) {
  3519. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3520. image.src = url;
  3521. }, false);
  3522. xhr.send();
  3523. }
  3524. else {
  3525. image.src = url;
  3526. }
  3527. }
  3528. else {
  3529. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3530. image.src = url;
  3531. }
  3532. };
  3533. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3534. var _this = this;
  3535. var updateVersion = function (event) {
  3536. // the version is not yet in the DB or we need to update it
  3537. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3538. };
  3539. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3540. };
  3541. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3542. var _this = this;
  3543. if (this.isSupported) {
  3544. var version;
  3545. try {
  3546. var transaction = this.db.transaction(["versions"]);
  3547. transaction.oncomplete = function (event) {
  3548. if (version) {
  3549. // If the version in the JSON file is > than the version in DB
  3550. if (_this.manifestVersionFound > version.data) {
  3551. _this.mustUpdateRessources = true;
  3552. updateInDBCallback();
  3553. }
  3554. else {
  3555. callback(version.data);
  3556. }
  3557. }
  3558. else {
  3559. _this.mustUpdateRessources = true;
  3560. updateInDBCallback();
  3561. }
  3562. };
  3563. transaction.onabort = function (event) {
  3564. callback(-1);
  3565. };
  3566. var getRequest = transaction.objectStore("versions").get(url);
  3567. getRequest.onsuccess = function (event) {
  3568. version = (event.target).result;
  3569. };
  3570. getRequest.onerror = function (event) {
  3571. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3572. callback(-1);
  3573. };
  3574. }
  3575. catch (ex) {
  3576. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3577. callback(-1);
  3578. }
  3579. }
  3580. else {
  3581. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3582. callback(-1);
  3583. }
  3584. };
  3585. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3586. var _this = this;
  3587. if (this.isSupported && !this.hasReachedQuota) {
  3588. try {
  3589. // Open a transaction to the database
  3590. var transaction = this.db.transaction(["versions"], "readwrite");
  3591. // the transaction could abort because of a QuotaExceededError error
  3592. transaction.onabort = function (event) {
  3593. try {
  3594. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3595. _this.hasReachedQuota = true;
  3596. }
  3597. }
  3598. catch (ex) { }
  3599. callback(-1);
  3600. };
  3601. transaction.oncomplete = function (event) {
  3602. callback(_this.manifestVersionFound);
  3603. };
  3604. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3605. // Put the scene into the database
  3606. var addRequest = transaction.objectStore("versions").put(newVersion);
  3607. addRequest.onsuccess = function (event) {
  3608. };
  3609. addRequest.onerror = function (event) {
  3610. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3611. };
  3612. }
  3613. catch (ex) {
  3614. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3615. callback(-1);
  3616. }
  3617. }
  3618. else {
  3619. callback(-1);
  3620. }
  3621. };
  3622. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3623. var _this = this;
  3624. var completeUrl = Database.ReturnFullUrlLocation(url);
  3625. var saveAndLoadFile = function (event) {
  3626. // the scene is not yet in the DB, let's try to save it
  3627. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3628. };
  3629. this._checkVersionFromDB(completeUrl, function (version) {
  3630. if (version !== -1) {
  3631. if (!_this.mustUpdateRessources) {
  3632. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3633. }
  3634. else {
  3635. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3636. }
  3637. }
  3638. else {
  3639. errorCallback();
  3640. }
  3641. });
  3642. };
  3643. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3644. if (this.isSupported) {
  3645. var targetStore;
  3646. if (url.indexOf(".babylon") !== -1) {
  3647. targetStore = "scenes";
  3648. }
  3649. else {
  3650. targetStore = "textures";
  3651. }
  3652. var file;
  3653. var transaction = this.db.transaction([targetStore]);
  3654. transaction.oncomplete = function (event) {
  3655. if (file) {
  3656. callback(file.data);
  3657. }
  3658. else {
  3659. notInDBCallback();
  3660. }
  3661. };
  3662. transaction.onabort = function (event) {
  3663. notInDBCallback();
  3664. };
  3665. var getRequest = transaction.objectStore(targetStore).get(url);
  3666. getRequest.onsuccess = function (event) {
  3667. file = (event.target).result;
  3668. };
  3669. getRequest.onerror = function (event) {
  3670. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3671. notInDBCallback();
  3672. };
  3673. }
  3674. else {
  3675. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3676. callback();
  3677. }
  3678. };
  3679. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3680. var _this = this;
  3681. if (this.isSupported) {
  3682. var targetStore;
  3683. if (url.indexOf(".babylon") !== -1) {
  3684. targetStore = "scenes";
  3685. }
  3686. else {
  3687. targetStore = "textures";
  3688. }
  3689. // Create XHR
  3690. var xhr = new XMLHttpRequest(), fileData;
  3691. xhr.open("GET", url, true);
  3692. if (useArrayBuffer) {
  3693. xhr.responseType = "arraybuffer";
  3694. }
  3695. xhr.onprogress = progressCallback;
  3696. xhr.addEventListener("load", function () {
  3697. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3698. // Blob as response (XHR2)
  3699. //fileData = xhr.responseText;
  3700. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3701. if (!_this.hasReachedQuota) {
  3702. // Open a transaction to the database
  3703. var transaction = _this.db.transaction([targetStore], "readwrite");
  3704. // the transaction could abort because of a QuotaExceededError error
  3705. transaction.onabort = function (event) {
  3706. try {
  3707. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3708. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3709. this.hasReachedQuota = true;
  3710. }
  3711. }
  3712. catch (ex) { }
  3713. callback(fileData);
  3714. };
  3715. transaction.oncomplete = function (event) {
  3716. callback(fileData);
  3717. };
  3718. var newFile;
  3719. if (targetStore === "scenes") {
  3720. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3721. }
  3722. else {
  3723. newFile = { textureUrl: url, data: fileData };
  3724. }
  3725. try {
  3726. // Put the scene into the database
  3727. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3728. addRequest.onsuccess = function (event) {
  3729. };
  3730. addRequest.onerror = function (event) {
  3731. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3732. };
  3733. }
  3734. catch (ex) {
  3735. callback(fileData);
  3736. }
  3737. }
  3738. else {
  3739. callback(fileData);
  3740. }
  3741. }
  3742. else {
  3743. callback();
  3744. }
  3745. }, false);
  3746. xhr.addEventListener("error", function (event) {
  3747. BABYLON.Tools.Error("error on XHR request.");
  3748. callback();
  3749. }, false);
  3750. xhr.send();
  3751. }
  3752. else {
  3753. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3754. callback();
  3755. }
  3756. };
  3757. Database.IsUASupportingBlobStorage = true;
  3758. Database.IDBStorageEnabled = true;
  3759. Database.parseURL = function (url) {
  3760. var a = document.createElement('a');
  3761. a.href = url;
  3762. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3763. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3764. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3765. return absLocation;
  3766. };
  3767. Database.ReturnFullUrlLocation = function (url) {
  3768. if (url.indexOf("http:/") === -1) {
  3769. return (Database.parseURL(window.location.href) + url);
  3770. }
  3771. else {
  3772. return url;
  3773. }
  3774. };
  3775. return Database;
  3776. })();
  3777. BABYLON.Database = Database;
  3778. })(BABYLON || (BABYLON = {}));
  3779. var BABYLON;
  3780. (function (BABYLON) {
  3781. var Internals;
  3782. (function (Internals) {
  3783. /*
  3784. * Based on jsTGALoader - Javascript loader for TGA file
  3785. * By Vincent Thibault
  3786. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3787. */
  3788. var TGATools = (function () {
  3789. function TGATools() {
  3790. }
  3791. TGATools.GetTGAHeader = function (data) {
  3792. var offset = 0;
  3793. var header = {
  3794. id_length: data[offset++],
  3795. colormap_type: data[offset++],
  3796. image_type: data[offset++],
  3797. colormap_index: data[offset++] | data[offset++] << 8,
  3798. colormap_length: data[offset++] | data[offset++] << 8,
  3799. colormap_size: data[offset++],
  3800. origin: [
  3801. data[offset++] | data[offset++] << 8,
  3802. data[offset++] | data[offset++] << 8
  3803. ],
  3804. width: data[offset++] | data[offset++] << 8,
  3805. height: data[offset++] | data[offset++] << 8,
  3806. pixel_size: data[offset++],
  3807. flags: data[offset++]
  3808. };
  3809. return header;
  3810. };
  3811. TGATools.UploadContent = function (gl, data) {
  3812. // Not enough data to contain header ?
  3813. if (data.length < 19) {
  3814. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3815. return;
  3816. }
  3817. // Read Header
  3818. var offset = 18;
  3819. var header = TGATools.GetTGAHeader(data);
  3820. // Assume it's a valid Targa file.
  3821. if (header.id_length + offset > data.length) {
  3822. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3823. return;
  3824. }
  3825. // Skip not needed data
  3826. offset += header.id_length;
  3827. var use_rle = false;
  3828. var use_pal = false;
  3829. var use_rgb = false;
  3830. var use_grey = false;
  3831. // Get some informations.
  3832. switch (header.image_type) {
  3833. case TGATools._TYPE_RLE_INDEXED:
  3834. use_rle = true;
  3835. case TGATools._TYPE_INDEXED:
  3836. use_pal = true;
  3837. break;
  3838. case TGATools._TYPE_RLE_RGB:
  3839. use_rle = true;
  3840. case TGATools._TYPE_RGB:
  3841. use_rgb = true;
  3842. break;
  3843. case TGATools._TYPE_RLE_GREY:
  3844. use_rle = true;
  3845. case TGATools._TYPE_GREY:
  3846. use_grey = true;
  3847. break;
  3848. }
  3849. var pixel_data;
  3850. var numAlphaBits = header.flags & 0xf;
  3851. var pixel_size = header.pixel_size >> 3;
  3852. var pixel_total = header.width * header.height * pixel_size;
  3853. // Read palettes
  3854. var palettes;
  3855. if (use_pal) {
  3856. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3857. }
  3858. // Read LRE
  3859. if (use_rle) {
  3860. pixel_data = new Uint8Array(pixel_total);
  3861. var c, count, i;
  3862. var localOffset = 0;
  3863. var pixels = new Uint8Array(pixel_size);
  3864. while (offset < pixel_total && localOffset < pixel_total) {
  3865. c = data[offset++];
  3866. count = (c & 0x7f) + 1;
  3867. // RLE pixels
  3868. if (c & 0x80) {
  3869. // Bind pixel tmp array
  3870. for (i = 0; i < pixel_size; ++i) {
  3871. pixels[i] = data[offset++];
  3872. }
  3873. // Copy pixel array
  3874. for (i = 0; i < count; ++i) {
  3875. pixel_data.set(pixels, localOffset + i * pixel_size);
  3876. }
  3877. localOffset += pixel_size * count;
  3878. }
  3879. else {
  3880. count *= pixel_size;
  3881. for (i = 0; i < count; ++i) {
  3882. pixel_data[localOffset + i] = data[offset++];
  3883. }
  3884. localOffset += count;
  3885. }
  3886. }
  3887. }
  3888. else {
  3889. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3890. }
  3891. // Load to texture
  3892. var x_start, y_start, x_step, y_step, y_end, x_end;
  3893. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3894. default:
  3895. case TGATools._ORIGIN_UL:
  3896. x_start = 0;
  3897. x_step = 1;
  3898. x_end = header.width;
  3899. y_start = 0;
  3900. y_step = 1;
  3901. y_end = header.height;
  3902. break;
  3903. case TGATools._ORIGIN_BL:
  3904. x_start = 0;
  3905. x_step = 1;
  3906. x_end = header.width;
  3907. y_start = header.height - 1;
  3908. y_step = -1;
  3909. y_end = -1;
  3910. break;
  3911. case TGATools._ORIGIN_UR:
  3912. x_start = header.width - 1;
  3913. x_step = -1;
  3914. x_end = -1;
  3915. y_start = 0;
  3916. y_step = 1;
  3917. y_end = header.height;
  3918. break;
  3919. case TGATools._ORIGIN_BR:
  3920. x_start = header.width - 1;
  3921. x_step = -1;
  3922. x_end = -1;
  3923. y_start = header.height - 1;
  3924. y_step = -1;
  3925. y_end = -1;
  3926. break;
  3927. }
  3928. // Load the specify method
  3929. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3930. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3931. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3932. };
  3933. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3934. var image = pixel_data, colormap = palettes;
  3935. var width = header.width, height = header.height;
  3936. var color, i = 0, x, y;
  3937. var imageData = new Uint8Array(width * height * 4);
  3938. for (y = y_start; y !== y_end; y += y_step) {
  3939. for (x = x_start; x !== x_end; x += x_step, i++) {
  3940. color = image[i];
  3941. imageData[(x + width * y) * 4 + 3] = 255;
  3942. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3943. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3944. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3945. }
  3946. }
  3947. return imageData;
  3948. };
  3949. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3950. var image = pixel_data;
  3951. var width = header.width, height = header.height;
  3952. var color, i = 0, x, y;
  3953. var imageData = new Uint8Array(width * height * 4);
  3954. for (y = y_start; y !== y_end; y += y_step) {
  3955. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3956. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3957. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3958. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3959. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3960. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3961. }
  3962. }
  3963. return imageData;
  3964. };
  3965. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3966. var image = pixel_data;
  3967. var width = header.width, height = header.height;
  3968. var i = 0, x, y;
  3969. var imageData = new Uint8Array(width * height * 4);
  3970. for (y = y_start; y !== y_end; y += y_step) {
  3971. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3972. imageData[(x + width * y) * 4 + 3] = 255;
  3973. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3974. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3975. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3976. }
  3977. }
  3978. return imageData;
  3979. };
  3980. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3981. var image = pixel_data;
  3982. var width = header.width, height = header.height;
  3983. var i = 0, x, y;
  3984. var imageData = new Uint8Array(width * height * 4);
  3985. for (y = y_start; y !== y_end; y += y_step) {
  3986. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3987. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3988. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3989. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3990. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3991. }
  3992. }
  3993. return imageData;
  3994. };
  3995. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3996. var image = pixel_data;
  3997. var width = header.width, height = header.height;
  3998. var color, i = 0, x, y;
  3999. var imageData = new Uint8Array(width * height * 4);
  4000. for (y = y_start; y !== y_end; y += y_step) {
  4001. for (x = x_start; x !== x_end; x += x_step, i++) {
  4002. color = image[i];
  4003. imageData[(x + width * y) * 4 + 0] = color;
  4004. imageData[(x + width * y) * 4 + 1] = color;
  4005. imageData[(x + width * y) * 4 + 2] = color;
  4006. imageData[(x + width * y) * 4 + 3] = 255;
  4007. }
  4008. }
  4009. return imageData;
  4010. };
  4011. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4012. var image = pixel_data;
  4013. var width = header.width, height = header.height;
  4014. var i = 0, x, y;
  4015. var imageData = new Uint8Array(width * height * 4);
  4016. for (y = y_start; y !== y_end; y += y_step) {
  4017. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4018. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4019. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4020. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4021. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4022. }
  4023. }
  4024. return imageData;
  4025. };
  4026. TGATools._TYPE_NO_DATA = 0;
  4027. TGATools._TYPE_INDEXED = 1;
  4028. TGATools._TYPE_RGB = 2;
  4029. TGATools._TYPE_GREY = 3;
  4030. TGATools._TYPE_RLE_INDEXED = 9;
  4031. TGATools._TYPE_RLE_RGB = 10;
  4032. TGATools._TYPE_RLE_GREY = 11;
  4033. TGATools._ORIGIN_MASK = 0x30;
  4034. TGATools._ORIGIN_SHIFT = 0x04;
  4035. TGATools._ORIGIN_BL = 0x00;
  4036. TGATools._ORIGIN_BR = 0x01;
  4037. TGATools._ORIGIN_UL = 0x02;
  4038. TGATools._ORIGIN_UR = 0x03;
  4039. return TGATools;
  4040. })();
  4041. Internals.TGATools = TGATools;
  4042. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4043. })(BABYLON || (BABYLON = {}));
  4044. var BABYLON;
  4045. (function (BABYLON) {
  4046. var SmartArray = (function () {
  4047. function SmartArray(capacity) {
  4048. this.length = 0;
  4049. this._duplicateId = 0;
  4050. this.data = new Array(capacity);
  4051. this._id = SmartArray._GlobalId++;
  4052. }
  4053. SmartArray.prototype.push = function (value) {
  4054. this.data[this.length++] = value;
  4055. if (this.length > this.data.length) {
  4056. this.data.length *= 2;
  4057. }
  4058. if (!value.__smartArrayFlags) {
  4059. value.__smartArrayFlags = {};
  4060. }
  4061. value.__smartArrayFlags[this._id] = this._duplicateId;
  4062. };
  4063. SmartArray.prototype.pushNoDuplicate = function (value) {
  4064. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4065. return;
  4066. }
  4067. this.push(value);
  4068. };
  4069. SmartArray.prototype.sort = function (compareFn) {
  4070. this.data.sort(compareFn);
  4071. };
  4072. SmartArray.prototype.reset = function () {
  4073. this.length = 0;
  4074. this._duplicateId++;
  4075. };
  4076. SmartArray.prototype.concat = function (array) {
  4077. if (array.length === 0) {
  4078. return;
  4079. }
  4080. if (this.length + array.length > this.data.length) {
  4081. this.data.length = (this.length + array.length) * 2;
  4082. }
  4083. for (var index = 0; index < array.length; index++) {
  4084. this.data[this.length++] = (array.data || array)[index];
  4085. }
  4086. };
  4087. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4088. if (array.length === 0) {
  4089. return;
  4090. }
  4091. if (this.length + array.length > this.data.length) {
  4092. this.data.length = (this.length + array.length) * 2;
  4093. }
  4094. for (var index = 0; index < array.length; index++) {
  4095. var item = (array.data || array)[index];
  4096. this.pushNoDuplicate(item);
  4097. }
  4098. };
  4099. SmartArray.prototype.indexOf = function (value) {
  4100. var position = this.data.indexOf(value);
  4101. if (position >= this.length) {
  4102. return -1;
  4103. }
  4104. return position;
  4105. };
  4106. // Statics
  4107. SmartArray._GlobalId = 0;
  4108. return SmartArray;
  4109. })();
  4110. BABYLON.SmartArray = SmartArray;
  4111. })(BABYLON || (BABYLON = {}));
  4112. var BABYLON;
  4113. (function (BABYLON) {
  4114. /**
  4115. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4116. * The underlying implementation relies on an associative array to ensure the best performances.
  4117. * The value can be anything including 'null' but except 'undefined'
  4118. */
  4119. var StringDictionary = (function () {
  4120. function StringDictionary() {
  4121. this._count = 0;
  4122. this._data = {};
  4123. }
  4124. /**
  4125. * Get a value based from its key
  4126. * @param key the given key to get the matching value from
  4127. * @return the value if found, otherwise undefined is returned
  4128. */
  4129. StringDictionary.prototype.get = function (key) {
  4130. var val = this._data[key];
  4131. if (val !== undefined) {
  4132. return val;
  4133. }
  4134. return undefined;
  4135. };
  4136. /**
  4137. * Get a value from its key or add it if it doesn't exist.
  4138. * This method will ensure you that a given key/data will be present in the dictionary.
  4139. * @param key the given key to get the matching value from
  4140. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4141. * The factory will only be invoked if there's no data for the given key.
  4142. * @return the value corresponding to the key.
  4143. */
  4144. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4145. var val = this.get(key);
  4146. if (val !== undefined) {
  4147. return val;
  4148. }
  4149. val = factory(key);
  4150. if (val) {
  4151. this.add(key, val);
  4152. }
  4153. return val;
  4154. };
  4155. /**
  4156. * Get a value from its key if present in the dictionary otherwise add it
  4157. * @param key the key to get the value from
  4158. * @param val if there's no such key/value pair in the dictionary add it with this value
  4159. * @return the value corresponding to the key
  4160. */
  4161. StringDictionary.prototype.getOrAdd = function (key, val) {
  4162. var curVal = this.get(key);
  4163. if (curVal !== undefined) {
  4164. return curVal;
  4165. }
  4166. this.add(key, val);
  4167. return val;
  4168. };
  4169. /**
  4170. * Check if there's a given key in the dictionary
  4171. * @param key the key to check for
  4172. * @return true if the key is present, false otherwise
  4173. */
  4174. StringDictionary.prototype.contains = function (key) {
  4175. return this._data[key] !== undefined;
  4176. };
  4177. /**
  4178. * Add a new key and its corresponding value
  4179. * @param key the key to add
  4180. * @param value the value corresponding to the key
  4181. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4182. */
  4183. StringDictionary.prototype.add = function (key, value) {
  4184. if (this._data[key] !== undefined) {
  4185. return false;
  4186. }
  4187. this._data[key] = value;
  4188. ++this._count;
  4189. return true;
  4190. };
  4191. StringDictionary.prototype.set = function (key, value) {
  4192. if (this._data[key] === undefined) {
  4193. return false;
  4194. }
  4195. this._data[key] = value;
  4196. return true;
  4197. };
  4198. /**
  4199. * Remove a key/value from the dictionary.
  4200. * @param key the key to remove
  4201. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4202. */
  4203. StringDictionary.prototype.remove = function (key) {
  4204. if (this.contains(key)) {
  4205. delete this._data[key];
  4206. --this._count;
  4207. return true;
  4208. }
  4209. return false;
  4210. };
  4211. /**
  4212. * Clear the whole content of the dictionary
  4213. */
  4214. StringDictionary.prototype.clear = function () {
  4215. this._data = {};
  4216. this._count = 0;
  4217. };
  4218. Object.defineProperty(StringDictionary.prototype, "count", {
  4219. get: function () {
  4220. return this._count;
  4221. },
  4222. enumerable: true,
  4223. configurable: true
  4224. });
  4225. /**
  4226. * Execute a callback on each key/val of the dictionary.
  4227. * Note that you can remove any element in this dictionary in the callback implementation
  4228. * @param callback the callback to execute on a given key/value pair
  4229. */
  4230. StringDictionary.prototype.forEach = function (callback) {
  4231. for (var cur in this._data) {
  4232. var val = this._data[cur];
  4233. callback(cur, val);
  4234. }
  4235. };
  4236. /**
  4237. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4238. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4239. * Note that you can remove any element in this dictionary in the callback implementation
  4240. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4241. */
  4242. StringDictionary.prototype.first = function (callback) {
  4243. for (var cur in this._data) {
  4244. var val = this._data[cur];
  4245. var res = callback(cur, val);
  4246. if (res) {
  4247. return res;
  4248. }
  4249. }
  4250. return null;
  4251. };
  4252. return StringDictionary;
  4253. })();
  4254. BABYLON.StringDictionary = StringDictionary;
  4255. })(BABYLON || (BABYLON = {}));
  4256. var BABYLON;
  4257. (function (BABYLON) {
  4258. // Screenshots
  4259. var screenshotCanvas;
  4260. var cloneValue = function (source, destinationObject) {
  4261. if (!source)
  4262. return null;
  4263. if (source instanceof BABYLON.Mesh) {
  4264. return null;
  4265. }
  4266. if (source instanceof BABYLON.SubMesh) {
  4267. return source.clone(destinationObject);
  4268. }
  4269. else if (source.clone) {
  4270. return source.clone();
  4271. }
  4272. return null;
  4273. };
  4274. var Tools = (function () {
  4275. function Tools() {
  4276. }
  4277. Tools.Instantiate = function (className) {
  4278. var arr = className.split(".");
  4279. var fn = (window || this);
  4280. for (var i = 0, len = arr.length; i < len; i++) {
  4281. fn = fn[arr[i]];
  4282. }
  4283. if (typeof fn !== "function") {
  4284. return null;
  4285. }
  4286. return fn;
  4287. };
  4288. Tools.SetImmediate = function (action) {
  4289. if (window.setImmediate) {
  4290. window.setImmediate(action);
  4291. }
  4292. else {
  4293. setTimeout(action, 1);
  4294. }
  4295. };
  4296. Tools.IsExponentOfTwo = function (value) {
  4297. var count = 1;
  4298. do {
  4299. count *= 2;
  4300. } while (count < value);
  4301. return count === value;
  4302. };
  4303. Tools.GetExponentOfTwo = function (value, max) {
  4304. var count = 1;
  4305. do {
  4306. count *= 2;
  4307. } while (count < value);
  4308. if (count > max)
  4309. count = max;
  4310. return count;
  4311. };
  4312. Tools.GetFilename = function (path) {
  4313. var index = path.lastIndexOf("/");
  4314. if (index < 0)
  4315. return path;
  4316. return path.substring(index + 1);
  4317. };
  4318. Tools.GetDOMTextContent = function (element) {
  4319. var result = "";
  4320. var child = element.firstChild;
  4321. while (child) {
  4322. if (child.nodeType === 3) {
  4323. result += child.textContent;
  4324. }
  4325. child = child.nextSibling;
  4326. }
  4327. return result;
  4328. };
  4329. Tools.ToDegrees = function (angle) {
  4330. return angle * 180 / Math.PI;
  4331. };
  4332. Tools.ToRadians = function (angle) {
  4333. return angle * Math.PI / 180;
  4334. };
  4335. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4336. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4337. var output = "";
  4338. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4339. var i = 0;
  4340. var bytes = new Uint8Array(buffer);
  4341. while (i < bytes.length) {
  4342. chr1 = bytes[i++];
  4343. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4344. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4345. enc1 = chr1 >> 2;
  4346. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4347. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4348. enc4 = chr3 & 63;
  4349. if (isNaN(chr2)) {
  4350. enc3 = enc4 = 64;
  4351. }
  4352. else if (isNaN(chr3)) {
  4353. enc4 = 64;
  4354. }
  4355. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4356. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4357. }
  4358. return "data:image/png;base64," + output;
  4359. };
  4360. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4361. if (bias === void 0) { bias = null; }
  4362. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4363. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4364. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4365. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4366. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4367. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4368. }
  4369. if (bias) {
  4370. minimum.x -= minimum.x * bias.x + bias.y;
  4371. minimum.y -= minimum.y * bias.x + bias.y;
  4372. minimum.z -= minimum.z * bias.x + bias.y;
  4373. maximum.x += maximum.x * bias.x + bias.y;
  4374. maximum.y += maximum.y * bias.x + bias.y;
  4375. maximum.z += maximum.z * bias.x + bias.y;
  4376. }
  4377. return {
  4378. minimum: minimum,
  4379. maximum: maximum
  4380. };
  4381. };
  4382. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4383. if (bias === void 0) { bias = null; }
  4384. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4385. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4386. for (var index = start; index < start + count; index++) {
  4387. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4388. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4389. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4390. }
  4391. if (bias) {
  4392. minimum.x -= minimum.x * bias.x + bias.y;
  4393. minimum.y -= minimum.y * bias.x + bias.y;
  4394. minimum.z -= minimum.z * bias.x + bias.y;
  4395. maximum.x += maximum.x * bias.x + bias.y;
  4396. maximum.y += maximum.y * bias.x + bias.y;
  4397. maximum.z += maximum.z * bias.x + bias.y;
  4398. }
  4399. return {
  4400. minimum: minimum,
  4401. maximum: maximum
  4402. };
  4403. };
  4404. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4405. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4406. return undefined;
  4407. return Array.isArray(obj) ? obj : [obj];
  4408. };
  4409. // Misc.
  4410. Tools.GetPointerPrefix = function () {
  4411. var eventPrefix = "pointer";
  4412. // Check if pointer events are supported
  4413. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4414. eventPrefix = "mouse";
  4415. }
  4416. return eventPrefix;
  4417. };
  4418. Tools.QueueNewFrame = function (func) {
  4419. if (window.requestAnimationFrame)
  4420. window.requestAnimationFrame(func);
  4421. else if (window.msRequestAnimationFrame)
  4422. window.msRequestAnimationFrame(func);
  4423. else if (window.webkitRequestAnimationFrame)
  4424. window.webkitRequestAnimationFrame(func);
  4425. else if (window.mozRequestAnimationFrame)
  4426. window.mozRequestAnimationFrame(func);
  4427. else if (window.oRequestAnimationFrame)
  4428. window.oRequestAnimationFrame(func);
  4429. else {
  4430. window.setTimeout(func, 16);
  4431. }
  4432. };
  4433. Tools.RequestFullscreen = function (element) {
  4434. if (element.requestFullscreen)
  4435. element.requestFullscreen();
  4436. else if (element.msRequestFullscreen)
  4437. element.msRequestFullscreen();
  4438. else if (element.webkitRequestFullscreen)
  4439. element.webkitRequestFullscreen();
  4440. else if (element.mozRequestFullScreen)
  4441. element.mozRequestFullScreen();
  4442. };
  4443. Tools.ExitFullscreen = function () {
  4444. if (document.exitFullscreen) {
  4445. document.exitFullscreen();
  4446. }
  4447. else if (document.mozCancelFullScreen) {
  4448. document.mozCancelFullScreen();
  4449. }
  4450. else if (document.webkitCancelFullScreen) {
  4451. document.webkitCancelFullScreen();
  4452. }
  4453. else if (document.msCancelFullScreen) {
  4454. document.msCancelFullScreen();
  4455. }
  4456. };
  4457. // External files
  4458. Tools.CleanUrl = function (url) {
  4459. url = url.replace(/#/mg, "%23");
  4460. return url;
  4461. };
  4462. Tools.LoadImage = function (url, onload, onerror, database) {
  4463. if (url instanceof ArrayBuffer) {
  4464. url = Tools.EncodeArrayBufferTobase64(url);
  4465. }
  4466. url = Tools.CleanUrl(url);
  4467. var img = new Image();
  4468. if (url.substr(0, 5) !== "data:") {
  4469. if (Tools.CorsBehavior) {
  4470. switch (typeof (Tools.CorsBehavior)) {
  4471. case "function":
  4472. var result = Tools.CorsBehavior(url);
  4473. if (result) {
  4474. img.crossOrigin = result;
  4475. }
  4476. break;
  4477. case "string":
  4478. default:
  4479. img.crossOrigin = Tools.CorsBehavior;
  4480. break;
  4481. }
  4482. }
  4483. }
  4484. img.onload = function () {
  4485. onload(img);
  4486. };
  4487. img.onerror = function (err) {
  4488. Tools.Error("Error while trying to load texture: " + url);
  4489. if (Tools.UseFallbackTexture) {
  4490. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4491. onload(img);
  4492. }
  4493. else {
  4494. onerror();
  4495. }
  4496. };
  4497. var noIndexedDB = function () {
  4498. img.src = url;
  4499. };
  4500. var loadFromIndexedDB = function () {
  4501. database.loadImageFromDB(url, img);
  4502. };
  4503. //ANY database to do!
  4504. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4505. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4506. }
  4507. else {
  4508. if (url.indexOf("file:") === -1) {
  4509. noIndexedDB();
  4510. }
  4511. else {
  4512. try {
  4513. var textureName = url.substring(5).toLowerCase();
  4514. var blobURL;
  4515. try {
  4516. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4517. }
  4518. catch (ex) {
  4519. // Chrome doesn't support oneTimeOnly parameter
  4520. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4521. }
  4522. img.src = blobURL;
  4523. }
  4524. catch (e) {
  4525. img.src = null;
  4526. }
  4527. }
  4528. }
  4529. return img;
  4530. };
  4531. //ANY
  4532. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4533. url = Tools.CleanUrl(url);
  4534. var noIndexedDB = function () {
  4535. var request = new XMLHttpRequest();
  4536. var loadUrl = Tools.BaseUrl + url;
  4537. request.open('GET', loadUrl, true);
  4538. if (useArrayBuffer) {
  4539. request.responseType = "arraybuffer";
  4540. }
  4541. request.onprogress = progressCallBack;
  4542. request.onreadystatechange = function () {
  4543. if (request.readyState === 4) {
  4544. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4545. callback(!useArrayBuffer ? request.responseText : request.response);
  4546. }
  4547. else {
  4548. if (onError) {
  4549. onError();
  4550. }
  4551. else {
  4552. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4553. }
  4554. }
  4555. }
  4556. };
  4557. request.send(null);
  4558. };
  4559. var loadFromIndexedDB = function () {
  4560. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4561. };
  4562. if (url.indexOf("file:") !== -1) {
  4563. var fileName = url.substring(5).toLowerCase();
  4564. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4565. }
  4566. else {
  4567. // Caching all files
  4568. if (database && database.enableSceneOffline) {
  4569. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4570. }
  4571. else {
  4572. noIndexedDB();
  4573. }
  4574. }
  4575. };
  4576. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4577. var reader = new FileReader();
  4578. reader.onload = function (e) {
  4579. //target doesn't have result from ts 1.3
  4580. callback(e.target['result']);
  4581. };
  4582. reader.onprogress = progressCallback;
  4583. reader.readAsDataURL(fileToLoad);
  4584. };
  4585. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4586. var reader = new FileReader();
  4587. reader.onerror = function (e) {
  4588. Tools.Log("Error while reading file: " + fileToLoad.name);
  4589. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4590. };
  4591. reader.onload = function (e) {
  4592. //target doesn't have result from ts 1.3
  4593. callback(e.target['result']);
  4594. };
  4595. reader.onprogress = progressCallBack;
  4596. if (!useArrayBuffer) {
  4597. // Asynchronous read
  4598. reader.readAsText(fileToLoad);
  4599. }
  4600. else {
  4601. reader.readAsArrayBuffer(fileToLoad);
  4602. }
  4603. };
  4604. //returns a downloadable url to a file content.
  4605. Tools.FileAsURL = function (content) {
  4606. var fileBlob = new Blob([content]);
  4607. var url = window.URL || window.webkitURL;
  4608. var link = url.createObjectURL(fileBlob);
  4609. return link;
  4610. };
  4611. // Misc.
  4612. Tools.Format = function (value, decimals) {
  4613. if (decimals === void 0) { decimals = 2; }
  4614. return value.toFixed(decimals);
  4615. };
  4616. Tools.CheckExtends = function (v, min, max) {
  4617. if (v.x < min.x)
  4618. min.x = v.x;
  4619. if (v.y < min.y)
  4620. min.y = v.y;
  4621. if (v.z < min.z)
  4622. min.z = v.z;
  4623. if (v.x > max.x)
  4624. max.x = v.x;
  4625. if (v.y > max.y)
  4626. max.y = v.y;
  4627. if (v.z > max.z)
  4628. max.z = v.z;
  4629. };
  4630. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4631. for (var prop in source) {
  4632. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4633. continue;
  4634. }
  4635. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4636. continue;
  4637. }
  4638. var sourceValue = source[prop];
  4639. var typeOfSourceValue = typeof sourceValue;
  4640. if (typeOfSourceValue === "function") {
  4641. continue;
  4642. }
  4643. if (typeOfSourceValue === "object") {
  4644. if (sourceValue instanceof Array) {
  4645. destination[prop] = [];
  4646. if (sourceValue.length > 0) {
  4647. if (typeof sourceValue[0] == "object") {
  4648. for (var index = 0; index < sourceValue.length; index++) {
  4649. var clonedValue = cloneValue(sourceValue[index], destination);
  4650. if (destination[prop].indexOf(clonedValue) === -1) {
  4651. destination[prop].push(clonedValue);
  4652. }
  4653. }
  4654. }
  4655. else {
  4656. destination[prop] = sourceValue.slice(0);
  4657. }
  4658. }
  4659. }
  4660. else {
  4661. destination[prop] = cloneValue(sourceValue, destination);
  4662. }
  4663. }
  4664. else {
  4665. destination[prop] = sourceValue;
  4666. }
  4667. }
  4668. };
  4669. Tools.IsEmpty = function (obj) {
  4670. for (var i in obj) {
  4671. return false;
  4672. }
  4673. return true;
  4674. };
  4675. Tools.RegisterTopRootEvents = function (events) {
  4676. for (var index = 0; index < events.length; index++) {
  4677. var event = events[index];
  4678. window.addEventListener(event.name, event.handler, false);
  4679. try {
  4680. if (window.parent) {
  4681. window.parent.addEventListener(event.name, event.handler, false);
  4682. }
  4683. }
  4684. catch (e) {
  4685. }
  4686. }
  4687. };
  4688. Tools.UnregisterTopRootEvents = function (events) {
  4689. for (var index = 0; index < events.length; index++) {
  4690. var event = events[index];
  4691. window.removeEventListener(event.name, event.handler);
  4692. try {
  4693. if (window.parent) {
  4694. window.parent.removeEventListener(event.name, event.handler);
  4695. }
  4696. }
  4697. catch (e) {
  4698. }
  4699. }
  4700. };
  4701. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4702. // Read the contents of the framebuffer
  4703. var numberOfChannelsByLine = width * 4;
  4704. var halfHeight = height / 2;
  4705. //Reading datas from WebGL
  4706. var data = engine.readPixels(0, 0, width, height);
  4707. //To flip image on Y axis.
  4708. for (var i = 0; i < halfHeight; i++) {
  4709. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4710. var currentCell = j + i * numberOfChannelsByLine;
  4711. var targetLine = height - i - 1;
  4712. var targetCell = j + targetLine * numberOfChannelsByLine;
  4713. var temp = data[currentCell];
  4714. data[currentCell] = data[targetCell];
  4715. data[targetCell] = temp;
  4716. }
  4717. }
  4718. // Create a 2D canvas to store the result
  4719. if (!screenshotCanvas) {
  4720. screenshotCanvas = document.createElement('canvas');
  4721. }
  4722. screenshotCanvas.width = width;
  4723. screenshotCanvas.height = height;
  4724. var context = screenshotCanvas.getContext('2d');
  4725. // Copy the pixels to a 2D canvas
  4726. var imageData = context.createImageData(width, height);
  4727. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4728. var castData = imageData.data;
  4729. castData.set(data);
  4730. context.putImageData(imageData, 0, 0);
  4731. var base64Image = screenshotCanvas.toDataURL();
  4732. if (successCallback) {
  4733. successCallback(base64Image);
  4734. }
  4735. else {
  4736. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4737. if (("download" in document.createElement("a"))) {
  4738. var a = window.document.createElement("a");
  4739. a.href = base64Image;
  4740. var date = new Date();
  4741. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4742. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4743. window.document.body.appendChild(a);
  4744. a.addEventListener("click", function () {
  4745. a.parentElement.removeChild(a);
  4746. });
  4747. a.click();
  4748. }
  4749. else {
  4750. var newWindow = window.open("");
  4751. var img = newWindow.document.createElement("img");
  4752. img.src = base64Image;
  4753. newWindow.document.body.appendChild(img);
  4754. }
  4755. }
  4756. };
  4757. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4758. var width;
  4759. var height;
  4760. //If a precision value is specified
  4761. if (size.precision) {
  4762. width = Math.round(engine.getRenderWidth() * size.precision);
  4763. height = Math.round(width / engine.getAspectRatio(camera));
  4764. size = { width: width, height: height };
  4765. }
  4766. else if (size.width && size.height) {
  4767. width = size.width;
  4768. height = size.height;
  4769. }
  4770. else if (size.width && !size.height) {
  4771. width = size.width;
  4772. height = Math.round(width / engine.getAspectRatio(camera));
  4773. size = { width: width, height: height };
  4774. }
  4775. else if (size.height && !size.width) {
  4776. height = size.height;
  4777. width = Math.round(height * engine.getAspectRatio(camera));
  4778. size = { width: width, height: height };
  4779. }
  4780. else if (!isNaN(size)) {
  4781. height = size;
  4782. width = size;
  4783. }
  4784. else {
  4785. Tools.Error("Invalid 'size' parameter !");
  4786. return;
  4787. }
  4788. var scene = camera.getScene();
  4789. var previousCamera = null;
  4790. if (scene.activeCamera !== camera) {
  4791. previousCamera = scene.activeCamera;
  4792. scene.activeCamera = camera;
  4793. }
  4794. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4795. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4796. texture.renderList = scene.meshes;
  4797. texture.onAfterRenderObservable.add(function () {
  4798. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4799. });
  4800. scene.incrementRenderId();
  4801. texture.render(true);
  4802. texture.dispose();
  4803. if (previousCamera) {
  4804. scene.activeCamera = previousCamera;
  4805. }
  4806. camera.getProjectionMatrix(true); // Force cache refresh;
  4807. };
  4808. // XHR response validator for local file scenario
  4809. Tools.ValidateXHRData = function (xhr, dataType) {
  4810. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4811. if (dataType === void 0) { dataType = 7; }
  4812. try {
  4813. if (dataType & 1) {
  4814. if (xhr.responseText && xhr.responseText.length > 0) {
  4815. return true;
  4816. }
  4817. else if (dataType === 1) {
  4818. return false;
  4819. }
  4820. }
  4821. if (dataType & 2) {
  4822. // Check header width and height since there is no "TGA" magic number
  4823. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4824. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4825. return true;
  4826. }
  4827. else if (dataType === 2) {
  4828. return false;
  4829. }
  4830. }
  4831. if (dataType & 4) {
  4832. // Check for the "DDS" magic number
  4833. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4834. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4835. return true;
  4836. }
  4837. else {
  4838. return false;
  4839. }
  4840. }
  4841. }
  4842. catch (e) {
  4843. }
  4844. return false;
  4845. };
  4846. Object.defineProperty(Tools, "NoneLogLevel", {
  4847. get: function () {
  4848. return Tools._NoneLogLevel;
  4849. },
  4850. enumerable: true,
  4851. configurable: true
  4852. });
  4853. Object.defineProperty(Tools, "MessageLogLevel", {
  4854. get: function () {
  4855. return Tools._MessageLogLevel;
  4856. },
  4857. enumerable: true,
  4858. configurable: true
  4859. });
  4860. Object.defineProperty(Tools, "WarningLogLevel", {
  4861. get: function () {
  4862. return Tools._WarningLogLevel;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. Object.defineProperty(Tools, "ErrorLogLevel", {
  4868. get: function () {
  4869. return Tools._ErrorLogLevel;
  4870. },
  4871. enumerable: true,
  4872. configurable: true
  4873. });
  4874. Object.defineProperty(Tools, "AllLogLevel", {
  4875. get: function () {
  4876. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4877. },
  4878. enumerable: true,
  4879. configurable: true
  4880. });
  4881. Tools._AddLogEntry = function (entry) {
  4882. Tools._LogCache = entry + Tools._LogCache;
  4883. if (Tools.OnNewCacheEntry) {
  4884. Tools.OnNewCacheEntry(entry);
  4885. }
  4886. };
  4887. Tools._FormatMessage = function (message) {
  4888. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4889. var date = new Date();
  4890. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4891. };
  4892. Tools._LogDisabled = function (message) {
  4893. // nothing to do
  4894. };
  4895. Tools._LogEnabled = function (message) {
  4896. var formattedMessage = Tools._FormatMessage(message);
  4897. console.log("BJS - " + formattedMessage);
  4898. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4899. Tools._AddLogEntry(entry);
  4900. };
  4901. Tools._WarnDisabled = function (message) {
  4902. // nothing to do
  4903. };
  4904. Tools._WarnEnabled = function (message) {
  4905. var formattedMessage = Tools._FormatMessage(message);
  4906. console.warn("BJS - " + formattedMessage);
  4907. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4908. Tools._AddLogEntry(entry);
  4909. };
  4910. Tools._ErrorDisabled = function (message) {
  4911. // nothing to do
  4912. };
  4913. Tools._ErrorEnabled = function (message) {
  4914. Tools.errorsCount++;
  4915. var formattedMessage = Tools._FormatMessage(message);
  4916. console.error("BJS - " + formattedMessage);
  4917. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4918. Tools._AddLogEntry(entry);
  4919. };
  4920. Object.defineProperty(Tools, "LogCache", {
  4921. get: function () {
  4922. return Tools._LogCache;
  4923. },
  4924. enumerable: true,
  4925. configurable: true
  4926. });
  4927. Tools.ClearLogCache = function () {
  4928. Tools._LogCache = "";
  4929. Tools.errorsCount = 0;
  4930. };
  4931. Object.defineProperty(Tools, "LogLevels", {
  4932. set: function (level) {
  4933. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4934. Tools.Log = Tools._LogEnabled;
  4935. }
  4936. else {
  4937. Tools.Log = Tools._LogDisabled;
  4938. }
  4939. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4940. Tools.Warn = Tools._WarnEnabled;
  4941. }
  4942. else {
  4943. Tools.Warn = Tools._WarnDisabled;
  4944. }
  4945. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4946. Tools.Error = Tools._ErrorEnabled;
  4947. }
  4948. else {
  4949. Tools.Error = Tools._ErrorDisabled;
  4950. }
  4951. },
  4952. enumerable: true,
  4953. configurable: true
  4954. });
  4955. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4956. get: function () {
  4957. return Tools._PerformanceNoneLogLevel;
  4958. },
  4959. enumerable: true,
  4960. configurable: true
  4961. });
  4962. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4963. get: function () {
  4964. return Tools._PerformanceUserMarkLogLevel;
  4965. },
  4966. enumerable: true,
  4967. configurable: true
  4968. });
  4969. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4970. get: function () {
  4971. return Tools._PerformanceConsoleLogLevel;
  4972. },
  4973. enumerable: true,
  4974. configurable: true
  4975. });
  4976. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4977. set: function (level) {
  4978. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4979. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4980. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4981. return;
  4982. }
  4983. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4984. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4985. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4986. return;
  4987. }
  4988. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4989. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4990. },
  4991. enumerable: true,
  4992. configurable: true
  4993. });
  4994. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4995. };
  4996. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4997. };
  4998. Tools._StartUserMark = function (counterName, condition) {
  4999. if (condition === void 0) { condition = true; }
  5000. if (!condition || !Tools._performance.mark) {
  5001. return;
  5002. }
  5003. Tools._performance.mark(counterName + "-Begin");
  5004. };
  5005. Tools._EndUserMark = function (counterName, condition) {
  5006. if (condition === void 0) { condition = true; }
  5007. if (!condition || !Tools._performance.mark) {
  5008. return;
  5009. }
  5010. Tools._performance.mark(counterName + "-End");
  5011. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5012. };
  5013. Tools._StartPerformanceConsole = function (counterName, condition) {
  5014. if (condition === void 0) { condition = true; }
  5015. if (!condition) {
  5016. return;
  5017. }
  5018. Tools._StartUserMark(counterName, condition);
  5019. if (console.time) {
  5020. console.time(counterName);
  5021. }
  5022. };
  5023. Tools._EndPerformanceConsole = function (counterName, condition) {
  5024. if (condition === void 0) { condition = true; }
  5025. if (!condition) {
  5026. return;
  5027. }
  5028. Tools._EndUserMark(counterName, condition);
  5029. if (console.time) {
  5030. console.timeEnd(counterName);
  5031. }
  5032. };
  5033. Object.defineProperty(Tools, "Now", {
  5034. get: function () {
  5035. if (window.performance && window.performance.now) {
  5036. return window.performance.now();
  5037. }
  5038. return new Date().getTime();
  5039. },
  5040. enumerable: true,
  5041. configurable: true
  5042. });
  5043. /**
  5044. * This method will return the name of the class used to create the instance of the given object.
  5045. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5046. * @param object the object to get the class name from
  5047. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5048. */
  5049. Tools.getClassName = function (object, isType) {
  5050. if (isType === void 0) { isType = false; }
  5051. var name = null;
  5052. if (object instanceof Object) {
  5053. var classObj = isType ? object : Object.getPrototypeOf(object);
  5054. name = classObj.constructor["__bjsclassName__"];
  5055. }
  5056. if (!name) {
  5057. name = typeof object;
  5058. }
  5059. return name;
  5060. };
  5061. Tools.first = function (array, predicate) {
  5062. for (var _i = 0; _i < array.length; _i++) {
  5063. var el = array[_i];
  5064. if (predicate(el)) {
  5065. return el;
  5066. }
  5067. }
  5068. };
  5069. Tools.BaseUrl = "";
  5070. Tools.CorsBehavior = "anonymous";
  5071. Tools.UseFallbackTexture = true;
  5072. // Logs
  5073. Tools._NoneLogLevel = 0;
  5074. Tools._MessageLogLevel = 1;
  5075. Tools._WarningLogLevel = 2;
  5076. Tools._ErrorLogLevel = 4;
  5077. Tools._LogCache = "";
  5078. Tools.errorsCount = 0;
  5079. Tools.Log = Tools._LogEnabled;
  5080. Tools.Warn = Tools._WarnEnabled;
  5081. Tools.Error = Tools._ErrorEnabled;
  5082. // Performances
  5083. Tools._PerformanceNoneLogLevel = 0;
  5084. Tools._PerformanceUserMarkLogLevel = 1;
  5085. Tools._PerformanceConsoleLogLevel = 2;
  5086. Tools._performance = window.performance;
  5087. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5088. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5089. return Tools;
  5090. })();
  5091. BABYLON.Tools = Tools;
  5092. /**
  5093. * Use this className as a decorator on a given class definition to add it a name.
  5094. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5095. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5096. * @param name
  5097. */
  5098. function className(name) {
  5099. return function (target) {
  5100. target["__bjsclassName__"] = name;
  5101. };
  5102. }
  5103. BABYLON.className = className;
  5104. /**
  5105. * An implementation of a loop for asynchronous functions.
  5106. */
  5107. var AsyncLoop = (function () {
  5108. /**
  5109. * Constroctor.
  5110. * @param iterations the number of iterations.
  5111. * @param _fn the function to run each iteration
  5112. * @param _successCallback the callback that will be called upon succesful execution
  5113. * @param offset starting offset.
  5114. */
  5115. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5116. if (offset === void 0) { offset = 0; }
  5117. this.iterations = iterations;
  5118. this._fn = _fn;
  5119. this._successCallback = _successCallback;
  5120. this.index = offset - 1;
  5121. this._done = false;
  5122. }
  5123. /**
  5124. * Execute the next iteration. Must be called after the last iteration was finished.
  5125. */
  5126. AsyncLoop.prototype.executeNext = function () {
  5127. if (!this._done) {
  5128. if (this.index + 1 < this.iterations) {
  5129. ++this.index;
  5130. this._fn(this);
  5131. }
  5132. else {
  5133. this.breakLoop();
  5134. }
  5135. }
  5136. };
  5137. /**
  5138. * Break the loop and run the success callback.
  5139. */
  5140. AsyncLoop.prototype.breakLoop = function () {
  5141. this._done = true;
  5142. this._successCallback();
  5143. };
  5144. /**
  5145. * Helper function
  5146. */
  5147. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5148. if (offset === void 0) { offset = 0; }
  5149. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5150. loop.executeNext();
  5151. return loop;
  5152. };
  5153. /**
  5154. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5155. * @param iterations total number of iterations
  5156. * @param syncedIterations number of synchronous iterations in each async iteration.
  5157. * @param fn the function to call each iteration.
  5158. * @param callback a success call back that will be called when iterating stops.
  5159. * @param breakFunction a break condition (optional)
  5160. * @param timeout timeout settings for the setTimeout function. default - 0.
  5161. * @constructor
  5162. */
  5163. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5164. if (timeout === void 0) { timeout = 0; }
  5165. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5166. if (breakFunction && breakFunction())
  5167. loop.breakLoop();
  5168. else {
  5169. setTimeout(function () {
  5170. for (var i = 0; i < syncedIterations; ++i) {
  5171. var iteration = (loop.index * syncedIterations) + i;
  5172. if (iteration >= iterations)
  5173. break;
  5174. fn(iteration);
  5175. if (breakFunction && breakFunction()) {
  5176. loop.breakLoop();
  5177. break;
  5178. }
  5179. }
  5180. loop.executeNext();
  5181. }, timeout);
  5182. }
  5183. }, callback);
  5184. };
  5185. return AsyncLoop;
  5186. })();
  5187. BABYLON.AsyncLoop = AsyncLoop;
  5188. })(BABYLON || (BABYLON = {}));
  5189. var BABYLON;
  5190. (function (BABYLON) {
  5191. var Internals;
  5192. (function (Internals) {
  5193. var _AlphaState = (function () {
  5194. function _AlphaState() {
  5195. this._isAlphaBlendDirty = false;
  5196. this._isBlendFunctionParametersDirty = false;
  5197. this._alphaBlend = false;
  5198. this._blendFunctionParameters = new Array(4);
  5199. }
  5200. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5201. get: function () {
  5202. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5203. },
  5204. enumerable: true,
  5205. configurable: true
  5206. });
  5207. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5208. get: function () {
  5209. return this._alphaBlend;
  5210. },
  5211. set: function (value) {
  5212. if (this._alphaBlend === value) {
  5213. return;
  5214. }
  5215. this._alphaBlend = value;
  5216. this._isAlphaBlendDirty = true;
  5217. },
  5218. enumerable: true,
  5219. configurable: true
  5220. });
  5221. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5222. if (this._blendFunctionParameters[0] === value0 &&
  5223. this._blendFunctionParameters[1] === value1 &&
  5224. this._blendFunctionParameters[2] === value2 &&
  5225. this._blendFunctionParameters[3] === value3) {
  5226. return;
  5227. }
  5228. this._blendFunctionParameters[0] = value0;
  5229. this._blendFunctionParameters[1] = value1;
  5230. this._blendFunctionParameters[2] = value2;
  5231. this._blendFunctionParameters[3] = value3;
  5232. this._isBlendFunctionParametersDirty = true;
  5233. };
  5234. _AlphaState.prototype.reset = function () {
  5235. this._alphaBlend = false;
  5236. this._blendFunctionParameters[0] = null;
  5237. this._blendFunctionParameters[1] = null;
  5238. this._blendFunctionParameters[2] = null;
  5239. this._blendFunctionParameters[3] = null;
  5240. this._isAlphaBlendDirty = true;
  5241. this._isBlendFunctionParametersDirty = false;
  5242. };
  5243. _AlphaState.prototype.apply = function (gl) {
  5244. if (!this.isDirty) {
  5245. return;
  5246. }
  5247. // Alpha blend
  5248. if (this._isAlphaBlendDirty) {
  5249. if (this._alphaBlend) {
  5250. gl.enable(gl.BLEND);
  5251. }
  5252. else {
  5253. gl.disable(gl.BLEND);
  5254. }
  5255. this._isAlphaBlendDirty = false;
  5256. }
  5257. // Alpha function
  5258. if (this._isBlendFunctionParametersDirty) {
  5259. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5260. this._isBlendFunctionParametersDirty = false;
  5261. }
  5262. };
  5263. return _AlphaState;
  5264. })();
  5265. Internals._AlphaState = _AlphaState;
  5266. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5267. })(BABYLON || (BABYLON = {}));
  5268. var BABYLON;
  5269. (function (BABYLON) {
  5270. var Internals;
  5271. (function (Internals) {
  5272. var _DepthCullingState = (function () {
  5273. function _DepthCullingState() {
  5274. this._isDepthTestDirty = false;
  5275. this._isDepthMaskDirty = false;
  5276. this._isDepthFuncDirty = false;
  5277. this._isCullFaceDirty = false;
  5278. this._isCullDirty = false;
  5279. this._isZOffsetDirty = false;
  5280. }
  5281. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5282. get: function () {
  5283. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5284. },
  5285. enumerable: true,
  5286. configurable: true
  5287. });
  5288. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5289. get: function () {
  5290. return this._zOffset;
  5291. },
  5292. set: function (value) {
  5293. if (this._zOffset === value) {
  5294. return;
  5295. }
  5296. this._zOffset = value;
  5297. this._isZOffsetDirty = true;
  5298. },
  5299. enumerable: true,
  5300. configurable: true
  5301. });
  5302. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5303. get: function () {
  5304. return this._cullFace;
  5305. },
  5306. set: function (value) {
  5307. if (this._cullFace === value) {
  5308. return;
  5309. }
  5310. this._cullFace = value;
  5311. this._isCullFaceDirty = true;
  5312. },
  5313. enumerable: true,
  5314. configurable: true
  5315. });
  5316. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5317. get: function () {
  5318. return this._cull;
  5319. },
  5320. set: function (value) {
  5321. if (this._cull === value) {
  5322. return;
  5323. }
  5324. this._cull = value;
  5325. this._isCullDirty = true;
  5326. },
  5327. enumerable: true,
  5328. configurable: true
  5329. });
  5330. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5331. get: function () {
  5332. return this._depthFunc;
  5333. },
  5334. set: function (value) {
  5335. if (this._depthFunc === value) {
  5336. return;
  5337. }
  5338. this._depthFunc = value;
  5339. this._isDepthFuncDirty = true;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5345. get: function () {
  5346. return this._depthMask;
  5347. },
  5348. set: function (value) {
  5349. if (this._depthMask === value) {
  5350. return;
  5351. }
  5352. this._depthMask = value;
  5353. this._isDepthMaskDirty = true;
  5354. },
  5355. enumerable: true,
  5356. configurable: true
  5357. });
  5358. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5359. get: function () {
  5360. return this._depthTest;
  5361. },
  5362. set: function (value) {
  5363. if (this._depthTest === value) {
  5364. return;
  5365. }
  5366. this._depthTest = value;
  5367. this._isDepthTestDirty = true;
  5368. },
  5369. enumerable: true,
  5370. configurable: true
  5371. });
  5372. _DepthCullingState.prototype.reset = function () {
  5373. this._depthMask = true;
  5374. this._depthTest = true;
  5375. this._depthFunc = null;
  5376. this._cull = null;
  5377. this._cullFace = null;
  5378. this._zOffset = 0;
  5379. this._isDepthTestDirty = true;
  5380. this._isDepthMaskDirty = true;
  5381. this._isDepthFuncDirty = false;
  5382. this._isCullFaceDirty = false;
  5383. this._isCullDirty = false;
  5384. this._isZOffsetDirty = false;
  5385. };
  5386. _DepthCullingState.prototype.apply = function (gl) {
  5387. if (!this.isDirty) {
  5388. return;
  5389. }
  5390. // Cull
  5391. if (this._isCullDirty) {
  5392. if (this.cull) {
  5393. gl.enable(gl.CULL_FACE);
  5394. }
  5395. else {
  5396. gl.disable(gl.CULL_FACE);
  5397. }
  5398. this._isCullDirty = false;
  5399. }
  5400. // Cull face
  5401. if (this._isCullFaceDirty) {
  5402. gl.cullFace(this.cullFace);
  5403. this._isCullFaceDirty = false;
  5404. }
  5405. // Depth mask
  5406. if (this._isDepthMaskDirty) {
  5407. gl.depthMask(this.depthMask);
  5408. this._isDepthMaskDirty = false;
  5409. }
  5410. // Depth test
  5411. if (this._isDepthTestDirty) {
  5412. if (this.depthTest) {
  5413. gl.enable(gl.DEPTH_TEST);
  5414. }
  5415. else {
  5416. gl.disable(gl.DEPTH_TEST);
  5417. }
  5418. this._isDepthTestDirty = false;
  5419. }
  5420. // Depth func
  5421. if (this._isDepthFuncDirty) {
  5422. gl.depthFunc(this.depthFunc);
  5423. this._isDepthFuncDirty = false;
  5424. }
  5425. // zOffset
  5426. if (this._isZOffsetDirty) {
  5427. if (this.zOffset) {
  5428. gl.enable(gl.POLYGON_OFFSET_FILL);
  5429. gl.polygonOffset(this.zOffset, 0);
  5430. }
  5431. else {
  5432. gl.disable(gl.POLYGON_OFFSET_FILL);
  5433. }
  5434. this._isZOffsetDirty = false;
  5435. }
  5436. };
  5437. return _DepthCullingState;
  5438. })();
  5439. Internals._DepthCullingState = _DepthCullingState;
  5440. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5441. })(BABYLON || (BABYLON = {}));
  5442. var BABYLON;
  5443. (function (BABYLON) {
  5444. var compileShader = function (gl, source, type, defines) {
  5445. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5446. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5447. gl.compileShader(shader);
  5448. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5449. throw new Error(gl.getShaderInfoLog(shader));
  5450. }
  5451. return shader;
  5452. };
  5453. var getWebGLTextureType = function (gl, type) {
  5454. var textureType = gl.UNSIGNED_BYTE;
  5455. if (type === Engine.TEXTURETYPE_FLOAT)
  5456. textureType = gl.FLOAT;
  5457. return textureType;
  5458. };
  5459. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5460. var magFilter = gl.NEAREST;
  5461. var minFilter = gl.NEAREST;
  5462. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5463. magFilter = gl.LINEAR;
  5464. if (generateMipMaps) {
  5465. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5466. }
  5467. else {
  5468. minFilter = gl.LINEAR;
  5469. }
  5470. }
  5471. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5472. magFilter = gl.LINEAR;
  5473. if (generateMipMaps) {
  5474. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5475. }
  5476. else {
  5477. minFilter = gl.LINEAR;
  5478. }
  5479. }
  5480. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5481. magFilter = gl.NEAREST;
  5482. if (generateMipMaps) {
  5483. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5484. }
  5485. else {
  5486. minFilter = gl.NEAREST;
  5487. }
  5488. }
  5489. return {
  5490. min: minFilter,
  5491. mag: magFilter
  5492. };
  5493. };
  5494. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5495. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5496. var engine = scene.getEngine();
  5497. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5498. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5499. gl.bindTexture(gl.TEXTURE_2D, texture);
  5500. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5501. texture._baseWidth = width;
  5502. texture._baseHeight = height;
  5503. texture._width = potWidth;
  5504. texture._height = potHeight;
  5505. texture.isReady = true;
  5506. processFunction(potWidth, potHeight);
  5507. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5510. if (!noMipmap && !isCompressed) {
  5511. gl.generateMipmap(gl.TEXTURE_2D);
  5512. }
  5513. gl.bindTexture(gl.TEXTURE_2D, null);
  5514. engine.resetTextureCache();
  5515. scene._removePendingData(texture);
  5516. if (onLoad) {
  5517. onLoad();
  5518. }
  5519. };
  5520. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5521. var img;
  5522. var onload = function () {
  5523. loadedImages[index] = img;
  5524. loadedImages._internalCount++;
  5525. scene._removePendingData(img);
  5526. if (loadedImages._internalCount === 6) {
  5527. onfinish(loadedImages);
  5528. }
  5529. };
  5530. var onerror = function () {
  5531. scene._removePendingData(img);
  5532. };
  5533. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5534. scene._addPendingData(img);
  5535. };
  5536. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5537. var loadedImages = [];
  5538. loadedImages._internalCount = 0;
  5539. for (var index = 0; index < 6; index++) {
  5540. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5541. }
  5542. };
  5543. var InstancingAttributeInfo = (function () {
  5544. function InstancingAttributeInfo() {
  5545. }
  5546. return InstancingAttributeInfo;
  5547. })();
  5548. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5549. var EngineCapabilities = (function () {
  5550. function EngineCapabilities() {
  5551. }
  5552. return EngineCapabilities;
  5553. })();
  5554. BABYLON.EngineCapabilities = EngineCapabilities;
  5555. /**
  5556. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5557. */
  5558. var Engine = (function () {
  5559. /**
  5560. * @constructor
  5561. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5562. * @param {boolean} [antialias] - enable antialias
  5563. * @param options - further options to be sent to the getContext function
  5564. */
  5565. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5566. var _this = this;
  5567. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5568. // Public members
  5569. this.isFullscreen = false;
  5570. this.isPointerLock = false;
  5571. this.cullBackFaces = true;
  5572. this.renderEvenInBackground = true;
  5573. // To enable/disable IDB support and avoid XHR on .manifest
  5574. this.enableOfflineSupport = true;
  5575. this.scenes = new Array();
  5576. this._windowIsBackground = false;
  5577. this._webGLVersion = "1.0";
  5578. this._drawCalls = 0;
  5579. this._renderingQueueLaunched = false;
  5580. this._activeRenderLoops = [];
  5581. // FPS
  5582. this.fpsRange = 60;
  5583. this.previousFramesDuration = [];
  5584. this.fps = 60;
  5585. this.deltaTime = 0;
  5586. // States
  5587. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5588. this._alphaState = new BABYLON.Internals._AlphaState();
  5589. this._alphaMode = Engine.ALPHA_DISABLE;
  5590. // Cache
  5591. this._loadedTexturesCache = new Array();
  5592. this._maxTextureChannels = 16;
  5593. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5594. this._compiledEffects = {};
  5595. this._uintIndicesCurrentlySet = false;
  5596. this._renderingCanvas = canvas;
  5597. this._externalData = new BABYLON.StringDictionary();
  5598. options = options || {};
  5599. options.antialias = antialias;
  5600. if (options.preserveDrawingBuffer === undefined) {
  5601. options.preserveDrawingBuffer = false;
  5602. }
  5603. // GL
  5604. //try {
  5605. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5606. // if (this._gl) {
  5607. // this._webGLVersion = "2.0";
  5608. // }
  5609. //} catch (e) {
  5610. // // Do nothing
  5611. //}
  5612. if (!this._gl) {
  5613. try {
  5614. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5615. }
  5616. catch (e) {
  5617. throw new Error("WebGL not supported");
  5618. }
  5619. }
  5620. if (!this._gl) {
  5621. throw new Error("WebGL not supported");
  5622. }
  5623. this._onBlur = function () {
  5624. _this._windowIsBackground = true;
  5625. };
  5626. this._onFocus = function () {
  5627. _this._windowIsBackground = false;
  5628. };
  5629. window.addEventListener("blur", this._onBlur);
  5630. window.addEventListener("focus", this._onFocus);
  5631. // Viewport
  5632. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5633. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5634. this.resize();
  5635. // Caps
  5636. this._caps = new EngineCapabilities();
  5637. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5638. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5639. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5640. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5641. // Infos
  5642. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5643. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5644. if (rendererInfo != null) {
  5645. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5646. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5647. }
  5648. if (!this._glVendor) {
  5649. this._glVendor = "Unknown vendor";
  5650. }
  5651. if (!this._glRenderer) {
  5652. this._glRenderer = "Unknown renderer";
  5653. }
  5654. // Extensions
  5655. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5656. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5657. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5658. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  5659. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5660. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5661. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5662. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5663. this._caps.highPrecisionShaderSupported = true;
  5664. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5665. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5666. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5667. if (this._gl.getShaderPrecisionFormat) {
  5668. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5669. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5670. }
  5671. // Depth buffer
  5672. this.setDepthBuffer(true);
  5673. this.setDepthFunctionToLessOrEqual();
  5674. this.setDepthWrite(true);
  5675. // Fullscreen
  5676. this._onFullscreenChange = function () {
  5677. if (document.fullscreen !== undefined) {
  5678. _this.isFullscreen = document.fullscreen;
  5679. }
  5680. else if (document.mozFullScreen !== undefined) {
  5681. _this.isFullscreen = document.mozFullScreen;
  5682. }
  5683. else if (document.webkitIsFullScreen !== undefined) {
  5684. _this.isFullscreen = document.webkitIsFullScreen;
  5685. }
  5686. else if (document.msIsFullScreen !== undefined) {
  5687. _this.isFullscreen = document.msIsFullScreen;
  5688. }
  5689. // Pointer lock
  5690. if (_this.isFullscreen && _this._pointerLockRequested) {
  5691. canvas.requestPointerLock = canvas.requestPointerLock ||
  5692. canvas.msRequestPointerLock ||
  5693. canvas.mozRequestPointerLock ||
  5694. canvas.webkitRequestPointerLock;
  5695. if (canvas.requestPointerLock) {
  5696. canvas.requestPointerLock();
  5697. }
  5698. }
  5699. };
  5700. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5701. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5702. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5703. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5704. // Pointer lock
  5705. this._onPointerLockChange = function () {
  5706. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5707. document.webkitPointerLockElement === canvas ||
  5708. document.msPointerLockElement === canvas ||
  5709. document.pointerLockElement === canvas);
  5710. };
  5711. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5712. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5713. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5714. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5715. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5716. Engine.audioEngine = new BABYLON.AudioEngine();
  5717. }
  5718. //default loading screen
  5719. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5720. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5721. }
  5722. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5723. get: function () {
  5724. return Engine._ALPHA_DISABLE;
  5725. },
  5726. enumerable: true,
  5727. configurable: true
  5728. });
  5729. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5730. get: function () {
  5731. return Engine._ALPHA_ONEONE;
  5732. },
  5733. enumerable: true,
  5734. configurable: true
  5735. });
  5736. Object.defineProperty(Engine, "ALPHA_ADD", {
  5737. get: function () {
  5738. return Engine._ALPHA_ADD;
  5739. },
  5740. enumerable: true,
  5741. configurable: true
  5742. });
  5743. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5744. get: function () {
  5745. return Engine._ALPHA_COMBINE;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5751. get: function () {
  5752. return Engine._ALPHA_SUBTRACT;
  5753. },
  5754. enumerable: true,
  5755. configurable: true
  5756. });
  5757. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5758. get: function () {
  5759. return Engine._ALPHA_MULTIPLY;
  5760. },
  5761. enumerable: true,
  5762. configurable: true
  5763. });
  5764. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5765. get: function () {
  5766. return Engine._ALPHA_MAXIMIZED;
  5767. },
  5768. enumerable: true,
  5769. configurable: true
  5770. });
  5771. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5772. get: function () {
  5773. return Engine._DELAYLOADSTATE_NONE;
  5774. },
  5775. enumerable: true,
  5776. configurable: true
  5777. });
  5778. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5779. get: function () {
  5780. return Engine._DELAYLOADSTATE_LOADED;
  5781. },
  5782. enumerable: true,
  5783. configurable: true
  5784. });
  5785. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5786. get: function () {
  5787. return Engine._DELAYLOADSTATE_LOADING;
  5788. },
  5789. enumerable: true,
  5790. configurable: true
  5791. });
  5792. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5793. get: function () {
  5794. return Engine._DELAYLOADSTATE_NOTLOADED;
  5795. },
  5796. enumerable: true,
  5797. configurable: true
  5798. });
  5799. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5800. get: function () {
  5801. return Engine._TEXTUREFORMAT_ALPHA;
  5802. },
  5803. enumerable: true,
  5804. configurable: true
  5805. });
  5806. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5807. get: function () {
  5808. return Engine._TEXTUREFORMAT_LUMINANCE;
  5809. },
  5810. enumerable: true,
  5811. configurable: true
  5812. });
  5813. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5814. get: function () {
  5815. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5816. },
  5817. enumerable: true,
  5818. configurable: true
  5819. });
  5820. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5821. get: function () {
  5822. return Engine._TEXTUREFORMAT_RGB;
  5823. },
  5824. enumerable: true,
  5825. configurable: true
  5826. });
  5827. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5828. get: function () {
  5829. return Engine._TEXTUREFORMAT_RGBA;
  5830. },
  5831. enumerable: true,
  5832. configurable: true
  5833. });
  5834. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5835. get: function () {
  5836. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5837. },
  5838. enumerable: true,
  5839. configurable: true
  5840. });
  5841. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5842. get: function () {
  5843. return Engine._TEXTURETYPE_FLOAT;
  5844. },
  5845. enumerable: true,
  5846. configurable: true
  5847. });
  5848. Object.defineProperty(Engine, "Version", {
  5849. get: function () {
  5850. return "2.4.0-beta";
  5851. },
  5852. enumerable: true,
  5853. configurable: true
  5854. });
  5855. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5856. get: function () {
  5857. return this._webGLVersion;
  5858. },
  5859. enumerable: true,
  5860. configurable: true
  5861. });
  5862. Engine.prototype._prepareWorkingCanvas = function () {
  5863. if (this._workingCanvas) {
  5864. return;
  5865. }
  5866. this._workingCanvas = document.createElement("canvas");
  5867. this._workingContext = this._workingCanvas.getContext("2d");
  5868. };
  5869. Engine.prototype.resetTextureCache = function () {
  5870. for (var index = 0; index < this._maxTextureChannels; index++) {
  5871. this._activeTexturesCache[index] = null;
  5872. }
  5873. };
  5874. Engine.prototype.getGlInfo = function () {
  5875. return {
  5876. vendor: this._glVendor,
  5877. renderer: this._glRenderer,
  5878. version: this._glVersion
  5879. };
  5880. };
  5881. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5882. if (useScreen === void 0) { useScreen = false; }
  5883. var viewport = camera.viewport;
  5884. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5885. };
  5886. Engine.prototype.getRenderWidth = function (useScreen) {
  5887. if (useScreen === void 0) { useScreen = false; }
  5888. if (!useScreen && this._currentRenderTarget) {
  5889. return this._currentRenderTarget._width;
  5890. }
  5891. return this._renderingCanvas.width;
  5892. };
  5893. Engine.prototype.getRenderHeight = function (useScreen) {
  5894. if (useScreen === void 0) { useScreen = false; }
  5895. if (!useScreen && this._currentRenderTarget) {
  5896. return this._currentRenderTarget._height;
  5897. }
  5898. return this._renderingCanvas.height;
  5899. };
  5900. Engine.prototype.getRenderingCanvas = function () {
  5901. return this._renderingCanvas;
  5902. };
  5903. Engine.prototype.getRenderingCanvasClientRect = function () {
  5904. return this._renderingCanvas.getBoundingClientRect();
  5905. };
  5906. Engine.prototype.setHardwareScalingLevel = function (level) {
  5907. this._hardwareScalingLevel = level;
  5908. this.resize();
  5909. };
  5910. Engine.prototype.getHardwareScalingLevel = function () {
  5911. return this._hardwareScalingLevel;
  5912. };
  5913. Engine.prototype.getLoadedTexturesCache = function () {
  5914. return this._loadedTexturesCache;
  5915. };
  5916. Engine.prototype.getCaps = function () {
  5917. return this._caps;
  5918. };
  5919. Object.defineProperty(Engine.prototype, "drawCalls", {
  5920. get: function () {
  5921. return this._drawCalls;
  5922. },
  5923. enumerable: true,
  5924. configurable: true
  5925. });
  5926. // Methods
  5927. Engine.prototype.resetDrawCalls = function () {
  5928. this._drawCalls = 0;
  5929. };
  5930. Engine.prototype.getDepthFunction = function () {
  5931. return this._depthCullingState.depthFunc;
  5932. };
  5933. Engine.prototype.setDepthFunction = function (depthFunc) {
  5934. this._depthCullingState.depthFunc = depthFunc;
  5935. };
  5936. Engine.prototype.setDepthFunctionToGreater = function () {
  5937. this._depthCullingState.depthFunc = this._gl.GREATER;
  5938. };
  5939. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5940. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5941. };
  5942. Engine.prototype.setDepthFunctionToLess = function () {
  5943. this._depthCullingState.depthFunc = this._gl.LESS;
  5944. };
  5945. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5946. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5947. };
  5948. /**
  5949. * stop executing a render loop function and remove it from the execution array
  5950. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5951. */
  5952. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5953. if (!renderFunction) {
  5954. this._activeRenderLoops = [];
  5955. return;
  5956. }
  5957. var index = this._activeRenderLoops.indexOf(renderFunction);
  5958. if (index >= 0) {
  5959. this._activeRenderLoops.splice(index, 1);
  5960. }
  5961. };
  5962. Engine.prototype._renderLoop = function () {
  5963. var shouldRender = true;
  5964. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5965. shouldRender = false;
  5966. }
  5967. if (shouldRender) {
  5968. // Start new frame
  5969. this.beginFrame();
  5970. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5971. var renderFunction = this._activeRenderLoops[index];
  5972. renderFunction();
  5973. }
  5974. // Present
  5975. this.endFrame();
  5976. }
  5977. if (this._activeRenderLoops.length > 0) {
  5978. // Register new frame
  5979. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5980. }
  5981. else {
  5982. this._renderingQueueLaunched = false;
  5983. }
  5984. };
  5985. /**
  5986. * Register and execute a render loop. The engine can have more than one render function.
  5987. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  5988. * @example
  5989. * engine.runRenderLoop(function () {
  5990. * scene.render()
  5991. * })
  5992. */
  5993. Engine.prototype.runRenderLoop = function (renderFunction) {
  5994. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5995. return;
  5996. }
  5997. this._activeRenderLoops.push(renderFunction);
  5998. if (!this._renderingQueueLaunched) {
  5999. this._renderingQueueLaunched = true;
  6000. this._bindedRenderFunction = this._renderLoop.bind(this);
  6001. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6002. }
  6003. };
  6004. /**
  6005. * Toggle full screen mode.
  6006. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6007. */
  6008. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  6009. if (this.isFullscreen) {
  6010. BABYLON.Tools.ExitFullscreen();
  6011. }
  6012. else {
  6013. this._pointerLockRequested = requestPointerLock;
  6014. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  6015. }
  6016. };
  6017. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6018. this.applyStates();
  6019. if (backBuffer) {
  6020. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6021. }
  6022. if (depthStencil && this._depthCullingState.depthMask) {
  6023. this._gl.clearDepth(1.0);
  6024. }
  6025. var mode = 0;
  6026. if (backBuffer) {
  6027. mode |= this._gl.COLOR_BUFFER_BIT;
  6028. }
  6029. if (depthStencil && this._depthCullingState.depthMask) {
  6030. mode |= this._gl.DEPTH_BUFFER_BIT;
  6031. }
  6032. this._gl.clear(mode);
  6033. };
  6034. /**
  6035. * Set the WebGL's viewport
  6036. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6037. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6038. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6039. */
  6040. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6041. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6042. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6043. var x = viewport.x || 0;
  6044. var y = viewport.y || 0;
  6045. this._cachedViewport = viewport;
  6046. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6047. };
  6048. /**
  6049. * Directly set the WebGL Viewport
  6050. * The x, y, width & height are directly passed to the WebGL call
  6051. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  6052. */
  6053. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6054. var currentViewport = this._cachedViewport;
  6055. this._cachedViewport = null;
  6056. this._gl.viewport(x, y, width, height);
  6057. return currentViewport;
  6058. };
  6059. Engine.prototype.beginFrame = function () {
  6060. this._measureFps();
  6061. };
  6062. Engine.prototype.endFrame = function () {
  6063. //this.flushFramebuffer();
  6064. };
  6065. /**
  6066. * resize the view according to the canvas' size.
  6067. * @example
  6068. * window.addEventListener("resize", function () {
  6069. * engine.resize();
  6070. * });
  6071. */
  6072. Engine.prototype.resize = function () {
  6073. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6074. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6075. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6076. for (var index = 0; index < this.scenes.length; index++) {
  6077. var scene = this.scenes[index];
  6078. if (scene.debugLayer.isVisible()) {
  6079. scene.debugLayer._syncPositions();
  6080. }
  6081. }
  6082. };
  6083. /**
  6084. * force a specific size of the canvas
  6085. * @param {number} width - the new canvas' width
  6086. * @param {number} height - the new canvas' height
  6087. */
  6088. Engine.prototype.setSize = function (width, height) {
  6089. this._renderingCanvas.width = width;
  6090. this._renderingCanvas.height = height;
  6091. for (var index = 0; index < this.scenes.length; index++) {
  6092. var scene = this.scenes[index];
  6093. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6094. var cam = scene.cameras[camIndex];
  6095. cam._currentRenderId = 0;
  6096. }
  6097. }
  6098. };
  6099. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6100. this._currentRenderTarget = texture;
  6101. var gl = this._gl;
  6102. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  6103. if (texture.isCube) {
  6104. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6105. }
  6106. else {
  6107. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6108. }
  6109. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6110. this.wipeCaches();
  6111. };
  6112. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6113. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6114. this._currentRenderTarget = null;
  6115. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6116. var gl = this._gl;
  6117. gl.bindTexture(gl.TEXTURE_2D, texture);
  6118. gl.generateMipmap(gl.TEXTURE_2D);
  6119. gl.bindTexture(gl.TEXTURE_2D, null);
  6120. }
  6121. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6122. };
  6123. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6124. if (texture.generateMipMaps) {
  6125. var gl = this._gl;
  6126. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6127. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6128. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6129. }
  6130. };
  6131. Engine.prototype.flushFramebuffer = function () {
  6132. this._gl.flush();
  6133. };
  6134. Engine.prototype.restoreDefaultFramebuffer = function () {
  6135. this._currentRenderTarget = null;
  6136. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6137. this.setViewport(this._cachedViewport);
  6138. this.wipeCaches();
  6139. };
  6140. // VBOs
  6141. Engine.prototype._resetVertexBufferBinding = function () {
  6142. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  6143. this._cachedVertexBuffers = null;
  6144. };
  6145. Engine.prototype.createVertexBuffer = function (vertices) {
  6146. var vbo = this._gl.createBuffer();
  6147. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6148. if (vertices instanceof Float32Array) {
  6149. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6150. }
  6151. else {
  6152. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6153. }
  6154. this._resetVertexBufferBinding();
  6155. vbo.references = 1;
  6156. return vbo;
  6157. };
  6158. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6159. var vbo = this._gl.createBuffer();
  6160. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6161. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6162. this._resetVertexBufferBinding();
  6163. vbo.references = 1;
  6164. return vbo;
  6165. };
  6166. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6167. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6168. if (offset === undefined) {
  6169. offset = 0;
  6170. }
  6171. if (vertices instanceof Float32Array) {
  6172. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6173. }
  6174. else {
  6175. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6176. }
  6177. this._resetVertexBufferBinding();
  6178. };
  6179. Engine.prototype._resetIndexBufferBinding = function () {
  6180. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6181. this._cachedIndexBuffer = null;
  6182. };
  6183. Engine.prototype.createIndexBuffer = function (indices) {
  6184. var vbo = this._gl.createBuffer();
  6185. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6186. // Check for 32 bits indices
  6187. var arrayBuffer;
  6188. var need32Bits = false;
  6189. if (this._caps.uintIndices) {
  6190. for (var index = 0; index < indices.length; index++) {
  6191. if (indices[index] > 65535) {
  6192. need32Bits = true;
  6193. break;
  6194. }
  6195. }
  6196. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6197. }
  6198. else {
  6199. arrayBuffer = new Uint16Array(indices);
  6200. }
  6201. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6202. this._resetIndexBufferBinding();
  6203. vbo.references = 1;
  6204. vbo.is32Bits = need32Bits;
  6205. return vbo;
  6206. };
  6207. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6208. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6209. this._cachedVertexBuffers = vertexBuffer;
  6210. this._cachedEffectForVertexBuffers = effect;
  6211. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6212. var offset = 0;
  6213. for (var index = 0; index < vertexDeclaration.length; index++) {
  6214. var order = effect.getAttributeLocation(index);
  6215. if (order >= 0) {
  6216. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6217. }
  6218. offset += vertexDeclaration[index] * 4;
  6219. }
  6220. }
  6221. if (this._cachedIndexBuffer !== indexBuffer) {
  6222. this._cachedIndexBuffer = indexBuffer;
  6223. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6224. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6225. }
  6226. };
  6227. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6228. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6229. this._cachedVertexBuffers = vertexBuffers;
  6230. this._cachedEffectForVertexBuffers = effect;
  6231. var attributes = effect.getAttributesNames();
  6232. for (var index = 0; index < attributes.length; index++) {
  6233. var order = effect.getAttributeLocation(index);
  6234. if (order >= 0) {
  6235. var vertexBuffer = vertexBuffers[attributes[index]];
  6236. if (!vertexBuffer) {
  6237. continue;
  6238. }
  6239. var stride = vertexBuffer.getStrideSize();
  6240. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6241. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6242. }
  6243. }
  6244. }
  6245. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6246. this._cachedIndexBuffer = indexBuffer;
  6247. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6248. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6249. }
  6250. };
  6251. Engine.prototype._releaseBuffer = function (buffer) {
  6252. buffer.references--;
  6253. if (buffer.references === 0) {
  6254. this._gl.deleteBuffer(buffer);
  6255. return true;
  6256. }
  6257. return false;
  6258. };
  6259. Engine.prototype.createInstancesBuffer = function (capacity) {
  6260. var buffer = this._gl.createBuffer();
  6261. buffer.capacity = capacity;
  6262. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6263. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6264. return buffer;
  6265. };
  6266. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6267. this._gl.deleteBuffer(buffer);
  6268. };
  6269. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6270. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6271. if (data) {
  6272. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6273. }
  6274. if (offsetLocations[0].index !== undefined) {
  6275. var stride = 0;
  6276. for (var i = 0; i < offsetLocations.length; i++) {
  6277. var ai = offsetLocations[i];
  6278. stride += ai.attributeSize * 4;
  6279. }
  6280. for (var i = 0; i < offsetLocations.length; i++) {
  6281. var ai = offsetLocations[i];
  6282. this._gl.enableVertexAttribArray(ai.index);
  6283. this._gl.vertexAttribPointer(ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6284. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6285. }
  6286. }
  6287. else {
  6288. for (var index = 0; index < 4; index++) {
  6289. var offsetLocation = offsetLocations[index];
  6290. this._gl.enableVertexAttribArray(offsetLocation);
  6291. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6292. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6293. }
  6294. }
  6295. };
  6296. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6297. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6298. if (offsetLocations[0].index !== undefined) {
  6299. for (var i = 0; i < offsetLocations.length; i++) {
  6300. var ai = offsetLocations[i];
  6301. this._gl.disableVertexAttribArray(ai.index);
  6302. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 0);
  6303. }
  6304. }
  6305. else {
  6306. for (var index = 0; index < 4; index++) {
  6307. var offsetLocation = offsetLocations[index];
  6308. this._gl.disableVertexAttribArray(offsetLocation);
  6309. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6310. }
  6311. }
  6312. };
  6313. Engine.prototype.applyStates = function () {
  6314. this._depthCullingState.apply(this._gl);
  6315. this._alphaState.apply(this._gl);
  6316. };
  6317. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6318. // Apply states
  6319. this.applyStates();
  6320. this._drawCalls++;
  6321. // Render
  6322. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6323. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6324. if (instancesCount) {
  6325. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6326. return;
  6327. }
  6328. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6329. };
  6330. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6331. // Apply states
  6332. this.applyStates();
  6333. this._drawCalls++;
  6334. if (instancesCount) {
  6335. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6336. return;
  6337. }
  6338. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6339. };
  6340. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6341. // Apply states
  6342. this.applyStates();
  6343. this._drawCalls++;
  6344. if (instancesCount) {
  6345. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6346. return;
  6347. }
  6348. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6349. };
  6350. // Shaders
  6351. Engine.prototype._releaseEffect = function (effect) {
  6352. if (this._compiledEffects[effect._key]) {
  6353. delete this._compiledEffects[effect._key];
  6354. if (effect.getProgram()) {
  6355. this._gl.deleteProgram(effect.getProgram());
  6356. }
  6357. }
  6358. };
  6359. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6360. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6361. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6362. var name = vertex + "+" + fragment + "@" + defines;
  6363. if (this._compiledEffects[name]) {
  6364. return this._compiledEffects[name];
  6365. }
  6366. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6367. effect._key = name;
  6368. this._compiledEffects[name] = effect;
  6369. return effect;
  6370. };
  6371. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6372. if (uniformsNames === void 0) { uniformsNames = []; }
  6373. if (samplers === void 0) { samplers = []; }
  6374. if (defines === void 0) { defines = ""; }
  6375. return this.createEffect({
  6376. vertex: "particles",
  6377. fragmentElement: fragmentName
  6378. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6379. };
  6380. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6381. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6382. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6383. var shaderProgram = this._gl.createProgram();
  6384. this._gl.attachShader(shaderProgram, vertexShader);
  6385. this._gl.attachShader(shaderProgram, fragmentShader);
  6386. this._gl.linkProgram(shaderProgram);
  6387. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6388. if (!linked) {
  6389. var error = this._gl.getProgramInfoLog(shaderProgram);
  6390. if (error) {
  6391. throw new Error(error);
  6392. }
  6393. }
  6394. this._gl.deleteShader(vertexShader);
  6395. this._gl.deleteShader(fragmentShader);
  6396. return shaderProgram;
  6397. };
  6398. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6399. var results = [];
  6400. for (var index = 0; index < uniformsNames.length; index++) {
  6401. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6402. }
  6403. return results;
  6404. };
  6405. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6406. var results = [];
  6407. for (var index = 0; index < attributesNames.length; index++) {
  6408. try {
  6409. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6410. }
  6411. catch (e) {
  6412. results.push(-1);
  6413. }
  6414. }
  6415. return results;
  6416. };
  6417. Engine.prototype.enableEffect = function (effect) {
  6418. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6419. if (effect && effect.onBind) {
  6420. effect.onBind(effect);
  6421. }
  6422. return;
  6423. }
  6424. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6425. // Use program
  6426. this._gl.useProgram(effect.getProgram());
  6427. for (var i in this._vertexAttribArrays) {
  6428. //make sure this is a number)
  6429. var iAsNumber = +i;
  6430. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6431. continue;
  6432. }
  6433. this._vertexAttribArrays[iAsNumber] = false;
  6434. this._gl.disableVertexAttribArray(iAsNumber);
  6435. }
  6436. var attributesCount = effect.getAttributesCount();
  6437. for (var index = 0; index < attributesCount; index++) {
  6438. // Attributes
  6439. var order = effect.getAttributeLocation(index);
  6440. if (order >= 0) {
  6441. this._vertexAttribArrays[order] = true;
  6442. this._gl.enableVertexAttribArray(order);
  6443. }
  6444. }
  6445. this._currentEffect = effect;
  6446. if (effect.onBind) {
  6447. effect.onBind(effect);
  6448. }
  6449. };
  6450. Engine.prototype.setArray = function (uniform, array) {
  6451. if (!uniform)
  6452. return;
  6453. this._gl.uniform1fv(uniform, array);
  6454. };
  6455. Engine.prototype.setArray2 = function (uniform, array) {
  6456. if (!uniform || array.length % 2 !== 0)
  6457. return;
  6458. this._gl.uniform2fv(uniform, array);
  6459. };
  6460. Engine.prototype.setArray3 = function (uniform, array) {
  6461. if (!uniform || array.length % 3 !== 0)
  6462. return;
  6463. this._gl.uniform3fv(uniform, array);
  6464. };
  6465. Engine.prototype.setArray4 = function (uniform, array) {
  6466. if (!uniform || array.length % 4 !== 0)
  6467. return;
  6468. this._gl.uniform4fv(uniform, array);
  6469. };
  6470. Engine.prototype.setMatrices = function (uniform, matrices) {
  6471. if (!uniform)
  6472. return;
  6473. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6474. };
  6475. Engine.prototype.setMatrix = function (uniform, matrix) {
  6476. if (!uniform)
  6477. return;
  6478. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6479. };
  6480. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6481. if (!uniform)
  6482. return;
  6483. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6484. };
  6485. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6486. if (!uniform)
  6487. return;
  6488. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6489. };
  6490. Engine.prototype.setFloat = function (uniform, value) {
  6491. if (!uniform)
  6492. return;
  6493. this._gl.uniform1f(uniform, value);
  6494. };
  6495. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6496. if (!uniform)
  6497. return;
  6498. this._gl.uniform2f(uniform, x, y);
  6499. };
  6500. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6501. if (!uniform)
  6502. return;
  6503. this._gl.uniform3f(uniform, x, y, z);
  6504. };
  6505. Engine.prototype.setBool = function (uniform, bool) {
  6506. if (!uniform)
  6507. return;
  6508. this._gl.uniform1i(uniform, bool);
  6509. };
  6510. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6511. if (!uniform)
  6512. return;
  6513. this._gl.uniform4f(uniform, x, y, z, w);
  6514. };
  6515. Engine.prototype.setColor3 = function (uniform, color3) {
  6516. if (!uniform)
  6517. return;
  6518. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6519. };
  6520. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6521. if (!uniform)
  6522. return;
  6523. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6524. };
  6525. // States
  6526. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6527. if (zOffset === void 0) { zOffset = 0; }
  6528. if (reverseSide === void 0) { reverseSide = false; }
  6529. // Culling
  6530. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6531. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6532. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6533. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6534. if (culling) {
  6535. this._depthCullingState.cullFace = cullFace;
  6536. this._depthCullingState.cull = true;
  6537. }
  6538. else {
  6539. this._depthCullingState.cull = false;
  6540. }
  6541. }
  6542. // Z offset
  6543. this._depthCullingState.zOffset = zOffset;
  6544. };
  6545. Engine.prototype.setDepthBuffer = function (enable) {
  6546. this._depthCullingState.depthTest = enable;
  6547. };
  6548. Engine.prototype.getDepthWrite = function () {
  6549. return this._depthCullingState.depthMask;
  6550. };
  6551. Engine.prototype.setDepthWrite = function (enable) {
  6552. this._depthCullingState.depthMask = enable;
  6553. };
  6554. Engine.prototype.setColorWrite = function (enable) {
  6555. this._gl.colorMask(enable, enable, enable, enable);
  6556. };
  6557. Engine.prototype.setAlphaMode = function (mode) {
  6558. if (this._alphaMode === mode) {
  6559. return;
  6560. }
  6561. switch (mode) {
  6562. case Engine.ALPHA_DISABLE:
  6563. this.setDepthWrite(true);
  6564. this._alphaState.alphaBlend = false;
  6565. break;
  6566. case Engine.ALPHA_COMBINE:
  6567. this.setDepthWrite(false);
  6568. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6569. this._alphaState.alphaBlend = true;
  6570. break;
  6571. case Engine.ALPHA_ONEONE:
  6572. this.setDepthWrite(false);
  6573. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6574. this._alphaState.alphaBlend = true;
  6575. break;
  6576. case Engine.ALPHA_ADD:
  6577. this.setDepthWrite(false);
  6578. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6579. this._alphaState.alphaBlend = true;
  6580. break;
  6581. case Engine.ALPHA_SUBTRACT:
  6582. this.setDepthWrite(false);
  6583. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6584. this._alphaState.alphaBlend = true;
  6585. break;
  6586. case Engine.ALPHA_MULTIPLY:
  6587. this.setDepthWrite(false);
  6588. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6589. this._alphaState.alphaBlend = true;
  6590. break;
  6591. case Engine.ALPHA_MAXIMIZED:
  6592. this.setDepthWrite(false);
  6593. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6594. this._alphaState.alphaBlend = true;
  6595. break;
  6596. }
  6597. this._alphaMode = mode;
  6598. };
  6599. Engine.prototype.getAlphaMode = function () {
  6600. return this._alphaMode;
  6601. };
  6602. Engine.prototype.setAlphaTesting = function (enable) {
  6603. this._alphaTest = enable;
  6604. };
  6605. Engine.prototype.getAlphaTesting = function () {
  6606. return this._alphaTest;
  6607. };
  6608. // Textures
  6609. Engine.prototype.wipeCaches = function () {
  6610. this.resetTextureCache();
  6611. this._currentEffect = null;
  6612. this._depthCullingState.reset();
  6613. this._alphaState.reset();
  6614. this._cachedVertexBuffers = null;
  6615. this._cachedIndexBuffer = null;
  6616. this._cachedEffectForVertexBuffers = null;
  6617. };
  6618. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6619. var gl = this._gl;
  6620. gl.bindTexture(gl.TEXTURE_2D, texture);
  6621. var magFilter = gl.NEAREST;
  6622. var minFilter = gl.NEAREST;
  6623. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6624. magFilter = gl.LINEAR;
  6625. minFilter = gl.LINEAR;
  6626. }
  6627. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6628. magFilter = gl.LINEAR;
  6629. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6630. }
  6631. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6632. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6633. gl.bindTexture(gl.TEXTURE_2D, null);
  6634. texture.samplingMode = samplingMode;
  6635. };
  6636. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6637. var _this = this;
  6638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6639. if (onLoad === void 0) { onLoad = null; }
  6640. if (onError === void 0) { onError = null; }
  6641. if (buffer === void 0) { buffer = null; }
  6642. var texture = this._gl.createTexture();
  6643. var extension;
  6644. var fromData = false;
  6645. if (url.substr(0, 5) === "data:") {
  6646. fromData = true;
  6647. }
  6648. if (!fromData)
  6649. extension = url.substr(url.length - 4, 4).toLowerCase();
  6650. else {
  6651. var oldUrl = url;
  6652. fromData = oldUrl.split(':');
  6653. url = oldUrl;
  6654. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6655. }
  6656. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6657. var isTGA = (extension === ".tga");
  6658. scene._addPendingData(texture);
  6659. texture.url = url;
  6660. texture.noMipmap = noMipmap;
  6661. texture.references = 1;
  6662. texture.samplingMode = samplingMode;
  6663. this._loadedTexturesCache.push(texture);
  6664. var onerror = function () {
  6665. scene._removePendingData(texture);
  6666. if (onError) {
  6667. onError();
  6668. }
  6669. };
  6670. var callback;
  6671. if (isTGA) {
  6672. callback = function (arrayBuffer) {
  6673. var data = new Uint8Array(arrayBuffer);
  6674. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6675. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6676. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6677. }, onLoad, samplingMode);
  6678. };
  6679. if (!(fromData instanceof Array))
  6680. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6681. callback(arrayBuffer);
  6682. }, onerror, scene.database, true);
  6683. else
  6684. callback(buffer);
  6685. }
  6686. else if (isDDS) {
  6687. callback = function (data) {
  6688. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6689. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6690. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6691. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6692. }, onLoad, samplingMode);
  6693. };
  6694. if (!(fromData instanceof Array))
  6695. BABYLON.Tools.LoadFile(url, function (data) {
  6696. callback(data);
  6697. }, onerror, scene.database, true);
  6698. else
  6699. callback(buffer);
  6700. }
  6701. else {
  6702. var onload = function (img) {
  6703. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6704. var isPot = (img.width === potWidth && img.height === potHeight);
  6705. if (!isPot) {
  6706. _this._prepareWorkingCanvas();
  6707. _this._workingCanvas.width = potWidth;
  6708. _this._workingCanvas.height = potHeight;
  6709. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6710. _this._workingContext.imageSmoothingEnabled = false;
  6711. _this._workingContext.mozImageSmoothingEnabled = false;
  6712. _this._workingContext.oImageSmoothingEnabled = false;
  6713. _this._workingContext.webkitImageSmoothingEnabled = false;
  6714. _this._workingContext.msImageSmoothingEnabled = false;
  6715. }
  6716. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6717. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6718. _this._workingContext.imageSmoothingEnabled = true;
  6719. _this._workingContext.mozImageSmoothingEnabled = true;
  6720. _this._workingContext.oImageSmoothingEnabled = true;
  6721. _this._workingContext.webkitImageSmoothingEnabled = true;
  6722. _this._workingContext.msImageSmoothingEnabled = true;
  6723. }
  6724. }
  6725. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6726. }, onLoad, samplingMode);
  6727. };
  6728. if (!(fromData instanceof Array))
  6729. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6730. else
  6731. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6732. }
  6733. return texture;
  6734. };
  6735. Engine.prototype._getInternalFormat = function (format) {
  6736. var internalFormat = this._gl.RGBA;
  6737. switch (format) {
  6738. case Engine.TEXTUREFORMAT_ALPHA:
  6739. internalFormat = this._gl.ALPHA;
  6740. break;
  6741. case Engine.TEXTUREFORMAT_LUMINANCE:
  6742. internalFormat = this._gl.LUMINANCE;
  6743. break;
  6744. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6745. internalFormat = this._gl.LUMINANCE_ALPHA;
  6746. break;
  6747. case Engine.TEXTUREFORMAT_RGB:
  6748. internalFormat = this._gl.RGB;
  6749. break;
  6750. case Engine.TEXTUREFORMAT_RGBA:
  6751. internalFormat = this._gl.RGBA;
  6752. break;
  6753. }
  6754. return internalFormat;
  6755. };
  6756. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6757. if (compression === void 0) { compression = null; }
  6758. var internalFormat = this._getInternalFormat(format);
  6759. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6760. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6761. if (texture._width % 4 !== 0) {
  6762. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  6763. }
  6764. if (compression) {
  6765. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6766. }
  6767. else {
  6768. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6769. }
  6770. if (texture.generateMipMaps) {
  6771. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6772. }
  6773. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6774. this.resetTextureCache();
  6775. texture.isReady = true;
  6776. };
  6777. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6778. if (compression === void 0) { compression = null; }
  6779. var texture = this._gl.createTexture();
  6780. texture._baseWidth = width;
  6781. texture._baseHeight = height;
  6782. texture._width = width;
  6783. texture._height = height;
  6784. texture.references = 1;
  6785. this.updateRawTexture(texture, data, format, invertY, compression);
  6786. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6787. // Filters
  6788. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6789. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6790. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6791. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6792. texture.samplingMode = samplingMode;
  6793. this._loadedTexturesCache.push(texture);
  6794. return texture;
  6795. };
  6796. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6797. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6798. var texture = this._gl.createTexture();
  6799. texture._baseWidth = width;
  6800. texture._baseHeight = height;
  6801. if (forceExponantOfTwo) {
  6802. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6803. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6804. }
  6805. this.resetTextureCache();
  6806. texture._width = width;
  6807. texture._height = height;
  6808. texture.isReady = false;
  6809. texture.generateMipMaps = generateMipMaps;
  6810. texture.references = 1;
  6811. texture.samplingMode = samplingMode;
  6812. this.updateTextureSamplingMode(samplingMode, texture);
  6813. this._loadedTexturesCache.push(texture);
  6814. return texture;
  6815. };
  6816. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6817. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6818. if (texture.isCube) {
  6819. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6820. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6821. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6822. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6823. }
  6824. else {
  6825. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6826. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6827. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6828. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6829. }
  6830. };
  6831. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  6832. if (premulAlpha === void 0) { premulAlpha = false; }
  6833. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6834. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6835. if (premulAlpha) {
  6836. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  6837. }
  6838. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6839. if (texture.generateMipMaps) {
  6840. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6841. }
  6842. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6843. this.resetTextureCache();
  6844. texture.isReady = true;
  6845. };
  6846. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6847. if (texture._isDisabled) {
  6848. return;
  6849. }
  6850. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6851. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6852. try {
  6853. // Testing video texture support
  6854. if (this._videoTextureSupported === undefined) {
  6855. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6856. if (this._gl.getError() !== 0) {
  6857. this._videoTextureSupported = false;
  6858. }
  6859. else {
  6860. this._videoTextureSupported = true;
  6861. }
  6862. }
  6863. // Copy video through the current working canvas if video texture is not supported
  6864. if (!this._videoTextureSupported) {
  6865. if (!texture._workingCanvas) {
  6866. texture._workingCanvas = document.createElement("canvas");
  6867. texture._workingContext = texture._workingCanvas.getContext("2d");
  6868. texture._workingCanvas.width = texture._width;
  6869. texture._workingCanvas.height = texture._height;
  6870. }
  6871. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6872. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6873. }
  6874. else {
  6875. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6876. }
  6877. if (texture.generateMipMaps) {
  6878. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6879. }
  6880. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6881. this.resetTextureCache();
  6882. texture.isReady = true;
  6883. }
  6884. catch (ex) {
  6885. // Something unexpected
  6886. // Let's disable the texture
  6887. texture._isDisabled = true;
  6888. }
  6889. };
  6890. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6891. // old version had a "generateMipMaps" arg instead of options.
  6892. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6893. // in the same way, generateDepthBuffer is defaulted to true
  6894. var generateMipMaps = false;
  6895. var generateDepthBuffer = true;
  6896. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6897. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6898. if (options !== undefined) {
  6899. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6900. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6901. type = options.type === undefined ? type : options.type;
  6902. if (options.samplingMode !== undefined) {
  6903. samplingMode = options.samplingMode;
  6904. }
  6905. if (type === Engine.TEXTURETYPE_FLOAT) {
  6906. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6907. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6908. }
  6909. }
  6910. var gl = this._gl;
  6911. var texture = gl.createTexture();
  6912. gl.bindTexture(gl.TEXTURE_2D, texture);
  6913. var width = size.width || size;
  6914. var height = size.height || size;
  6915. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6916. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6917. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6918. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6919. }
  6920. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6921. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6922. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6923. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6924. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6925. var depthBuffer;
  6926. // Create the depth buffer
  6927. if (generateDepthBuffer) {
  6928. depthBuffer = gl.createRenderbuffer();
  6929. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6930. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6931. }
  6932. // Create the framebuffer
  6933. var framebuffer = gl.createFramebuffer();
  6934. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6935. if (generateDepthBuffer) {
  6936. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6937. }
  6938. if (generateMipMaps) {
  6939. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6940. }
  6941. // Unbind
  6942. gl.bindTexture(gl.TEXTURE_2D, null);
  6943. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6944. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6945. texture._framebuffer = framebuffer;
  6946. if (generateDepthBuffer) {
  6947. texture._depthBuffer = depthBuffer;
  6948. }
  6949. texture._width = width;
  6950. texture._height = height;
  6951. texture.isReady = true;
  6952. texture.generateMipMaps = generateMipMaps;
  6953. texture.references = 1;
  6954. texture.samplingMode = samplingMode;
  6955. this.resetTextureCache();
  6956. this._loadedTexturesCache.push(texture);
  6957. return texture;
  6958. };
  6959. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6960. var gl = this._gl;
  6961. var texture = gl.createTexture();
  6962. var generateMipMaps = true;
  6963. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6964. if (options !== undefined) {
  6965. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6966. if (options.samplingMode !== undefined) {
  6967. samplingMode = options.samplingMode;
  6968. }
  6969. }
  6970. texture.isCube = true;
  6971. texture.references = 1;
  6972. texture.generateMipMaps = generateMipMaps;
  6973. texture.references = 1;
  6974. texture.samplingMode = samplingMode;
  6975. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6976. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6977. for (var face = 0; face < 6; face++) {
  6978. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6979. }
  6980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6982. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6983. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6984. // Create the depth buffer
  6985. var depthBuffer = gl.createRenderbuffer();
  6986. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6987. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6988. // Create the framebuffer
  6989. var framebuffer = gl.createFramebuffer();
  6990. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6991. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6992. // Mipmaps
  6993. if (texture.generateMipMaps) {
  6994. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6995. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6996. }
  6997. // Unbind
  6998. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6999. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7000. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7001. texture._framebuffer = framebuffer;
  7002. texture._depthBuffer = depthBuffer;
  7003. this.resetTextureCache();
  7004. texture._width = size;
  7005. texture._height = size;
  7006. texture.isReady = true;
  7007. return texture;
  7008. };
  7009. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7010. var _this = this;
  7011. var gl = this._gl;
  7012. var texture = gl.createTexture();
  7013. texture.isCube = true;
  7014. texture.url = rootUrl;
  7015. texture.references = 1;
  7016. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7017. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7018. if (isDDS) {
  7019. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7020. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7021. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7022. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7023. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7024. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7025. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7026. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7027. }
  7028. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7029. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7030. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7031. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7032. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7033. _this.resetTextureCache();
  7034. texture._width = info.width;
  7035. texture._height = info.height;
  7036. texture.isReady = true;
  7037. }, null, null, true);
  7038. }
  7039. else {
  7040. cascadeLoad(rootUrl, scene, function (imgs) {
  7041. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7042. var height = width;
  7043. _this._prepareWorkingCanvas();
  7044. _this._workingCanvas.width = width;
  7045. _this._workingCanvas.height = height;
  7046. var faces = [
  7047. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7048. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7049. ];
  7050. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7051. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7052. for (var index = 0; index < faces.length; index++) {
  7053. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7054. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7055. }
  7056. if (!noMipmap) {
  7057. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7058. }
  7059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7063. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7064. _this.resetTextureCache();
  7065. texture._width = width;
  7066. texture._height = height;
  7067. texture.isReady = true;
  7068. }, files);
  7069. }
  7070. return texture;
  7071. };
  7072. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7073. texture._width = width;
  7074. texture._height = height;
  7075. texture._size = width * height;
  7076. texture._baseWidth = width;
  7077. texture._baseHeight = height;
  7078. };
  7079. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7080. var _this = this;
  7081. var gl = this._gl;
  7082. var texture = gl.createTexture();
  7083. scene._addPendingData(texture);
  7084. texture.isCube = true;
  7085. texture.references = 1;
  7086. texture.url = url;
  7087. var internalFormat = this._getInternalFormat(format);
  7088. var textureType = gl.UNSIGNED_BYTE;
  7089. if (type === Engine.TEXTURETYPE_FLOAT) {
  7090. textureType = gl.FLOAT;
  7091. }
  7092. var width = size;
  7093. var height = width;
  7094. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7095. texture._width = width;
  7096. texture._height = height;
  7097. var onerror = function () {
  7098. scene._removePendingData(texture);
  7099. };
  7100. var internalCallback = function (data) {
  7101. var rgbeDataArrays = callback(data);
  7102. var facesIndex = [
  7103. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7104. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7105. ];
  7106. width = texture._width;
  7107. height = texture._height;
  7108. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7109. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7110. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7111. if (!noMipmap && isPot) {
  7112. if (mipmmapGenerator) {
  7113. var arrayTemp = [];
  7114. // Data are known to be in +X +Y +Z -X -Y -Z
  7115. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7116. arrayTemp.push(rgbeDataArrays[0]); // +X
  7117. arrayTemp.push(rgbeDataArrays[3]); // -X
  7118. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7119. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7120. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7121. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7122. var mipData = mipmmapGenerator(arrayTemp);
  7123. for (var level = 0; level < mipData.length; level++) {
  7124. var mipSize = width >> level;
  7125. // mipData is order in +X -X +Y -Y +Z -Z
  7126. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7127. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7128. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7129. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7130. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7131. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7132. }
  7133. }
  7134. else {
  7135. // Data are known to be in +X +Y +Z -X -Y -Z
  7136. for (var index = 0; index < facesIndex.length; index++) {
  7137. var faceData = rgbeDataArrays[index];
  7138. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7139. }
  7140. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7141. }
  7142. }
  7143. else {
  7144. noMipmap = true;
  7145. }
  7146. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7147. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7149. }
  7150. else {
  7151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7153. }
  7154. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7155. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7156. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7157. texture.isReady = true;
  7158. _this.resetTextureCache();
  7159. scene._removePendingData(texture);
  7160. };
  7161. BABYLON.Tools.LoadFile(url, function (data) {
  7162. internalCallback(data);
  7163. }, onerror, scene.database, true);
  7164. return texture;
  7165. };
  7166. ;
  7167. Engine.prototype._releaseTexture = function (texture) {
  7168. var gl = this._gl;
  7169. if (texture._framebuffer) {
  7170. gl.deleteFramebuffer(texture._framebuffer);
  7171. }
  7172. if (texture._depthBuffer) {
  7173. gl.deleteRenderbuffer(texture._depthBuffer);
  7174. }
  7175. gl.deleteTexture(texture);
  7176. // Unbind channels
  7177. this.unbindAllTextures();
  7178. var index = this._loadedTexturesCache.indexOf(texture);
  7179. if (index !== -1) {
  7180. this._loadedTexturesCache.splice(index, 1);
  7181. }
  7182. };
  7183. Engine.prototype.bindSamplers = function (effect) {
  7184. this._gl.useProgram(effect.getProgram());
  7185. var samplers = effect.getSamplers();
  7186. for (var index = 0; index < samplers.length; index++) {
  7187. var uniform = effect.getUniform(samplers[index]);
  7188. this._gl.uniform1i(uniform, index);
  7189. }
  7190. this._currentEffect = null;
  7191. };
  7192. Engine.prototype._bindTexture = function (channel, texture) {
  7193. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7194. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7195. this._activeTexturesCache[channel] = null;
  7196. };
  7197. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7198. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7199. };
  7200. Engine.prototype.unbindAllTextures = function () {
  7201. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7202. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7203. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7204. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7205. this._activeTexturesCache[channel] = null;
  7206. }
  7207. };
  7208. Engine.prototype.setTexture = function (channel, texture) {
  7209. if (channel < 0) {
  7210. return;
  7211. }
  7212. // Not ready?
  7213. if (!texture || !texture.isReady()) {
  7214. if (this._activeTexturesCache[channel] != null) {
  7215. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7216. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7217. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7218. this._activeTexturesCache[channel] = null;
  7219. }
  7220. return;
  7221. }
  7222. // Video
  7223. var alreadyActivated = false;
  7224. if (texture instanceof BABYLON.VideoTexture) {
  7225. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7226. alreadyActivated = true;
  7227. texture.update();
  7228. }
  7229. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7230. texture.delayLoad();
  7231. return;
  7232. }
  7233. if (this._activeTexturesCache[channel] === texture) {
  7234. return;
  7235. }
  7236. this._activeTexturesCache[channel] = texture;
  7237. var internalTexture = texture.getInternalTexture();
  7238. if (!alreadyActivated) {
  7239. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7240. }
  7241. if (internalTexture.isCube) {
  7242. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7243. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7244. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7245. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7246. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7247. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7248. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7249. }
  7250. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7251. }
  7252. else {
  7253. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7254. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7255. internalTexture._cachedWrapU = texture.wrapU;
  7256. switch (texture.wrapU) {
  7257. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7258. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7259. break;
  7260. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7261. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7262. break;
  7263. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7264. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7265. break;
  7266. }
  7267. }
  7268. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7269. internalTexture._cachedWrapV = texture.wrapV;
  7270. switch (texture.wrapV) {
  7271. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7272. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7273. break;
  7274. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7275. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7276. break;
  7277. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7278. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7279. break;
  7280. }
  7281. }
  7282. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7283. }
  7284. };
  7285. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7286. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7287. var value = texture.anisotropicFilteringLevel;
  7288. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7289. value = 1;
  7290. }
  7291. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7292. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7293. texture._cachedAnisotropicFilteringLevel = value;
  7294. }
  7295. };
  7296. Engine.prototype.readPixels = function (x, y, width, height) {
  7297. var data = new Uint8Array(height * width * 4);
  7298. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7299. return data;
  7300. };
  7301. /**
  7302. * Add an externaly attached data from its key.
  7303. * This method call will fail and return false, if such key already exists.
  7304. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7305. * @param key the unique key that identifies the data
  7306. * @param data the data object to associate to the key for this Engine instance
  7307. * @return true if no such key were already present and the data was added successfully, false otherwise
  7308. */
  7309. Engine.prototype.addExternalData = function (key, data) {
  7310. return this._externalData.add(key, data);
  7311. };
  7312. /**
  7313. * Get an externaly attached data from its key
  7314. * @param key the unique key that identifies the data
  7315. * @return the associated data, if present (can be null), or undefined if not present
  7316. */
  7317. Engine.prototype.getExternalData = function (key) {
  7318. return this._externalData.get(key);
  7319. };
  7320. /**
  7321. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7322. * @param key the unique key that identifies the data
  7323. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7324. * @return the associated data, can be null if the factory returned null.
  7325. */
  7326. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7327. return this._externalData.getOrAddWithFactory(key, factory);
  7328. };
  7329. /**
  7330. * Remove an externaly attached data from the Engine instance
  7331. * @param key the unique key that identifies the data
  7332. * @return true if the data was successfully removed, false if it doesn't exist
  7333. */
  7334. Engine.prototype.removeExternalData = function (key) {
  7335. return this._externalData.remove(key);
  7336. };
  7337. Engine.prototype.releaseInternalTexture = function (texture) {
  7338. if (!texture) {
  7339. return;
  7340. }
  7341. texture.references--;
  7342. // Final reference ?
  7343. if (texture.references === 0) {
  7344. var texturesCache = this.getLoadedTexturesCache();
  7345. var index = texturesCache.indexOf(texture);
  7346. if (index > -1) {
  7347. texturesCache.splice(index, 1);
  7348. }
  7349. this._releaseTexture(texture);
  7350. }
  7351. };
  7352. // Dispose
  7353. Engine.prototype.dispose = function () {
  7354. this.hideLoadingUI();
  7355. this.stopRenderLoop();
  7356. // Release scenes
  7357. while (this.scenes.length) {
  7358. this.scenes[0].dispose();
  7359. }
  7360. // Release audio engine
  7361. Engine.audioEngine.dispose();
  7362. // Release effects
  7363. for (var name in this._compiledEffects) {
  7364. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7365. }
  7366. // Unbind
  7367. for (var i in this._vertexAttribArrays) {
  7368. //making sure this is a string
  7369. var iAsNumber = +i;
  7370. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7371. continue;
  7372. }
  7373. this._gl.disableVertexAttribArray(iAsNumber);
  7374. }
  7375. this._gl = null;
  7376. // Events
  7377. window.removeEventListener("blur", this._onBlur);
  7378. window.removeEventListener("focus", this._onFocus);
  7379. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7380. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7381. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7382. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7383. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7384. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7385. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7386. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7387. };
  7388. // Loading screen
  7389. Engine.prototype.displayLoadingUI = function () {
  7390. this._loadingScreen.displayLoadingUI();
  7391. };
  7392. Engine.prototype.hideLoadingUI = function () {
  7393. this._loadingScreen.hideLoadingUI();
  7394. };
  7395. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7396. get: function () {
  7397. return this._loadingScreen;
  7398. },
  7399. set: function (loadingScreen) {
  7400. this._loadingScreen = loadingScreen;
  7401. },
  7402. enumerable: true,
  7403. configurable: true
  7404. });
  7405. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7406. set: function (text) {
  7407. this._loadingScreen.loadingUIText = text;
  7408. },
  7409. enumerable: true,
  7410. configurable: true
  7411. });
  7412. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7413. set: function (color) {
  7414. this._loadingScreen.loadingUIBackgroundColor = color;
  7415. },
  7416. enumerable: true,
  7417. configurable: true
  7418. });
  7419. // FPS
  7420. Engine.prototype.getFps = function () {
  7421. return this.fps;
  7422. };
  7423. Engine.prototype.getDeltaTime = function () {
  7424. return this.deltaTime;
  7425. };
  7426. Engine.prototype._measureFps = function () {
  7427. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7428. var length = this.previousFramesDuration.length;
  7429. if (length >= 2) {
  7430. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7431. }
  7432. if (length >= this.fpsRange) {
  7433. if (length > this.fpsRange) {
  7434. this.previousFramesDuration.splice(0, 1);
  7435. length = this.previousFramesDuration.length;
  7436. }
  7437. var sum = 0;
  7438. for (var id = 0; id < length - 1; id++) {
  7439. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7440. }
  7441. this.fps = 1000.0 / (sum / (length - 1));
  7442. }
  7443. };
  7444. // Statics
  7445. Engine.isSupported = function () {
  7446. try {
  7447. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7448. if (navigator.isCocoonJS) {
  7449. return true;
  7450. }
  7451. var tempcanvas = document.createElement("canvas");
  7452. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7453. return gl != null && !!window.WebGLRenderingContext;
  7454. }
  7455. catch (e) {
  7456. return false;
  7457. }
  7458. };
  7459. // Const statics
  7460. Engine._ALPHA_DISABLE = 0;
  7461. Engine._ALPHA_ADD = 1;
  7462. Engine._ALPHA_COMBINE = 2;
  7463. Engine._ALPHA_SUBTRACT = 3;
  7464. Engine._ALPHA_MULTIPLY = 4;
  7465. Engine._ALPHA_MAXIMIZED = 5;
  7466. Engine._ALPHA_ONEONE = 6;
  7467. Engine._DELAYLOADSTATE_NONE = 0;
  7468. Engine._DELAYLOADSTATE_LOADED = 1;
  7469. Engine._DELAYLOADSTATE_LOADING = 2;
  7470. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7471. Engine._TEXTUREFORMAT_ALPHA = 0;
  7472. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7473. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7474. Engine._TEXTUREFORMAT_RGB = 4;
  7475. Engine._TEXTUREFORMAT_RGBA = 5;
  7476. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7477. Engine._TEXTURETYPE_FLOAT = 1;
  7478. // Updatable statics so stick with vars here
  7479. Engine.CollisionsEpsilon = 0.001;
  7480. Engine.CodeRepository = "src/";
  7481. Engine.ShadersRepository = "src/Shaders/";
  7482. return Engine;
  7483. })();
  7484. BABYLON.Engine = Engine;
  7485. })(BABYLON || (BABYLON = {}));
  7486. var BABYLON;
  7487. (function (BABYLON) {
  7488. /**
  7489. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7490. */
  7491. var Node = (function () {
  7492. /**
  7493. * @constructor
  7494. * @param {string} name - the name and id to be given to this node
  7495. * @param {BABYLON.Scene} the scene this node will be added to
  7496. */
  7497. function Node(name, scene) {
  7498. this.state = "";
  7499. this.animations = new Array();
  7500. this._ranges = {};
  7501. this._childrenFlag = -1;
  7502. this._isEnabled = true;
  7503. this._isReady = true;
  7504. this._currentRenderId = -1;
  7505. this._parentRenderId = -1;
  7506. this.name = name;
  7507. this.id = name;
  7508. this._scene = scene;
  7509. this._initCache();
  7510. }
  7511. Object.defineProperty(Node.prototype, "parent", {
  7512. get: function () {
  7513. return this._parentNode;
  7514. },
  7515. set: function (parent) {
  7516. if (this._parentNode === parent) {
  7517. return;
  7518. }
  7519. if (this._parentNode) {
  7520. var index = this._parentNode._children.indexOf(this);
  7521. if (index !== -1) {
  7522. this._parentNode._children.splice(index, 1);
  7523. }
  7524. }
  7525. this._parentNode = parent;
  7526. if (this._parentNode) {
  7527. if (!this._parentNode._children) {
  7528. this._parentNode._children = new Array();
  7529. }
  7530. this._parentNode._children.push(this);
  7531. }
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. Node.prototype.getScene = function () {
  7537. return this._scene;
  7538. };
  7539. Node.prototype.getEngine = function () {
  7540. return this._scene.getEngine();
  7541. };
  7542. // override it in derived class
  7543. Node.prototype.getWorldMatrix = function () {
  7544. return BABYLON.Matrix.Identity();
  7545. };
  7546. // override it in derived class if you add new variables to the cache
  7547. // and call the parent class method
  7548. Node.prototype._initCache = function () {
  7549. this._cache = {};
  7550. this._cache.parent = undefined;
  7551. };
  7552. Node.prototype.updateCache = function (force) {
  7553. if (!force && this.isSynchronized())
  7554. return;
  7555. this._cache.parent = this.parent;
  7556. this._updateCache();
  7557. };
  7558. // override it in derived class if you add new variables to the cache
  7559. // and call the parent class method if !ignoreParentClass
  7560. Node.prototype._updateCache = function (ignoreParentClass) {
  7561. };
  7562. // override it in derived class if you add new variables to the cache
  7563. Node.prototype._isSynchronized = function () {
  7564. return true;
  7565. };
  7566. Node.prototype._markSyncedWithParent = function () {
  7567. this._parentRenderId = this.parent._currentRenderId;
  7568. };
  7569. Node.prototype.isSynchronizedWithParent = function () {
  7570. if (!this.parent) {
  7571. return true;
  7572. }
  7573. if (this._parentRenderId !== this.parent._currentRenderId) {
  7574. return false;
  7575. }
  7576. return this.parent.isSynchronized();
  7577. };
  7578. Node.prototype.isSynchronized = function (updateCache) {
  7579. var check = this.hasNewParent();
  7580. check = check || !this.isSynchronizedWithParent();
  7581. check = check || !this._isSynchronized();
  7582. if (updateCache)
  7583. this.updateCache(true);
  7584. return !check;
  7585. };
  7586. Node.prototype.hasNewParent = function (update) {
  7587. if (this._cache.parent === this.parent)
  7588. return false;
  7589. if (update)
  7590. this._cache.parent = this.parent;
  7591. return true;
  7592. };
  7593. /**
  7594. * Is this node ready to be used/rendered
  7595. * @return {boolean} is it ready
  7596. */
  7597. Node.prototype.isReady = function () {
  7598. return this._isReady;
  7599. };
  7600. /**
  7601. * Is this node enabled.
  7602. * If the node has a parent and is enabled, the parent will be inspected as well.
  7603. * @return {boolean} whether this node (and its parent) is enabled.
  7604. * @see setEnabled
  7605. */
  7606. Node.prototype.isEnabled = function () {
  7607. if (!this._isEnabled) {
  7608. return false;
  7609. }
  7610. if (this.parent) {
  7611. return this.parent.isEnabled();
  7612. }
  7613. return true;
  7614. };
  7615. /**
  7616. * Set the enabled state of this node.
  7617. * @param {boolean} value - the new enabled state
  7618. * @see isEnabled
  7619. */
  7620. Node.prototype.setEnabled = function (value) {
  7621. this._isEnabled = value;
  7622. };
  7623. /**
  7624. * Is this node a descendant of the given node.
  7625. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7626. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7627. * @see parent
  7628. */
  7629. Node.prototype.isDescendantOf = function (ancestor) {
  7630. if (this.parent) {
  7631. if (this.parent === ancestor) {
  7632. return true;
  7633. }
  7634. return this.parent.isDescendantOf(ancestor);
  7635. }
  7636. return false;
  7637. };
  7638. /**
  7639. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7640. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7641. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7642. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7643. */
  7644. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7645. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7646. if (!this._children) {
  7647. return;
  7648. }
  7649. for (var index = 0; index < this._children.length; index++) {
  7650. var item = this._children[index];
  7651. if (!predicate || predicate(item)) {
  7652. results.push(item);
  7653. }
  7654. if (!directDescendantsOnly) {
  7655. item._getDescendants(results, false, predicate);
  7656. }
  7657. }
  7658. };
  7659. /**
  7660. * Will return all nodes that have this node as ascendant.
  7661. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7662. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7663. * @return {BABYLON.Node[]} all children nodes of all types.
  7664. */
  7665. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7666. var results = [];
  7667. this._getDescendants(results, directDescendantsOnly, predicate);
  7668. return results;
  7669. };
  7670. /**
  7671. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7672. * @Deprecated, legacy support.
  7673. * use getDecendants instead.
  7674. */
  7675. Node.prototype.getChildren = function (predicate) {
  7676. return this.getDescendants(true, predicate);
  7677. };
  7678. /**
  7679. * Get all child-meshes of this node.
  7680. */
  7681. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7682. var results = [];
  7683. this._getDescendants(results, directDecendantsOnly, function (node) {
  7684. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7685. });
  7686. return results;
  7687. };
  7688. Node.prototype._setReady = function (state) {
  7689. if (state === this._isReady) {
  7690. return;
  7691. }
  7692. if (!state) {
  7693. this._isReady = false;
  7694. return;
  7695. }
  7696. this._isReady = true;
  7697. if (this.onReady) {
  7698. this.onReady(this);
  7699. }
  7700. };
  7701. Node.prototype.getAnimationByName = function (name) {
  7702. for (var i = 0; i < this.animations.length; i++) {
  7703. var animation = this.animations[i];
  7704. if (animation.name === name) {
  7705. return animation;
  7706. }
  7707. }
  7708. return null;
  7709. };
  7710. Node.prototype.createAnimationRange = function (name, from, to) {
  7711. // check name not already in use
  7712. if (!this._ranges[name]) {
  7713. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7714. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7715. if (this.animations[i]) {
  7716. this.animations[i].createRange(name, from, to);
  7717. }
  7718. }
  7719. }
  7720. };
  7721. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7722. if (deleteFrames === void 0) { deleteFrames = true; }
  7723. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7724. if (this.animations[i]) {
  7725. this.animations[i].deleteRange(name, deleteFrames);
  7726. }
  7727. }
  7728. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7729. };
  7730. Node.prototype.getAnimationRange = function (name) {
  7731. return this._ranges[name];
  7732. };
  7733. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7734. var range = this.getAnimationRange(name);
  7735. if (!range) {
  7736. return null;
  7737. }
  7738. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7739. };
  7740. Node.prototype.serializeAnimationRanges = function () {
  7741. var serializationRanges = [];
  7742. for (var name in this._ranges) {
  7743. var range = {};
  7744. range.name = name;
  7745. range.from = this._ranges[name].from;
  7746. range.to = this._ranges[name].to;
  7747. serializationRanges.push(range);
  7748. }
  7749. return serializationRanges;
  7750. };
  7751. Node.prototype.dispose = function () {
  7752. this.parent = null;
  7753. };
  7754. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7755. if (parsedNode.ranges) {
  7756. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7757. var data = parsedNode.ranges[index];
  7758. node.createAnimationRange(data.name, data.from, data.to);
  7759. }
  7760. }
  7761. };
  7762. __decorate([
  7763. BABYLON.serialize()
  7764. ], Node.prototype, "name", void 0);
  7765. __decorate([
  7766. BABYLON.serialize()
  7767. ], Node.prototype, "id", void 0);
  7768. __decorate([
  7769. BABYLON.serialize()
  7770. ], Node.prototype, "uniqueId", void 0);
  7771. __decorate([
  7772. BABYLON.serialize()
  7773. ], Node.prototype, "state", void 0);
  7774. return Node;
  7775. })();
  7776. BABYLON.Node = Node;
  7777. })(BABYLON || (BABYLON = {}));
  7778. var BABYLON;
  7779. (function (BABYLON) {
  7780. var FilesInput = (function () {
  7781. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7782. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7783. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7784. this._engine = p_engine;
  7785. this._canvas = p_canvas;
  7786. this._currentScene = p_scene;
  7787. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7788. this._progressCallback = p_progressCallback;
  7789. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7790. this._textureLoadingCallback = p_textureLoadingCallback;
  7791. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7792. }
  7793. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7794. var _this = this;
  7795. if (p_elementToMonitor) {
  7796. this._elementToMonitor = p_elementToMonitor;
  7797. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7798. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7799. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7800. }
  7801. };
  7802. FilesInput.prototype.renderFunction = function () {
  7803. if (this._additionnalRenderLoopLogicCallback) {
  7804. this._additionnalRenderLoopLogicCallback();
  7805. }
  7806. if (this._currentScene) {
  7807. if (this._textureLoadingCallback) {
  7808. var remaining = this._currentScene.getWaitingItemsCount();
  7809. if (remaining > 0) {
  7810. this._textureLoadingCallback(remaining);
  7811. }
  7812. }
  7813. this._currentScene.render();
  7814. }
  7815. };
  7816. FilesInput.prototype.drag = function (e) {
  7817. e.stopPropagation();
  7818. e.preventDefault();
  7819. };
  7820. FilesInput.prototype.drop = function (eventDrop) {
  7821. eventDrop.stopPropagation();
  7822. eventDrop.preventDefault();
  7823. this.loadFiles(eventDrop);
  7824. };
  7825. FilesInput.prototype.loadFiles = function (event) {
  7826. if (this._startingProcessingFilesCallback)
  7827. this._startingProcessingFilesCallback();
  7828. // Handling data transfer via drag'n'drop
  7829. if (event && event.dataTransfer && event.dataTransfer.files) {
  7830. this._filesToLoad = event.dataTransfer.files;
  7831. }
  7832. // Handling files from input files
  7833. if (event && event.target && event.target.files) {
  7834. this._filesToLoad = event.target.files;
  7835. }
  7836. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7837. for (var i = 0; i < this._filesToLoad.length; i++) {
  7838. switch (this._filesToLoad[i].type) {
  7839. case "image/jpeg":
  7840. case "image/png":
  7841. case "image/bmp":
  7842. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7843. break;
  7844. case "image/targa":
  7845. case "image/vnd.ms-dds":
  7846. case "audio/wav":
  7847. case "audio/x-wav":
  7848. case "audio/mp3":
  7849. case "audio/mpeg":
  7850. case "audio/mpeg3":
  7851. case "audio/x-mpeg-3":
  7852. case "audio/ogg":
  7853. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7854. break;
  7855. default:
  7856. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7857. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7858. }
  7859. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7860. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7861. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7862. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7863. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7864. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7865. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7866. this._sceneFileToLoad = this._filesToLoad[i];
  7867. }
  7868. break;
  7869. }
  7870. }
  7871. this.reload();
  7872. }
  7873. };
  7874. FilesInput.prototype.reload = function () {
  7875. var _this = this;
  7876. var that = this;
  7877. // If a ".babylon" file has been provided
  7878. if (this._sceneFileToLoad) {
  7879. if (this._currentScene) {
  7880. if (BABYLON.Tools.errorsCount > 0) {
  7881. BABYLON.Tools.ClearLogCache();
  7882. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7883. }
  7884. this._engine.stopRenderLoop();
  7885. this._currentScene.dispose();
  7886. }
  7887. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7888. that._currentScene = newScene;
  7889. // Wait for textures and shaders to be ready
  7890. that._currentScene.executeWhenReady(function () {
  7891. // Attach camera to canvas inputs
  7892. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7893. that._currentScene.createDefaultCameraOrLight();
  7894. }
  7895. that._currentScene.activeCamera.attachControl(that._canvas);
  7896. if (that._sceneLoadedCallback) {
  7897. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7898. }
  7899. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7900. });
  7901. }, function (progress) {
  7902. if (_this._progressCallback) {
  7903. _this._progressCallback(progress);
  7904. }
  7905. });
  7906. }
  7907. else {
  7908. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7909. }
  7910. };
  7911. FilesInput.FilesTextures = new Array();
  7912. FilesInput.FilesToLoad = new Array();
  7913. return FilesInput;
  7914. })();
  7915. BABYLON.FilesInput = FilesInput;
  7916. })(BABYLON || (BABYLON = {}));
  7917. var BABYLON;
  7918. (function (BABYLON) {
  7919. var IntersectionInfo = (function () {
  7920. function IntersectionInfo(bu, bv, distance) {
  7921. this.bu = bu;
  7922. this.bv = bv;
  7923. this.distance = distance;
  7924. this.faceId = 0;
  7925. this.subMeshId = 0;
  7926. }
  7927. return IntersectionInfo;
  7928. })();
  7929. BABYLON.IntersectionInfo = IntersectionInfo;
  7930. var PickingInfo = (function () {
  7931. function PickingInfo() {
  7932. this.hit = false;
  7933. this.distance = 0;
  7934. this.pickedPoint = null;
  7935. this.pickedMesh = null;
  7936. this.bu = 0;
  7937. this.bv = 0;
  7938. this.faceId = -1;
  7939. this.subMeshId = 0;
  7940. this.pickedSprite = null;
  7941. }
  7942. // Methods
  7943. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7944. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7945. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7946. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7947. return null;
  7948. }
  7949. var indices = this.pickedMesh.getIndices();
  7950. var result;
  7951. if (useVerticesNormals) {
  7952. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7953. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7954. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7955. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7956. normal0 = normal0.scale(this.bu);
  7957. normal1 = normal1.scale(this.bv);
  7958. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7959. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7960. }
  7961. else {
  7962. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7963. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7964. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7965. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7966. var p1p2 = vertex1.subtract(vertex2);
  7967. var p3p2 = vertex3.subtract(vertex2);
  7968. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7969. }
  7970. if (useWorldCoordinates) {
  7971. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7972. }
  7973. return BABYLON.Vector3.Normalize(result);
  7974. };
  7975. PickingInfo.prototype.getTextureCoordinates = function () {
  7976. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7977. return null;
  7978. }
  7979. var indices = this.pickedMesh.getIndices();
  7980. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7981. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7982. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7983. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7984. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7985. uv1 = uv1.scale(this.bu);
  7986. uv2 = uv2.scale(this.bv);
  7987. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7988. };
  7989. return PickingInfo;
  7990. })();
  7991. BABYLON.PickingInfo = PickingInfo;
  7992. })(BABYLON || (BABYLON = {}));
  7993. var BABYLON;
  7994. (function (BABYLON) {
  7995. var BoundingSphere = (function () {
  7996. function BoundingSphere(minimum, maximum) {
  7997. this.minimum = minimum;
  7998. this.maximum = maximum;
  7999. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8000. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8001. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8002. this.radius = distance * 0.5;
  8003. this.centerWorld = BABYLON.Vector3.Zero();
  8004. this._update(BABYLON.Matrix.Identity());
  8005. }
  8006. // Methods
  8007. BoundingSphere.prototype._update = function (world) {
  8008. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8009. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8010. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8011. };
  8012. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8013. for (var i = 0; i < 6; i++) {
  8014. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8015. return false;
  8016. }
  8017. return true;
  8018. };
  8019. BoundingSphere.prototype.intersectsPoint = function (point) {
  8020. var x = this.centerWorld.x - point.x;
  8021. var y = this.centerWorld.y - point.y;
  8022. var z = this.centerWorld.z - point.z;
  8023. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8024. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8025. return false;
  8026. return true;
  8027. };
  8028. // Statics
  8029. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8030. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8031. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8032. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8033. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8034. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8035. return false;
  8036. return true;
  8037. };
  8038. return BoundingSphere;
  8039. })();
  8040. BABYLON.BoundingSphere = BoundingSphere;
  8041. })(BABYLON || (BABYLON = {}));
  8042. var BABYLON;
  8043. (function (BABYLON) {
  8044. var BoundingBox = (function () {
  8045. function BoundingBox(minimum, maximum) {
  8046. this.minimum = minimum;
  8047. this.maximum = maximum;
  8048. this.vectors = new Array();
  8049. this.vectorsWorld = new Array();
  8050. // Bounding vectors
  8051. this.vectors.push(this.minimum.clone());
  8052. this.vectors.push(this.maximum.clone());
  8053. this.vectors.push(this.minimum.clone());
  8054. this.vectors[2].x = this.maximum.x;
  8055. this.vectors.push(this.minimum.clone());
  8056. this.vectors[3].y = this.maximum.y;
  8057. this.vectors.push(this.minimum.clone());
  8058. this.vectors[4].z = this.maximum.z;
  8059. this.vectors.push(this.maximum.clone());
  8060. this.vectors[5].z = this.minimum.z;
  8061. this.vectors.push(this.maximum.clone());
  8062. this.vectors[6].x = this.minimum.x;
  8063. this.vectors.push(this.maximum.clone());
  8064. this.vectors[7].y = this.minimum.y;
  8065. // OBB
  8066. this.center = this.maximum.add(this.minimum).scale(0.5);
  8067. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8068. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8069. // World
  8070. for (var index = 0; index < this.vectors.length; index++) {
  8071. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8072. }
  8073. this.minimumWorld = BABYLON.Vector3.Zero();
  8074. this.maximumWorld = BABYLON.Vector3.Zero();
  8075. this._update(BABYLON.Matrix.Identity());
  8076. }
  8077. // Methods
  8078. BoundingBox.prototype.getWorldMatrix = function () {
  8079. return this._worldMatrix;
  8080. };
  8081. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8082. this._worldMatrix.copyFrom(matrix);
  8083. return this;
  8084. };
  8085. BoundingBox.prototype._update = function (world) {
  8086. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8087. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8088. for (var index = 0; index < this.vectors.length; index++) {
  8089. var v = this.vectorsWorld[index];
  8090. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8091. if (v.x < this.minimumWorld.x)
  8092. this.minimumWorld.x = v.x;
  8093. if (v.y < this.minimumWorld.y)
  8094. this.minimumWorld.y = v.y;
  8095. if (v.z < this.minimumWorld.z)
  8096. this.minimumWorld.z = v.z;
  8097. if (v.x > this.maximumWorld.x)
  8098. this.maximumWorld.x = v.x;
  8099. if (v.y > this.maximumWorld.y)
  8100. this.maximumWorld.y = v.y;
  8101. if (v.z > this.maximumWorld.z)
  8102. this.maximumWorld.z = v.z;
  8103. }
  8104. // OBB
  8105. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8106. this.center.scaleInPlace(0.5);
  8107. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8108. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8109. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8110. this._worldMatrix = world;
  8111. };
  8112. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8113. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8114. };
  8115. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8116. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8117. };
  8118. BoundingBox.prototype.intersectsPoint = function (point) {
  8119. var delta = -BABYLON.Epsilon;
  8120. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8121. return false;
  8122. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8123. return false;
  8124. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8125. return false;
  8126. return true;
  8127. };
  8128. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8129. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8130. };
  8131. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8132. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8133. return false;
  8134. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8135. return false;
  8136. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8137. return false;
  8138. return true;
  8139. };
  8140. // Statics
  8141. BoundingBox.Intersects = function (box0, box1) {
  8142. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8143. return false;
  8144. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8145. return false;
  8146. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8147. return false;
  8148. return true;
  8149. };
  8150. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8151. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8152. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8153. return (num <= (sphereRadius * sphereRadius));
  8154. };
  8155. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8156. for (var p = 0; p < 6; p++) {
  8157. for (var i = 0; i < 8; i++) {
  8158. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8159. return false;
  8160. }
  8161. }
  8162. }
  8163. return true;
  8164. };
  8165. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8166. for (var p = 0; p < 6; p++) {
  8167. var inCount = 8;
  8168. for (var i = 0; i < 8; i++) {
  8169. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8170. --inCount;
  8171. }
  8172. else {
  8173. break;
  8174. }
  8175. }
  8176. if (inCount === 0)
  8177. return false;
  8178. }
  8179. return true;
  8180. };
  8181. return BoundingBox;
  8182. })();
  8183. BABYLON.BoundingBox = BoundingBox;
  8184. })(BABYLON || (BABYLON = {}));
  8185. var BABYLON;
  8186. (function (BABYLON) {
  8187. var computeBoxExtents = function (axis, box) {
  8188. var p = BABYLON.Vector3.Dot(box.center, axis);
  8189. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8190. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8191. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8192. var r = r0 + r1 + r2;
  8193. return {
  8194. min: p - r,
  8195. max: p + r
  8196. };
  8197. };
  8198. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8199. var axisOverlap = function (axis, box0, box1) {
  8200. var result0 = computeBoxExtents(axis, box0);
  8201. var result1 = computeBoxExtents(axis, box1);
  8202. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8203. };
  8204. var BoundingInfo = (function () {
  8205. function BoundingInfo(minimum, maximum) {
  8206. this.minimum = minimum;
  8207. this.maximum = maximum;
  8208. this._isLocked = false;
  8209. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8210. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8211. }
  8212. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8213. get: function () {
  8214. return this._isLocked;
  8215. },
  8216. set: function (value) {
  8217. this._isLocked = value;
  8218. },
  8219. enumerable: true,
  8220. configurable: true
  8221. });
  8222. // Methods
  8223. BoundingInfo.prototype.update = function (world) {
  8224. if (this._isLocked) {
  8225. return;
  8226. }
  8227. this.boundingBox._update(world);
  8228. this.boundingSphere._update(world);
  8229. };
  8230. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8231. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8232. return false;
  8233. return this.boundingBox.isInFrustum(frustumPlanes);
  8234. };
  8235. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8236. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8237. };
  8238. BoundingInfo.prototype._checkCollision = function (collider) {
  8239. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8240. };
  8241. BoundingInfo.prototype.intersectsPoint = function (point) {
  8242. if (!this.boundingSphere.centerWorld) {
  8243. return false;
  8244. }
  8245. if (!this.boundingSphere.intersectsPoint(point)) {
  8246. return false;
  8247. }
  8248. if (!this.boundingBox.intersectsPoint(point)) {
  8249. return false;
  8250. }
  8251. return true;
  8252. };
  8253. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8254. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8255. return false;
  8256. }
  8257. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8258. return false;
  8259. }
  8260. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8261. return false;
  8262. }
  8263. if (!precise) {
  8264. return true;
  8265. }
  8266. var box0 = this.boundingBox;
  8267. var box1 = boundingInfo.boundingBox;
  8268. if (!axisOverlap(box0.directions[0], box0, box1))
  8269. return false;
  8270. if (!axisOverlap(box0.directions[1], box0, box1))
  8271. return false;
  8272. if (!axisOverlap(box0.directions[2], box0, box1))
  8273. return false;
  8274. if (!axisOverlap(box1.directions[0], box0, box1))
  8275. return false;
  8276. if (!axisOverlap(box1.directions[1], box0, box1))
  8277. return false;
  8278. if (!axisOverlap(box1.directions[2], box0, box1))
  8279. return false;
  8280. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8281. return false;
  8282. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8283. return false;
  8284. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8285. return false;
  8286. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8287. return false;
  8288. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8289. return false;
  8290. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8291. return false;
  8292. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8293. return false;
  8294. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8295. return false;
  8296. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8297. return false;
  8298. return true;
  8299. };
  8300. return BoundingInfo;
  8301. })();
  8302. BABYLON.BoundingInfo = BoundingInfo;
  8303. })(BABYLON || (BABYLON = {}));
  8304. var BABYLON;
  8305. (function (BABYLON) {
  8306. var Ray = (function () {
  8307. function Ray(origin, direction, length) {
  8308. if (length === void 0) { length = Number.MAX_VALUE; }
  8309. this.origin = origin;
  8310. this.direction = direction;
  8311. this.length = length;
  8312. }
  8313. // Methods
  8314. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8315. var d = 0.0;
  8316. var maxValue = Number.MAX_VALUE;
  8317. var inv;
  8318. var min;
  8319. var max;
  8320. var temp;
  8321. if (Math.abs(this.direction.x) < 0.0000001) {
  8322. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8323. return false;
  8324. }
  8325. }
  8326. else {
  8327. inv = 1.0 / this.direction.x;
  8328. min = (minimum.x - this.origin.x) * inv;
  8329. max = (maximum.x - this.origin.x) * inv;
  8330. if (max === -Infinity) {
  8331. max = Infinity;
  8332. }
  8333. if (min > max) {
  8334. temp = min;
  8335. min = max;
  8336. max = temp;
  8337. }
  8338. d = Math.max(min, d);
  8339. maxValue = Math.min(max, maxValue);
  8340. if (d > maxValue) {
  8341. return false;
  8342. }
  8343. }
  8344. if (Math.abs(this.direction.y) < 0.0000001) {
  8345. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8346. return false;
  8347. }
  8348. }
  8349. else {
  8350. inv = 1.0 / this.direction.y;
  8351. min = (minimum.y - this.origin.y) * inv;
  8352. max = (maximum.y - this.origin.y) * inv;
  8353. if (max === -Infinity) {
  8354. max = Infinity;
  8355. }
  8356. if (min > max) {
  8357. temp = min;
  8358. min = max;
  8359. max = temp;
  8360. }
  8361. d = Math.max(min, d);
  8362. maxValue = Math.min(max, maxValue);
  8363. if (d > maxValue) {
  8364. return false;
  8365. }
  8366. }
  8367. if (Math.abs(this.direction.z) < 0.0000001) {
  8368. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8369. return false;
  8370. }
  8371. }
  8372. else {
  8373. inv = 1.0 / this.direction.z;
  8374. min = (minimum.z - this.origin.z) * inv;
  8375. max = (maximum.z - this.origin.z) * inv;
  8376. if (max === -Infinity) {
  8377. max = Infinity;
  8378. }
  8379. if (min > max) {
  8380. temp = min;
  8381. min = max;
  8382. max = temp;
  8383. }
  8384. d = Math.max(min, d);
  8385. maxValue = Math.min(max, maxValue);
  8386. if (d > maxValue) {
  8387. return false;
  8388. }
  8389. }
  8390. return true;
  8391. };
  8392. Ray.prototype.intersectsBox = function (box) {
  8393. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8394. };
  8395. Ray.prototype.intersectsSphere = function (sphere) {
  8396. var x = sphere.center.x - this.origin.x;
  8397. var y = sphere.center.y - this.origin.y;
  8398. var z = sphere.center.z - this.origin.z;
  8399. var pyth = (x * x) + (y * y) + (z * z);
  8400. var rr = sphere.radius * sphere.radius;
  8401. if (pyth <= rr) {
  8402. return true;
  8403. }
  8404. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8405. if (dot < 0.0) {
  8406. return false;
  8407. }
  8408. var temp = pyth - (dot * dot);
  8409. return temp <= rr;
  8410. };
  8411. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8412. if (!this._edge1) {
  8413. this._edge1 = BABYLON.Vector3.Zero();
  8414. this._edge2 = BABYLON.Vector3.Zero();
  8415. this._pvec = BABYLON.Vector3.Zero();
  8416. this._tvec = BABYLON.Vector3.Zero();
  8417. this._qvec = BABYLON.Vector3.Zero();
  8418. }
  8419. vertex1.subtractToRef(vertex0, this._edge1);
  8420. vertex2.subtractToRef(vertex0, this._edge2);
  8421. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8422. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8423. if (det === 0) {
  8424. return null;
  8425. }
  8426. var invdet = 1 / det;
  8427. this.origin.subtractToRef(vertex0, this._tvec);
  8428. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8429. if (bu < 0 || bu > 1.0) {
  8430. return null;
  8431. }
  8432. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8433. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8434. if (bv < 0 || bu + bv > 1.0) {
  8435. return null;
  8436. }
  8437. //check if the distance is longer than the predefined length.
  8438. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8439. if (distance > this.length) {
  8440. return null;
  8441. }
  8442. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8443. };
  8444. Ray.prototype.intersectsPlane = function (plane) {
  8445. var distance;
  8446. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8447. if (Math.abs(result1) < 9.99999997475243E-07) {
  8448. return null;
  8449. }
  8450. else {
  8451. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8452. distance = (-plane.d - result2) / result1;
  8453. if (distance < 0.0) {
  8454. if (distance < -9.99999997475243E-07) {
  8455. return null;
  8456. }
  8457. else {
  8458. return 0;
  8459. }
  8460. }
  8461. return distance;
  8462. }
  8463. };
  8464. /**
  8465. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8466. * @param sega the first point of the segment to test the intersection against
  8467. * @param segb the second point of the segment to test the intersection against
  8468. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8469. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8470. */
  8471. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8472. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8473. var u = segb.subtract(sega);
  8474. var v = rsegb.subtract(this.origin);
  8475. var w = sega.subtract(this.origin);
  8476. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8477. var b = BABYLON.Vector3.Dot(u, v);
  8478. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8479. var d = BABYLON.Vector3.Dot(u, w);
  8480. var e = BABYLON.Vector3.Dot(v, w);
  8481. var D = a * c - b * b; // always >= 0
  8482. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8483. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8484. // compute the line parameters of the two closest points
  8485. if (D < Ray.smallnum) {
  8486. sN = 0.0; // force using point P0 on segment S1
  8487. sD = 1.0; // to prevent possible division by 0.0 later
  8488. tN = e;
  8489. tD = c;
  8490. }
  8491. else {
  8492. sN = (b * e - c * d);
  8493. tN = (a * e - b * d);
  8494. if (sN < 0.0) {
  8495. sN = 0.0;
  8496. tN = e;
  8497. tD = c;
  8498. }
  8499. else if (sN > sD) {
  8500. sN = sD;
  8501. tN = e + b;
  8502. tD = c;
  8503. }
  8504. }
  8505. if (tN < 0.0) {
  8506. tN = 0.0;
  8507. // recompute sc for this edge
  8508. if (-d < 0.0) {
  8509. sN = 0.0;
  8510. }
  8511. else if (-d > a)
  8512. sN = sD;
  8513. else {
  8514. sN = -d;
  8515. sD = a;
  8516. }
  8517. }
  8518. else if (tN > tD) {
  8519. tN = tD;
  8520. // recompute sc for this edge
  8521. if ((-d + b) < 0.0) {
  8522. sN = 0;
  8523. }
  8524. else if ((-d + b) > a) {
  8525. sN = sD;
  8526. }
  8527. else {
  8528. sN = (-d + b);
  8529. sD = a;
  8530. }
  8531. }
  8532. // finally do the division to get sc and tc
  8533. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8534. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8535. // get the difference of the two closest points
  8536. var qtc = v.multiplyByFloats(tc, tc, tc);
  8537. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8538. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8539. if (isIntersected) {
  8540. return qtc.length();
  8541. }
  8542. return -1;
  8543. };
  8544. // Statics
  8545. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8546. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8547. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8548. var direction = end.subtract(start);
  8549. direction.normalize();
  8550. return new Ray(start, direction);
  8551. };
  8552. /**
  8553. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  8554. * transformed to the given world matrix.
  8555. * @param origin The origin point
  8556. * @param end The end point
  8557. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8558. */
  8559. Ray.CreateNewFromTo = function (origin, end, world) {
  8560. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8561. var direction = end.subtract(origin);
  8562. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8563. direction.normalize();
  8564. return Ray.Transform(new Ray(origin, direction, length), world);
  8565. };
  8566. Ray.Transform = function (ray, matrix) {
  8567. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8568. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8569. newDirection.normalize();
  8570. return new Ray(newOrigin, newDirection, ray.length);
  8571. };
  8572. Ray.smallnum = 0.00000001;
  8573. Ray.rayl = 10e8;
  8574. return Ray;
  8575. })();
  8576. BABYLON.Ray = Ray;
  8577. })(BABYLON || (BABYLON = {}));
  8578. var BABYLON;
  8579. (function (BABYLON) {
  8580. var AbstractMesh = (function (_super) {
  8581. __extends(AbstractMesh, _super);
  8582. // Constructor
  8583. function AbstractMesh(name, scene) {
  8584. var _this = this;
  8585. _super.call(this, name, scene);
  8586. // Events
  8587. /**
  8588. * An event triggered when the mesh is disposed.
  8589. * @type {BABYLON.Observable}
  8590. */
  8591. this.onDisposeObservable = new BABYLON.Observable();
  8592. /**
  8593. * An event triggered when this mesh collides with another one
  8594. * @type {BABYLON.Observable}
  8595. */
  8596. this.onCollideObservable = new BABYLON.Observable();
  8597. /**
  8598. * An event triggered when the collision's position changes
  8599. * @type {BABYLON.Observable}
  8600. */
  8601. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8602. /**
  8603. * An event triggered after the world matrix is updated
  8604. * @type {BABYLON.Observable}
  8605. */
  8606. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8607. // Properties
  8608. this.definedFacingForward = true; // orientation for POV movement & rotation
  8609. this.position = new BABYLON.Vector3(0, 0, 0);
  8610. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8611. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8612. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8613. this.visibility = 1.0;
  8614. this.alphaIndex = Number.MAX_VALUE;
  8615. this.infiniteDistance = false;
  8616. this.isVisible = true;
  8617. this.isPickable = true;
  8618. this.showBoundingBox = false;
  8619. this.showSubMeshesBoundingBox = false;
  8620. this.isBlocker = false;
  8621. this.renderingGroupId = 0;
  8622. this.receiveShadows = false;
  8623. this.renderOutline = false;
  8624. this.outlineColor = BABYLON.Color3.Red();
  8625. this.outlineWidth = 0.02;
  8626. this.renderOverlay = false;
  8627. this.overlayColor = BABYLON.Color3.Red();
  8628. this.overlayAlpha = 0.5;
  8629. this.hasVertexAlpha = false;
  8630. this.useVertexColors = true;
  8631. this.applyFog = true;
  8632. this.computeBonesUsingShaders = true;
  8633. this.scalingDeterminant = 1;
  8634. this.numBoneInfluencers = 4;
  8635. this.useOctreeForRenderingSelection = true;
  8636. this.useOctreeForPicking = true;
  8637. this.useOctreeForCollisions = true;
  8638. this.layerMask = 0x0FFFFFFF;
  8639. this.alwaysSelectAsActiveMesh = false;
  8640. // Collisions
  8641. this._checkCollisions = false;
  8642. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8643. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8644. this._collider = new BABYLON.Collider();
  8645. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8646. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8647. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8648. // Edges
  8649. this.edgesWidth = 1;
  8650. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8651. // Cache
  8652. this._localWorld = BABYLON.Matrix.Zero();
  8653. this._worldMatrix = BABYLON.Matrix.Zero();
  8654. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8655. this._absolutePosition = BABYLON.Vector3.Zero();
  8656. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8657. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8658. this._isDirty = false;
  8659. this._pivotMatrix = BABYLON.Matrix.Identity();
  8660. this._isDisposed = false;
  8661. this._renderId = 0;
  8662. this._intersectionsInProgress = new Array();
  8663. this._isWorldMatrixFrozen = false;
  8664. this._unIndexed = false;
  8665. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8666. if (collidedMesh === void 0) { collidedMesh = null; }
  8667. //TODO move this to the collision coordinator!
  8668. if (_this.getScene().workerCollisions)
  8669. newPosition.multiplyInPlace(_this._collider.radius);
  8670. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8671. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8672. _this.position.addInPlace(_this._diffPositionForCollisions);
  8673. }
  8674. if (collidedMesh) {
  8675. _this.onCollideObservable.notifyObservers(collidedMesh);
  8676. }
  8677. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8678. };
  8679. scene.addMesh(this);
  8680. }
  8681. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8682. get: function () {
  8683. return AbstractMesh._BILLBOARDMODE_NONE;
  8684. },
  8685. enumerable: true,
  8686. configurable: true
  8687. });
  8688. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8689. get: function () {
  8690. return AbstractMesh._BILLBOARDMODE_X;
  8691. },
  8692. enumerable: true,
  8693. configurable: true
  8694. });
  8695. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8696. get: function () {
  8697. return AbstractMesh._BILLBOARDMODE_Y;
  8698. },
  8699. enumerable: true,
  8700. configurable: true
  8701. });
  8702. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8703. get: function () {
  8704. return AbstractMesh._BILLBOARDMODE_Z;
  8705. },
  8706. enumerable: true,
  8707. configurable: true
  8708. });
  8709. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8710. get: function () {
  8711. return AbstractMesh._BILLBOARDMODE_ALL;
  8712. },
  8713. enumerable: true,
  8714. configurable: true
  8715. });
  8716. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  8717. set: function (callback) {
  8718. if (this._onDisposeObserver) {
  8719. this.onDisposeObservable.remove(this._onDisposeObserver);
  8720. }
  8721. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  8722. },
  8723. enumerable: true,
  8724. configurable: true
  8725. });
  8726. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8727. set: function (callback) {
  8728. if (this._onCollideObserver) {
  8729. this.onCollideObservable.remove(this._onCollideObserver);
  8730. }
  8731. this._onCollideObserver = this.onCollideObservable.add(callback);
  8732. },
  8733. enumerable: true,
  8734. configurable: true
  8735. });
  8736. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8737. set: function (callback) {
  8738. if (this._onCollisionPositionChangeObserver) {
  8739. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8740. }
  8741. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8742. },
  8743. enumerable: true,
  8744. configurable: true
  8745. });
  8746. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8747. get: function () {
  8748. return this._skeleton;
  8749. },
  8750. set: function (value) {
  8751. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8752. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8753. }
  8754. if (value && value.needInitialSkinMatrix) {
  8755. value._registerMeshWithPoseMatrix(this);
  8756. }
  8757. this._skeleton = value;
  8758. if (!this._skeleton) {
  8759. this._bonesTransformMatrices = null;
  8760. }
  8761. },
  8762. enumerable: true,
  8763. configurable: true
  8764. });
  8765. /**
  8766. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8767. */
  8768. AbstractMesh.prototype.toString = function (fullDetails) {
  8769. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8770. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8771. if (this._skeleton) {
  8772. ret += ", skeleton: " + this._skeleton.name;
  8773. }
  8774. if (fullDetails) {
  8775. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8776. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8777. }
  8778. return ret;
  8779. };
  8780. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8781. /**
  8782. * Getting the rotation object.
  8783. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8784. */
  8785. get: function () {
  8786. return this._rotation;
  8787. },
  8788. set: function (newRotation) {
  8789. this._rotation = newRotation;
  8790. },
  8791. enumerable: true,
  8792. configurable: true
  8793. });
  8794. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8795. get: function () {
  8796. return this._scaling;
  8797. },
  8798. set: function (newScaling) {
  8799. this._scaling = newScaling;
  8800. if (this.physicsImpostor) {
  8801. this.physicsImpostor.forceUpdate();
  8802. }
  8803. },
  8804. enumerable: true,
  8805. configurable: true
  8806. });
  8807. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8808. get: function () {
  8809. return this._rotationQuaternion;
  8810. },
  8811. set: function (quaternion) {
  8812. this._rotationQuaternion = quaternion;
  8813. //reset the rotation vector.
  8814. if (quaternion && this.rotation.length()) {
  8815. this.rotation.copyFromFloats(0, 0, 0);
  8816. }
  8817. },
  8818. enumerable: true,
  8819. configurable: true
  8820. });
  8821. // Methods
  8822. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8823. this._poseMatrix.copyFrom(matrix);
  8824. };
  8825. AbstractMesh.prototype.getPoseMatrix = function () {
  8826. return this._poseMatrix;
  8827. };
  8828. AbstractMesh.prototype.disableEdgesRendering = function () {
  8829. if (this._edgesRenderer !== undefined) {
  8830. this._edgesRenderer.dispose();
  8831. this._edgesRenderer = undefined;
  8832. }
  8833. };
  8834. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8835. if (epsilon === void 0) { epsilon = 0.95; }
  8836. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8837. this.disableEdgesRendering();
  8838. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8839. };
  8840. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8841. get: function () {
  8842. return false;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. AbstractMesh.prototype.getLOD = function (camera) {
  8848. return this;
  8849. };
  8850. AbstractMesh.prototype.getTotalVertices = function () {
  8851. return 0;
  8852. };
  8853. AbstractMesh.prototype.getIndices = function () {
  8854. return null;
  8855. };
  8856. AbstractMesh.prototype.getVerticesData = function (kind) {
  8857. return null;
  8858. };
  8859. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8860. return false;
  8861. };
  8862. AbstractMesh.prototype.getBoundingInfo = function () {
  8863. if (this._masterMesh) {
  8864. return this._masterMesh.getBoundingInfo();
  8865. }
  8866. if (!this._boundingInfo) {
  8867. this._updateBoundingInfo();
  8868. }
  8869. return this._boundingInfo;
  8870. };
  8871. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8872. get: function () {
  8873. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8874. },
  8875. enumerable: true,
  8876. configurable: true
  8877. });
  8878. AbstractMesh.prototype._preActivate = function () {
  8879. };
  8880. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8881. };
  8882. AbstractMesh.prototype._activate = function (renderId) {
  8883. this._renderId = renderId;
  8884. };
  8885. AbstractMesh.prototype.getWorldMatrix = function () {
  8886. if (this._masterMesh) {
  8887. return this._masterMesh.getWorldMatrix();
  8888. }
  8889. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8890. this.computeWorldMatrix();
  8891. }
  8892. return this._worldMatrix;
  8893. };
  8894. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8895. get: function () {
  8896. return this._worldMatrix;
  8897. },
  8898. enumerable: true,
  8899. configurable: true
  8900. });
  8901. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8902. get: function () {
  8903. return this._absolutePosition;
  8904. },
  8905. enumerable: true,
  8906. configurable: true
  8907. });
  8908. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8909. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8910. this.computeWorldMatrix(true);
  8911. this._isWorldMatrixFrozen = true;
  8912. };
  8913. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8914. this._isWorldMatrixFrozen = false;
  8915. this.computeWorldMatrix(true);
  8916. };
  8917. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8918. get: function () {
  8919. return this._isWorldMatrixFrozen;
  8920. },
  8921. enumerable: true,
  8922. configurable: true
  8923. });
  8924. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8925. axis.normalize();
  8926. if (!this.rotationQuaternion) {
  8927. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8928. this.rotation = BABYLON.Vector3.Zero();
  8929. }
  8930. var rotationQuaternion;
  8931. if (!space || space === BABYLON.Space.LOCAL) {
  8932. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8933. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8934. }
  8935. else {
  8936. if (this.parent) {
  8937. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8938. invertParentWorldMatrix.invert();
  8939. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8940. }
  8941. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8942. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8943. }
  8944. };
  8945. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8946. var displacementVector = axis.scale(distance);
  8947. if (!space || space === BABYLON.Space.LOCAL) {
  8948. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8949. this.setPositionWithLocalVector(tempV3);
  8950. }
  8951. else {
  8952. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8953. }
  8954. };
  8955. AbstractMesh.prototype.getAbsolutePosition = function () {
  8956. this.computeWorldMatrix();
  8957. return this._absolutePosition;
  8958. };
  8959. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8960. if (!absolutePosition) {
  8961. return;
  8962. }
  8963. var absolutePositionX;
  8964. var absolutePositionY;
  8965. var absolutePositionZ;
  8966. if (absolutePosition.x === undefined) {
  8967. if (arguments.length < 3) {
  8968. return;
  8969. }
  8970. absolutePositionX = arguments[0];
  8971. absolutePositionY = arguments[1];
  8972. absolutePositionZ = arguments[2];
  8973. }
  8974. else {
  8975. absolutePositionX = absolutePosition.x;
  8976. absolutePositionY = absolutePosition.y;
  8977. absolutePositionZ = absolutePosition.z;
  8978. }
  8979. if (this.parent) {
  8980. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8981. invertParentWorldMatrix.invert();
  8982. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8983. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8984. }
  8985. else {
  8986. this.position.x = absolutePositionX;
  8987. this.position.y = absolutePositionY;
  8988. this.position.z = absolutePositionZ;
  8989. }
  8990. };
  8991. // ================================== Point of View Movement =================================
  8992. /**
  8993. * Perform relative position change from the point of view of behind the front of the mesh.
  8994. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8995. * Supports definition of mesh facing forward or backward.
  8996. * @param {number} amountRight
  8997. * @param {number} amountUp
  8998. * @param {number} amountForward
  8999. */
  9000. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9001. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9002. };
  9003. /**
  9004. * Calculate relative position change from the point of view of behind the front of the mesh.
  9005. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9006. * Supports definition of mesh facing forward or backward.
  9007. * @param {number} amountRight
  9008. * @param {number} amountUp
  9009. * @param {number} amountForward
  9010. */
  9011. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9012. var rotMatrix = new BABYLON.Matrix();
  9013. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9014. rotQuaternion.toRotationMatrix(rotMatrix);
  9015. var translationDelta = BABYLON.Vector3.Zero();
  9016. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9017. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9018. return translationDelta;
  9019. };
  9020. // ================================== Point of View Rotation =================================
  9021. /**
  9022. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9023. * Supports definition of mesh facing forward or backward.
  9024. * @param {number} flipBack
  9025. * @param {number} twirlClockwise
  9026. * @param {number} tiltRight
  9027. */
  9028. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9029. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9030. };
  9031. /**
  9032. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9033. * Supports definition of mesh facing forward or backward.
  9034. * @param {number} flipBack
  9035. * @param {number} twirlClockwise
  9036. * @param {number} tiltRight
  9037. */
  9038. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9039. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9040. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9041. };
  9042. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9043. this._pivotMatrix = matrix;
  9044. this._cache.pivotMatrixUpdated = true;
  9045. };
  9046. AbstractMesh.prototype.getPivotMatrix = function () {
  9047. return this._pivotMatrix;
  9048. };
  9049. AbstractMesh.prototype._isSynchronized = function () {
  9050. if (this._isDirty) {
  9051. return false;
  9052. }
  9053. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9054. return false;
  9055. if (this._cache.pivotMatrixUpdated) {
  9056. return false;
  9057. }
  9058. if (this.infiniteDistance) {
  9059. return false;
  9060. }
  9061. if (!this._cache.position.equals(this.position))
  9062. return false;
  9063. if (this.rotationQuaternion) {
  9064. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9065. return false;
  9066. }
  9067. else {
  9068. if (!this._cache.rotation.equals(this.rotation))
  9069. return false;
  9070. }
  9071. if (!this._cache.scaling.equals(this.scaling))
  9072. return false;
  9073. return true;
  9074. };
  9075. AbstractMesh.prototype._initCache = function () {
  9076. _super.prototype._initCache.call(this);
  9077. this._cache.localMatrixUpdated = false;
  9078. this._cache.position = BABYLON.Vector3.Zero();
  9079. this._cache.scaling = BABYLON.Vector3.Zero();
  9080. this._cache.rotation = BABYLON.Vector3.Zero();
  9081. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9082. this._cache.billboardMode = -1;
  9083. };
  9084. AbstractMesh.prototype.markAsDirty = function (property) {
  9085. if (property === "rotation") {
  9086. this.rotationQuaternion = null;
  9087. }
  9088. this._currentRenderId = Number.MAX_VALUE;
  9089. this._isDirty = true;
  9090. };
  9091. AbstractMesh.prototype._updateBoundingInfo = function () {
  9092. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9093. this._boundingInfo.update(this.worldMatrixFromCache);
  9094. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9095. };
  9096. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9097. if (!this.subMeshes) {
  9098. return;
  9099. }
  9100. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9101. var subMesh = this.subMeshes[subIndex];
  9102. if (!subMesh.IsGlobal) {
  9103. subMesh.updateBoundingInfo(matrix);
  9104. }
  9105. }
  9106. };
  9107. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9108. if (this._isWorldMatrixFrozen) {
  9109. return this._worldMatrix;
  9110. }
  9111. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9112. this._currentRenderId = this.getScene().getRenderId();
  9113. return this._worldMatrix;
  9114. }
  9115. this._cache.position.copyFrom(this.position);
  9116. this._cache.scaling.copyFrom(this.scaling);
  9117. this._cache.pivotMatrixUpdated = false;
  9118. this._cache.billboardMode = this.billboardMode;
  9119. this._currentRenderId = this.getScene().getRenderId();
  9120. this._isDirty = false;
  9121. // Scaling
  9122. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9123. // Rotation
  9124. //rotate, if quaternion is set and rotation was used
  9125. if (this.rotationQuaternion) {
  9126. var len = this.rotation.length();
  9127. if (len) {
  9128. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9129. this.rotation.copyFromFloats(0, 0, 0);
  9130. }
  9131. }
  9132. if (this.rotationQuaternion) {
  9133. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9134. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9135. }
  9136. else {
  9137. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9138. this._cache.rotation.copyFrom(this.rotation);
  9139. }
  9140. // Translation
  9141. if (this.infiniteDistance && !this.parent) {
  9142. var camera = this.getScene().activeCamera;
  9143. if (camera) {
  9144. var cameraWorldMatrix = camera.getWorldMatrix();
  9145. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9146. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9147. }
  9148. }
  9149. else {
  9150. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9151. }
  9152. // Composing transformations
  9153. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9154. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9155. // Billboarding
  9156. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9157. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9158. var localPosition = BABYLON.Tmp.Vector3[0];
  9159. if (this.parent && this.parent.getWorldMatrix) {
  9160. this._markSyncedWithParent();
  9161. var parentMatrix;
  9162. if (this._meshToBoneReferal) {
  9163. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9164. parentMatrix = BABYLON.Tmp.Matrix[6];
  9165. }
  9166. else {
  9167. parentMatrix = this.parent.getWorldMatrix();
  9168. }
  9169. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9170. localPosition = BABYLON.Tmp.Vector3[1];
  9171. }
  9172. var zero = this.getScene().activeCamera.globalPosition.clone();
  9173. if (this.parent && this.parent.position) {
  9174. localPosition.addInPlace(this.parent.position);
  9175. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9176. }
  9177. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9178. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9179. zero.x = localPosition.x + BABYLON.Epsilon;
  9180. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9181. zero.y = localPosition.y + BABYLON.Epsilon;
  9182. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9183. zero.z = localPosition.z + BABYLON.Epsilon;
  9184. }
  9185. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9186. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9187. BABYLON.Tmp.Matrix[3].invert();
  9188. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9189. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9190. }
  9191. // Local world
  9192. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9193. // Parent
  9194. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9195. this._markSyncedWithParent();
  9196. if (this._meshToBoneReferal) {
  9197. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9198. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9199. }
  9200. else {
  9201. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9202. }
  9203. }
  9204. else {
  9205. this._worldMatrix.copyFrom(this._localWorld);
  9206. }
  9207. // Bounding info
  9208. this._updateBoundingInfo();
  9209. // Absolute position
  9210. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9211. // Callbacks
  9212. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9213. if (!this._poseMatrix) {
  9214. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9215. }
  9216. return this._worldMatrix;
  9217. };
  9218. /**
  9219. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9220. * @param func: callback function to add
  9221. */
  9222. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9223. this.onAfterWorldMatrixUpdateObservable.add(func);
  9224. };
  9225. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9226. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9227. };
  9228. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9229. this.computeWorldMatrix();
  9230. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9231. };
  9232. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9233. this.computeWorldMatrix();
  9234. var invLocalWorldMatrix = this._localWorld.clone();
  9235. invLocalWorldMatrix.invert();
  9236. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9237. };
  9238. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9239. this.computeWorldMatrix(true);
  9240. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9241. };
  9242. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9243. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9244. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9245. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9246. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9247. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9248. /// <returns>Mesh oriented towards targetMesh</returns>
  9249. yawCor = yawCor || 0; // default to zero if undefined
  9250. pitchCor = pitchCor || 0;
  9251. rollCor = rollCor || 0;
  9252. var dv = targetPoint.subtract(this.position);
  9253. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9254. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9255. var pitch = Math.atan2(dv.y, len);
  9256. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9257. };
  9258. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9259. this._meshToBoneReferal = affectedMesh;
  9260. this.parent = bone;
  9261. if (bone.getWorldMatrix().determinant() < 0) {
  9262. this.scalingDeterminant *= -1;
  9263. }
  9264. };
  9265. AbstractMesh.prototype.detachFromBone = function () {
  9266. if (this.parent.getWorldMatrix().determinant() < 0) {
  9267. this.scalingDeterminant *= -1;
  9268. }
  9269. this._meshToBoneReferal = null;
  9270. this.parent = null;
  9271. };
  9272. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9273. return this._boundingInfo.isInFrustum(frustumPlanes);
  9274. };
  9275. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9276. if (!camera) {
  9277. camera = this.getScene().activeCamera;
  9278. }
  9279. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9280. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9281. return false;
  9282. }
  9283. return true;
  9284. };
  9285. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9286. if (!this._boundingInfo || !mesh._boundingInfo) {
  9287. return false;
  9288. }
  9289. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9290. };
  9291. AbstractMesh.prototype.intersectsPoint = function (point) {
  9292. if (!this._boundingInfo) {
  9293. return false;
  9294. }
  9295. return this._boundingInfo.intersectsPoint(point);
  9296. };
  9297. // Physics
  9298. /**
  9299. * @Deprecated. Use new PhysicsImpostor instead.
  9300. * */
  9301. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9302. //legacy support
  9303. if (impostor.impostor) {
  9304. options = impostor;
  9305. impostor = impostor.impostor;
  9306. }
  9307. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9308. return this.physicsImpostor.physicsBody;
  9309. };
  9310. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9311. return this.physicsImpostor;
  9312. };
  9313. /**
  9314. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9315. */
  9316. AbstractMesh.prototype.getPhysicsMass = function () {
  9317. return this.physicsImpostor.getParam("mass");
  9318. };
  9319. /**
  9320. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9321. */
  9322. AbstractMesh.prototype.getPhysicsFriction = function () {
  9323. return this.physicsImpostor.getParam("friction");
  9324. };
  9325. /**
  9326. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9327. */
  9328. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9329. return this.physicsImpostor.getParam("resitution");
  9330. };
  9331. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9332. if (!camera) {
  9333. camera = this.getScene().activeCamera;
  9334. }
  9335. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9336. };
  9337. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9338. if (!camera) {
  9339. camera = this.getScene().activeCamera;
  9340. }
  9341. return this.absolutePosition.subtract(camera.position).length();
  9342. };
  9343. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9344. if (!this.physicsImpostor) {
  9345. return;
  9346. }
  9347. this.physicsImpostor.applyImpulse(force, contactPoint);
  9348. };
  9349. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9350. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9351. return;
  9352. }
  9353. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9354. mainPivot: pivot1,
  9355. connectedPivot: pivot2,
  9356. nativeParams: options
  9357. });
  9358. };
  9359. /**
  9360. * @Deprecated
  9361. */
  9362. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9363. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9364. this.updatePhysicsBody();
  9365. };
  9366. /**
  9367. * @Deprecated
  9368. * Calling this function is not needed anymore.
  9369. * The physics engine takes care of transofmration automatically.
  9370. */
  9371. AbstractMesh.prototype.updatePhysicsBody = function () {
  9372. //Unneeded
  9373. };
  9374. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9375. // Collisions
  9376. get: function () {
  9377. return this._checkCollisions;
  9378. },
  9379. set: function (collisionEnabled) {
  9380. this._checkCollisions = collisionEnabled;
  9381. if (this.getScene().workerCollisions) {
  9382. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9383. }
  9384. },
  9385. enumerable: true,
  9386. configurable: true
  9387. });
  9388. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9389. var globalPosition = this.getAbsolutePosition();
  9390. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9391. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9392. this._collider.radius = this.ellipsoid;
  9393. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9394. };
  9395. // Submeshes octree
  9396. /**
  9397. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9398. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9399. */
  9400. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9401. if (maxCapacity === void 0) { maxCapacity = 64; }
  9402. if (maxDepth === void 0) { maxDepth = 2; }
  9403. if (!this._submeshesOctree) {
  9404. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9405. }
  9406. this.computeWorldMatrix(true);
  9407. // Update octree
  9408. var bbox = this.getBoundingInfo().boundingBox;
  9409. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9410. return this._submeshesOctree;
  9411. };
  9412. // Collisions
  9413. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9414. this._generatePointsArray();
  9415. // Transformation
  9416. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9417. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9418. subMesh._lastColliderWorldVertices = [];
  9419. subMesh._trianglePlanes = [];
  9420. var start = subMesh.verticesStart;
  9421. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9422. for (var i = start; i < end; i++) {
  9423. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9424. }
  9425. }
  9426. // Collide
  9427. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9428. if (collider.collisionFound) {
  9429. collider.collidedMesh = this;
  9430. }
  9431. };
  9432. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9433. var subMeshes;
  9434. var len;
  9435. // Octrees
  9436. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9437. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9438. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9439. len = intersections.length;
  9440. subMeshes = intersections.data;
  9441. }
  9442. else {
  9443. subMeshes = this.subMeshes;
  9444. len = subMeshes.length;
  9445. }
  9446. for (var index = 0; index < len; index++) {
  9447. var subMesh = subMeshes[index];
  9448. // Bounding test
  9449. if (len > 1 && !subMesh._checkCollision(collider))
  9450. continue;
  9451. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9452. }
  9453. };
  9454. AbstractMesh.prototype._checkCollision = function (collider) {
  9455. // Bounding box test
  9456. if (!this._boundingInfo._checkCollision(collider))
  9457. return;
  9458. // Transformation matrix
  9459. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9460. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9461. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9462. };
  9463. // Picking
  9464. AbstractMesh.prototype._generatePointsArray = function () {
  9465. return false;
  9466. };
  9467. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9468. var pickingInfo = new BABYLON.PickingInfo();
  9469. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9470. return pickingInfo;
  9471. }
  9472. if (!this._generatePointsArray()) {
  9473. return pickingInfo;
  9474. }
  9475. var intersectInfo = null;
  9476. // Octrees
  9477. var subMeshes;
  9478. var len;
  9479. if (this._submeshesOctree && this.useOctreeForPicking) {
  9480. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9481. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9482. len = intersections.length;
  9483. subMeshes = intersections.data;
  9484. }
  9485. else {
  9486. subMeshes = this.subMeshes;
  9487. len = subMeshes.length;
  9488. }
  9489. for (var index = 0; index < len; index++) {
  9490. var subMesh = subMeshes[index];
  9491. // Bounding test
  9492. if (len > 1 && !subMesh.canIntersects(ray))
  9493. continue;
  9494. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9495. if (currentIntersectInfo) {
  9496. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9497. intersectInfo = currentIntersectInfo;
  9498. intersectInfo.subMeshId = index;
  9499. if (fastCheck) {
  9500. break;
  9501. }
  9502. }
  9503. }
  9504. }
  9505. if (intersectInfo) {
  9506. // Get picked point
  9507. var world = this.getWorldMatrix();
  9508. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9509. var direction = ray.direction.clone();
  9510. direction = direction.scale(intersectInfo.distance);
  9511. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9512. var pickedPoint = worldOrigin.add(worldDirection);
  9513. // Return result
  9514. pickingInfo.hit = true;
  9515. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9516. pickingInfo.pickedPoint = pickedPoint;
  9517. pickingInfo.pickedMesh = this;
  9518. pickingInfo.bu = intersectInfo.bu;
  9519. pickingInfo.bv = intersectInfo.bv;
  9520. pickingInfo.faceId = intersectInfo.faceId;
  9521. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9522. return pickingInfo;
  9523. }
  9524. return pickingInfo;
  9525. };
  9526. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9527. return null;
  9528. };
  9529. AbstractMesh.prototype.releaseSubMeshes = function () {
  9530. if (this.subMeshes) {
  9531. while (this.subMeshes.length) {
  9532. this.subMeshes[0].dispose();
  9533. }
  9534. }
  9535. else {
  9536. this.subMeshes = new Array();
  9537. }
  9538. };
  9539. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9540. var _this = this;
  9541. var index;
  9542. // Action manager
  9543. if (this.actionManager) {
  9544. this.actionManager.dispose();
  9545. this.actionManager = null;
  9546. }
  9547. // Skeleton
  9548. this.skeleton = null;
  9549. // Animations
  9550. this.getScene().stopAnimation(this);
  9551. // Physics
  9552. if (this.physicsImpostor) {
  9553. this.physicsImpostor.dispose();
  9554. }
  9555. // Intersections in progress
  9556. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9557. var other = this._intersectionsInProgress[index];
  9558. var pos = other._intersectionsInProgress.indexOf(this);
  9559. other._intersectionsInProgress.splice(pos, 1);
  9560. }
  9561. this._intersectionsInProgress = [];
  9562. // Lights
  9563. var lights = this.getScene().lights;
  9564. lights.forEach(function (light) {
  9565. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9566. if (meshIndex !== -1) {
  9567. light.includedOnlyMeshes.splice(meshIndex, 1);
  9568. }
  9569. meshIndex = light.excludedMeshes.indexOf(_this);
  9570. if (meshIndex !== -1) {
  9571. light.excludedMeshes.splice(meshIndex, 1);
  9572. }
  9573. });
  9574. // Edges
  9575. if (this._edgesRenderer) {
  9576. this._edgesRenderer.dispose();
  9577. this._edgesRenderer = null;
  9578. }
  9579. // SubMeshes
  9580. this.releaseSubMeshes();
  9581. // Remove from scene
  9582. this.getScene().removeMesh(this);
  9583. if (!doNotRecurse) {
  9584. // Particles
  9585. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9586. if (this.getScene().particleSystems[index].emitter === this) {
  9587. this.getScene().particleSystems[index].dispose();
  9588. index--;
  9589. }
  9590. }
  9591. // Children
  9592. var objects = this.getDescendants(true);
  9593. for (index = 0; index < objects.length; index++) {
  9594. objects[index].dispose();
  9595. }
  9596. }
  9597. else {
  9598. var childMeshes = this.getChildMeshes(true);
  9599. for (index = 0; index < childMeshes.length; index++) {
  9600. var child = childMeshes[index];
  9601. child.parent = null;
  9602. child.computeWorldMatrix(true);
  9603. }
  9604. }
  9605. _super.prototype.dispose.call(this);
  9606. this.onAfterWorldMatrixUpdateObservable.clear();
  9607. this.onCollideObservable.clear();
  9608. this.onCollisionPositionChangeObservable.clear();
  9609. this._isDisposed = true;
  9610. // Callback
  9611. this.onDisposeObservable.notifyObservers(this);
  9612. this.onDisposeObservable.clear();
  9613. };
  9614. // Statics
  9615. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9616. AbstractMesh._BILLBOARDMODE_X = 1;
  9617. AbstractMesh._BILLBOARDMODE_Y = 2;
  9618. AbstractMesh._BILLBOARDMODE_Z = 4;
  9619. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9620. return AbstractMesh;
  9621. })(BABYLON.Node);
  9622. BABYLON.AbstractMesh = AbstractMesh;
  9623. })(BABYLON || (BABYLON = {}));
  9624. var BABYLON;
  9625. (function (BABYLON) {
  9626. var Light = (function (_super) {
  9627. __extends(Light, _super);
  9628. function Light(name, scene) {
  9629. _super.call(this, name, scene);
  9630. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9631. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9632. this.intensity = 1.0;
  9633. this.range = Number.MAX_VALUE;
  9634. this.includeOnlyWithLayerMask = 0;
  9635. this.includedOnlyMeshes = new Array();
  9636. this.excludedMeshes = new Array();
  9637. this.excludeWithLayerMask = 0;
  9638. // PBR Properties.
  9639. this.radius = 0.00001;
  9640. this._excludedMeshesIds = new Array();
  9641. this._includedOnlyMeshesIds = new Array();
  9642. scene.addLight(this);
  9643. }
  9644. /**
  9645. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9646. */
  9647. Light.prototype.toString = function (fullDetails) {
  9648. var ret = "Name: " + this.name;
  9649. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9650. if (this.animations) {
  9651. for (var i = 0; i < this.animations.length; i++) {
  9652. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9653. }
  9654. }
  9655. if (fullDetails) {
  9656. }
  9657. return ret;
  9658. };
  9659. Light.prototype.getShadowGenerator = function () {
  9660. return this._shadowGenerator;
  9661. };
  9662. Light.prototype.getAbsolutePosition = function () {
  9663. return BABYLON.Vector3.Zero();
  9664. };
  9665. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9666. };
  9667. Light.prototype._getWorldMatrix = function () {
  9668. return BABYLON.Matrix.Identity();
  9669. };
  9670. Light.prototype.canAffectMesh = function (mesh) {
  9671. if (!mesh) {
  9672. return true;
  9673. }
  9674. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9675. return false;
  9676. }
  9677. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9678. return false;
  9679. }
  9680. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9681. return false;
  9682. }
  9683. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9684. return false;
  9685. }
  9686. return true;
  9687. };
  9688. Light.prototype.getWorldMatrix = function () {
  9689. this._currentRenderId = this.getScene().getRenderId();
  9690. var worldMatrix = this._getWorldMatrix();
  9691. if (this.parent && this.parent.getWorldMatrix) {
  9692. if (!this._parentedWorldMatrix) {
  9693. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9694. }
  9695. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9696. this._markSyncedWithParent();
  9697. return this._parentedWorldMatrix;
  9698. }
  9699. return worldMatrix;
  9700. };
  9701. Light.prototype.dispose = function () {
  9702. if (this._shadowGenerator) {
  9703. this._shadowGenerator.dispose();
  9704. this._shadowGenerator = null;
  9705. }
  9706. // Animations
  9707. this.getScene().stopAnimation(this);
  9708. // Remove from scene
  9709. this.getScene().removeLight(this);
  9710. _super.prototype.dispose.call(this);
  9711. };
  9712. Light.prototype.getTypeID = function () {
  9713. return 0;
  9714. };
  9715. Light.prototype.clone = function (name) {
  9716. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9717. };
  9718. Light.prototype.serialize = function () {
  9719. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9720. // Type
  9721. serializationObject.type = this.getTypeID();
  9722. // Parent
  9723. if (this.parent) {
  9724. serializationObject.parentId = this.parent.id;
  9725. }
  9726. // Inclusion / exclusions
  9727. if (this.excludedMeshes.length > 0) {
  9728. serializationObject.excludedMeshesIds = [];
  9729. this.excludedMeshes.forEach(function (mesh) {
  9730. serializationObject.excludedMeshesIds.push(mesh.id);
  9731. });
  9732. }
  9733. if (this.includedOnlyMeshes.length > 0) {
  9734. serializationObject.includedOnlyMeshesIds = [];
  9735. this.includedOnlyMeshes.forEach(function (mesh) {
  9736. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9737. });
  9738. }
  9739. // Animations
  9740. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9741. serializationObject.ranges = this.serializeAnimationRanges();
  9742. return serializationObject;
  9743. };
  9744. Light.GetConstructorFromName = function (type, name, scene) {
  9745. switch (type) {
  9746. case 0:
  9747. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9748. case 1:
  9749. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9750. case 2:
  9751. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9752. case 3:
  9753. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9754. }
  9755. };
  9756. Light.Parse = function (parsedLight, scene) {
  9757. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9758. // Inclusion / exclusions
  9759. if (parsedLight.excludedMeshesIds) {
  9760. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9761. }
  9762. if (parsedLight.includedOnlyMeshesIds) {
  9763. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9764. }
  9765. // Parent
  9766. if (parsedLight.parentId) {
  9767. light._waitingParentId = parsedLight.parentId;
  9768. }
  9769. // Animations
  9770. if (parsedLight.animations) {
  9771. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9772. var parsedAnimation = parsedLight.animations[animationIndex];
  9773. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9774. }
  9775. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9776. }
  9777. if (parsedLight.autoAnimate) {
  9778. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9779. }
  9780. return light;
  9781. };
  9782. __decorate([
  9783. BABYLON.serializeAsColor3()
  9784. ], Light.prototype, "diffuse", void 0);
  9785. __decorate([
  9786. BABYLON.serializeAsColor3()
  9787. ], Light.prototype, "specular", void 0);
  9788. __decorate([
  9789. BABYLON.serialize()
  9790. ], Light.prototype, "intensity", void 0);
  9791. __decorate([
  9792. BABYLON.serialize()
  9793. ], Light.prototype, "range", void 0);
  9794. __decorate([
  9795. BABYLON.serialize()
  9796. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9797. __decorate([
  9798. BABYLON.serialize()
  9799. ], Light.prototype, "excludeWithLayerMask", void 0);
  9800. __decorate([
  9801. BABYLON.serialize()
  9802. ], Light.prototype, "radius", void 0);
  9803. return Light;
  9804. })(BABYLON.Node);
  9805. BABYLON.Light = Light;
  9806. })(BABYLON || (BABYLON = {}));
  9807. var BABYLON;
  9808. (function (BABYLON) {
  9809. var PointLight = (function (_super) {
  9810. __extends(PointLight, _super);
  9811. function PointLight(name, position, scene) {
  9812. _super.call(this, name, scene);
  9813. this.position = position;
  9814. }
  9815. PointLight.prototype.getAbsolutePosition = function () {
  9816. return this.transformedPosition ? this.transformedPosition : this.position;
  9817. };
  9818. PointLight.prototype.computeTransformedPosition = function () {
  9819. if (this.parent && this.parent.getWorldMatrix) {
  9820. if (!this.transformedPosition) {
  9821. this.transformedPosition = BABYLON.Vector3.Zero();
  9822. }
  9823. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9824. return true;
  9825. }
  9826. return false;
  9827. };
  9828. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9829. if (this.parent && this.parent.getWorldMatrix) {
  9830. this.computeTransformedPosition();
  9831. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9832. return;
  9833. }
  9834. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9835. };
  9836. PointLight.prototype.needCube = function () {
  9837. return true;
  9838. };
  9839. PointLight.prototype.supportsVSM = function () {
  9840. return false;
  9841. };
  9842. PointLight.prototype.needRefreshPerFrame = function () {
  9843. return false;
  9844. };
  9845. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9846. switch (faceIndex) {
  9847. case 0:
  9848. return new BABYLON.Vector3(1, 0, 0);
  9849. case 1:
  9850. return new BABYLON.Vector3(-1, 0, 0);
  9851. case 2:
  9852. return new BABYLON.Vector3(0, -1, 0);
  9853. case 3:
  9854. return new BABYLON.Vector3(0, 1, 0);
  9855. case 4:
  9856. return new BABYLON.Vector3(0, 0, 1);
  9857. case 5:
  9858. return new BABYLON.Vector3(0, 0, -1);
  9859. }
  9860. return BABYLON.Vector3.Zero();
  9861. };
  9862. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9863. var activeCamera = this.getScene().activeCamera;
  9864. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9865. };
  9866. PointLight.prototype._getWorldMatrix = function () {
  9867. if (!this._worldMatrix) {
  9868. this._worldMatrix = BABYLON.Matrix.Identity();
  9869. }
  9870. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9871. return this._worldMatrix;
  9872. };
  9873. PointLight.prototype.getTypeID = function () {
  9874. return 0;
  9875. };
  9876. __decorate([
  9877. BABYLON.serializeAsVector3()
  9878. ], PointLight.prototype, "position", void 0);
  9879. return PointLight;
  9880. })(BABYLON.Light);
  9881. BABYLON.PointLight = PointLight;
  9882. })(BABYLON || (BABYLON = {}));
  9883. var BABYLON;
  9884. (function (BABYLON) {
  9885. var SpotLight = (function (_super) {
  9886. __extends(SpotLight, _super);
  9887. function SpotLight(name, position, direction, angle, exponent, scene) {
  9888. _super.call(this, name, scene);
  9889. this.position = position;
  9890. this.direction = direction;
  9891. this.angle = angle;
  9892. this.exponent = exponent;
  9893. }
  9894. SpotLight.prototype.getAbsolutePosition = function () {
  9895. return this.transformedPosition ? this.transformedPosition : this.position;
  9896. };
  9897. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9898. var activeCamera = this.getScene().activeCamera;
  9899. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9900. };
  9901. SpotLight.prototype.needCube = function () {
  9902. return false;
  9903. };
  9904. SpotLight.prototype.supportsVSM = function () {
  9905. return true;
  9906. };
  9907. SpotLight.prototype.needRefreshPerFrame = function () {
  9908. return false;
  9909. };
  9910. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9911. return this.direction;
  9912. };
  9913. SpotLight.prototype.setDirectionToTarget = function (target) {
  9914. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9915. return this.direction;
  9916. };
  9917. SpotLight.prototype.computeTransformedPosition = function () {
  9918. if (this.parent && this.parent.getWorldMatrix) {
  9919. if (!this.transformedPosition) {
  9920. this.transformedPosition = BABYLON.Vector3.Zero();
  9921. }
  9922. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9923. return true;
  9924. }
  9925. return false;
  9926. };
  9927. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9928. var normalizeDirection;
  9929. if (this.parent && this.parent.getWorldMatrix) {
  9930. if (!this._transformedDirection) {
  9931. this._transformedDirection = BABYLON.Vector3.Zero();
  9932. }
  9933. this.computeTransformedPosition();
  9934. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9935. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9936. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9937. }
  9938. else {
  9939. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9940. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9941. }
  9942. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9943. };
  9944. SpotLight.prototype._getWorldMatrix = function () {
  9945. if (!this._worldMatrix) {
  9946. this._worldMatrix = BABYLON.Matrix.Identity();
  9947. }
  9948. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9949. return this._worldMatrix;
  9950. };
  9951. SpotLight.prototype.getTypeID = function () {
  9952. return 2;
  9953. };
  9954. __decorate([
  9955. BABYLON.serializeAsVector3()
  9956. ], SpotLight.prototype, "position", void 0);
  9957. __decorate([
  9958. BABYLON.serializeAsVector3()
  9959. ], SpotLight.prototype, "direction", void 0);
  9960. __decorate([
  9961. BABYLON.serialize()
  9962. ], SpotLight.prototype, "angle", void 0);
  9963. __decorate([
  9964. BABYLON.serialize()
  9965. ], SpotLight.prototype, "exponent", void 0);
  9966. return SpotLight;
  9967. })(BABYLON.Light);
  9968. BABYLON.SpotLight = SpotLight;
  9969. })(BABYLON || (BABYLON = {}));
  9970. var BABYLON;
  9971. (function (BABYLON) {
  9972. var HemisphericLight = (function (_super) {
  9973. __extends(HemisphericLight, _super);
  9974. function HemisphericLight(name, direction, scene) {
  9975. _super.call(this, name, scene);
  9976. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9977. this.direction = direction;
  9978. }
  9979. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9980. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9981. return this.direction;
  9982. };
  9983. HemisphericLight.prototype.getShadowGenerator = function () {
  9984. return null;
  9985. };
  9986. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9987. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9988. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9989. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9990. };
  9991. HemisphericLight.prototype._getWorldMatrix = function () {
  9992. if (!this._worldMatrix) {
  9993. this._worldMatrix = BABYLON.Matrix.Identity();
  9994. }
  9995. return this._worldMatrix;
  9996. };
  9997. HemisphericLight.prototype.getTypeID = function () {
  9998. return 3;
  9999. };
  10000. __decorate([
  10001. BABYLON.serializeAsColor3()
  10002. ], HemisphericLight.prototype, "groundColor", void 0);
  10003. __decorate([
  10004. BABYLON.serializeAsVector3()
  10005. ], HemisphericLight.prototype, "direction", void 0);
  10006. return HemisphericLight;
  10007. })(BABYLON.Light);
  10008. BABYLON.HemisphericLight = HemisphericLight;
  10009. })(BABYLON || (BABYLON = {}));
  10010. var BABYLON;
  10011. (function (BABYLON) {
  10012. var DirectionalLight = (function (_super) {
  10013. __extends(DirectionalLight, _super);
  10014. function DirectionalLight(name, direction, scene) {
  10015. _super.call(this, name, scene);
  10016. this.shadowOrthoScale = 0.5;
  10017. this.autoUpdateExtends = true;
  10018. // Cache
  10019. this._orthoLeft = Number.MAX_VALUE;
  10020. this._orthoRight = Number.MIN_VALUE;
  10021. this._orthoTop = Number.MIN_VALUE;
  10022. this._orthoBottom = Number.MAX_VALUE;
  10023. this.position = direction.scale(-1);
  10024. this.direction = direction;
  10025. }
  10026. DirectionalLight.prototype.getAbsolutePosition = function () {
  10027. return this.transformedPosition ? this.transformedPosition : this.position;
  10028. };
  10029. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10030. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10031. return this.direction;
  10032. };
  10033. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10034. var activeCamera = this.getScene().activeCamera;
  10035. // Check extends
  10036. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10037. var tempVector3 = BABYLON.Vector3.Zero();
  10038. this._orthoLeft = Number.MAX_VALUE;
  10039. this._orthoRight = Number.MIN_VALUE;
  10040. this._orthoTop = Number.MIN_VALUE;
  10041. this._orthoBottom = Number.MAX_VALUE;
  10042. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10043. var mesh = renderList[meshIndex];
  10044. if (!mesh) {
  10045. continue;
  10046. }
  10047. var boundingInfo = mesh.getBoundingInfo();
  10048. if (!boundingInfo) {
  10049. continue;
  10050. }
  10051. var boundingBox = boundingInfo.boundingBox;
  10052. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10053. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10054. if (tempVector3.x < this._orthoLeft)
  10055. this._orthoLeft = tempVector3.x;
  10056. if (tempVector3.y < this._orthoBottom)
  10057. this._orthoBottom = tempVector3.y;
  10058. if (tempVector3.x > this._orthoRight)
  10059. this._orthoRight = tempVector3.x;
  10060. if (tempVector3.y > this._orthoTop)
  10061. this._orthoTop = tempVector3.y;
  10062. }
  10063. }
  10064. }
  10065. var xOffset = this._orthoRight - this._orthoLeft;
  10066. var yOffset = this._orthoTop - this._orthoBottom;
  10067. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  10068. };
  10069. DirectionalLight.prototype.supportsVSM = function () {
  10070. return true;
  10071. };
  10072. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10073. return true;
  10074. };
  10075. DirectionalLight.prototype.needCube = function () {
  10076. return false;
  10077. };
  10078. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10079. return this.direction;
  10080. };
  10081. DirectionalLight.prototype.computeTransformedPosition = function () {
  10082. if (this.parent && this.parent.getWorldMatrix) {
  10083. if (!this.transformedPosition) {
  10084. this.transformedPosition = BABYLON.Vector3.Zero();
  10085. }
  10086. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10087. return true;
  10088. }
  10089. return false;
  10090. };
  10091. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10092. if (this.parent && this.parent.getWorldMatrix) {
  10093. if (!this._transformedDirection) {
  10094. this._transformedDirection = BABYLON.Vector3.Zero();
  10095. }
  10096. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10097. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10098. return;
  10099. }
  10100. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10101. };
  10102. DirectionalLight.prototype._getWorldMatrix = function () {
  10103. if (!this._worldMatrix) {
  10104. this._worldMatrix = BABYLON.Matrix.Identity();
  10105. }
  10106. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10107. return this._worldMatrix;
  10108. };
  10109. DirectionalLight.prototype.getTypeID = function () {
  10110. return 1;
  10111. };
  10112. __decorate([
  10113. BABYLON.serializeAsVector3()
  10114. ], DirectionalLight.prototype, "position", void 0);
  10115. __decorate([
  10116. BABYLON.serializeAsVector3()
  10117. ], DirectionalLight.prototype, "direction", void 0);
  10118. __decorate([
  10119. BABYLON.serialize()
  10120. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10121. __decorate([
  10122. BABYLON.serialize()
  10123. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10124. return DirectionalLight;
  10125. })(BABYLON.Light);
  10126. BABYLON.DirectionalLight = DirectionalLight;
  10127. })(BABYLON || (BABYLON = {}));
  10128. var BABYLON;
  10129. (function (BABYLON) {
  10130. var ShadowGenerator = (function () {
  10131. function ShadowGenerator(mapSize, light) {
  10132. var _this = this;
  10133. // Members
  10134. this._filter = ShadowGenerator.FILTER_NONE;
  10135. this.blurScale = 2;
  10136. this._blurBoxOffset = 0;
  10137. this._bias = 0.00005;
  10138. this._lightDirection = BABYLON.Vector3.Zero();
  10139. this.forceBackFacesOnly = false;
  10140. this._darkness = 0;
  10141. this._transparencyShadow = false;
  10142. this._viewMatrix = BABYLON.Matrix.Zero();
  10143. this._projectionMatrix = BABYLON.Matrix.Zero();
  10144. this._transformMatrix = BABYLON.Matrix.Zero();
  10145. this._worldViewProjection = BABYLON.Matrix.Zero();
  10146. this._currentFaceIndex = 0;
  10147. this._currentFaceIndexCache = 0;
  10148. this._light = light;
  10149. this._scene = light.getScene();
  10150. this._mapSize = mapSize;
  10151. light._shadowGenerator = this;
  10152. // Render target
  10153. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  10154. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10155. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10156. this._shadowMap.anisotropicFilteringLevel = 1;
  10157. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10158. this._shadowMap.renderParticles = false;
  10159. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10160. _this._currentFaceIndex = faceIndex;
  10161. });
  10162. this._shadowMap.onAfterUnbindObservable.add(function () {
  10163. if (!_this.useBlurVarianceShadowMap) {
  10164. return;
  10165. }
  10166. if (!_this._shadowMap2) {
  10167. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  10168. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10169. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10170. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10171. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10172. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10173. effect.setTexture("textureSampler", _this._shadowMap);
  10174. });
  10175. _this.blurBoxOffset = 1;
  10176. }
  10177. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10178. });
  10179. // Custom render function
  10180. var renderSubMesh = function (subMesh) {
  10181. var mesh = subMesh.getRenderingMesh();
  10182. var scene = _this._scene;
  10183. var engine = scene.getEngine();
  10184. // Culling
  10185. engine.setState(subMesh.getMaterial().backFaceCulling);
  10186. // Managing instances
  10187. var batch = mesh._getInstancesRenderList(subMesh._id);
  10188. if (batch.mustReturn) {
  10189. return;
  10190. }
  10191. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10192. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10193. engine.enableEffect(_this._effect);
  10194. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10195. var material = subMesh.getMaterial();
  10196. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10197. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10198. if (_this.getLight().needCube()) {
  10199. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10200. }
  10201. // Alpha test
  10202. if (material && material.needAlphaTesting()) {
  10203. var alphaTexture = material.getAlphaTestTexture();
  10204. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10205. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10206. }
  10207. // Bones
  10208. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10209. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10210. }
  10211. if (_this.forceBackFacesOnly) {
  10212. engine.setState(true, 0, false, true);
  10213. }
  10214. // Draw
  10215. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10216. if (_this.forceBackFacesOnly) {
  10217. engine.setState(true, 0, false, false);
  10218. }
  10219. }
  10220. else {
  10221. // Need to reset refresh rate of the shadowMap
  10222. _this._shadowMap.resetRefreshCounter();
  10223. }
  10224. };
  10225. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10226. var index;
  10227. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10228. renderSubMesh(opaqueSubMeshes.data[index]);
  10229. }
  10230. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10231. renderSubMesh(alphaTestSubMeshes.data[index]);
  10232. }
  10233. if (_this._transparencyShadow) {
  10234. for (index = 0; index < transparentSubMeshes.length; index++) {
  10235. renderSubMesh(transparentSubMeshes.data[index]);
  10236. }
  10237. }
  10238. };
  10239. this._shadowMap.onClearObservable.add(function (engine) {
  10240. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10241. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10242. }
  10243. else {
  10244. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10245. }
  10246. });
  10247. }
  10248. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10249. // Static
  10250. get: function () {
  10251. return ShadowGenerator._FILTER_NONE;
  10252. },
  10253. enumerable: true,
  10254. configurable: true
  10255. });
  10256. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10257. get: function () {
  10258. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10259. },
  10260. enumerable: true,
  10261. configurable: true
  10262. });
  10263. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10264. get: function () {
  10265. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10266. },
  10267. enumerable: true,
  10268. configurable: true
  10269. });
  10270. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10271. get: function () {
  10272. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10273. },
  10274. enumerable: true,
  10275. configurable: true
  10276. });
  10277. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10278. get: function () {
  10279. return this._bias;
  10280. },
  10281. set: function (bias) {
  10282. this._bias = bias;
  10283. },
  10284. enumerable: true,
  10285. configurable: true
  10286. });
  10287. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10288. get: function () {
  10289. return this._blurBoxOffset;
  10290. },
  10291. set: function (value) {
  10292. var _this = this;
  10293. if (this._blurBoxOffset === value) {
  10294. return;
  10295. }
  10296. this._blurBoxOffset = value;
  10297. if (this._boxBlurPostprocess) {
  10298. this._boxBlurPostprocess.dispose();
  10299. }
  10300. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  10301. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  10302. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10303. });
  10304. },
  10305. enumerable: true,
  10306. configurable: true
  10307. });
  10308. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10309. get: function () {
  10310. return this._filter;
  10311. },
  10312. set: function (value) {
  10313. if (this._filter === value) {
  10314. return;
  10315. }
  10316. this._filter = value;
  10317. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10318. this._shadowMap.anisotropicFilteringLevel = 16;
  10319. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10320. }
  10321. else {
  10322. this._shadowMap.anisotropicFilteringLevel = 1;
  10323. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10324. }
  10325. },
  10326. enumerable: true,
  10327. configurable: true
  10328. });
  10329. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10330. get: function () {
  10331. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10332. },
  10333. set: function (value) {
  10334. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10335. },
  10336. enumerable: true,
  10337. configurable: true
  10338. });
  10339. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10340. get: function () {
  10341. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10342. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10343. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10344. },
  10345. set: function (value) {
  10346. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10347. },
  10348. enumerable: true,
  10349. configurable: true
  10350. });
  10351. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10352. get: function () {
  10353. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10354. },
  10355. set: function (value) {
  10356. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10357. },
  10358. enumerable: true,
  10359. configurable: true
  10360. });
  10361. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10362. var defines = [];
  10363. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10364. defines.push("#define VSM");
  10365. }
  10366. if (this.getLight().needCube()) {
  10367. defines.push("#define CUBEMAP");
  10368. }
  10369. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10370. var mesh = subMesh.getMesh();
  10371. var material = subMesh.getMaterial();
  10372. // Alpha test
  10373. if (material && material.needAlphaTesting()) {
  10374. defines.push("#define ALPHATEST");
  10375. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10376. attribs.push(BABYLON.VertexBuffer.UVKind);
  10377. defines.push("#define UV1");
  10378. }
  10379. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10380. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10381. defines.push("#define UV2");
  10382. }
  10383. }
  10384. // Bones
  10385. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10386. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10387. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10388. if (mesh.numBoneInfluencers > 4) {
  10389. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10390. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10391. }
  10392. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10393. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10394. }
  10395. else {
  10396. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10397. }
  10398. // Instances
  10399. if (useInstances) {
  10400. defines.push("#define INSTANCES");
  10401. attribs.push("world0");
  10402. attribs.push("world1");
  10403. attribs.push("world2");
  10404. attribs.push("world3");
  10405. }
  10406. // Get correct effect
  10407. var join = defines.join("\n");
  10408. if (this._cachedDefines !== join) {
  10409. this._cachedDefines = join;
  10410. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10411. }
  10412. return this._effect.isReady();
  10413. };
  10414. ShadowGenerator.prototype.getShadowMap = function () {
  10415. return this._shadowMap;
  10416. };
  10417. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10418. if (this._shadowMap2) {
  10419. return this._shadowMap2;
  10420. }
  10421. return this._shadowMap;
  10422. };
  10423. ShadowGenerator.prototype.getLight = function () {
  10424. return this._light;
  10425. };
  10426. // Methods
  10427. ShadowGenerator.prototype.getTransformMatrix = function () {
  10428. var scene = this._scene;
  10429. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10430. return this._transformMatrix;
  10431. }
  10432. this._currentRenderID = scene.getRenderId();
  10433. this._currentFaceIndexCache = this._currentFaceIndex;
  10434. var lightPosition = this._light.position;
  10435. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10436. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10437. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10438. }
  10439. if (this._light.computeTransformedPosition()) {
  10440. lightPosition = this._light.transformedPosition;
  10441. }
  10442. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10443. this._cachedPosition = lightPosition.clone();
  10444. this._cachedDirection = this._lightDirection.clone();
  10445. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10446. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10447. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10448. }
  10449. return this._transformMatrix;
  10450. };
  10451. ShadowGenerator.prototype.getDarkness = function () {
  10452. return this._darkness;
  10453. };
  10454. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10455. if (darkness >= 1.0)
  10456. this._darkness = 1.0;
  10457. else if (darkness <= 0.0)
  10458. this._darkness = 0.0;
  10459. else
  10460. this._darkness = darkness;
  10461. };
  10462. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10463. this._transparencyShadow = hasShadow;
  10464. };
  10465. ShadowGenerator.prototype._packHalf = function (depth) {
  10466. var scale = depth * 255.0;
  10467. var fract = scale - Math.floor(scale);
  10468. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10469. };
  10470. ShadowGenerator.prototype.dispose = function () {
  10471. this._shadowMap.dispose();
  10472. if (this._shadowMap2) {
  10473. this._shadowMap2.dispose();
  10474. }
  10475. if (this._downSamplePostprocess) {
  10476. this._downSamplePostprocess.dispose();
  10477. }
  10478. if (this._boxBlurPostprocess) {
  10479. this._boxBlurPostprocess.dispose();
  10480. }
  10481. };
  10482. ShadowGenerator.prototype.serialize = function () {
  10483. var serializationObject = {};
  10484. serializationObject.lightId = this._light.id;
  10485. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10486. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10487. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10488. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10489. serializationObject.renderList = [];
  10490. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10491. var mesh = this.getShadowMap().renderList[meshIndex];
  10492. serializationObject.renderList.push(mesh.id);
  10493. }
  10494. return serializationObject;
  10495. };
  10496. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10497. //casting to point light, as light is missing the position attr and typescript complains.
  10498. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10499. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10500. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10501. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  10502. meshes.forEach(function (mesh) {
  10503. shadowGenerator.getShadowMap().renderList.push(mesh);
  10504. });
  10505. }
  10506. if (parsedShadowGenerator.usePoissonSampling) {
  10507. shadowGenerator.usePoissonSampling = true;
  10508. }
  10509. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10510. shadowGenerator.useVarianceShadowMap = true;
  10511. }
  10512. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10513. shadowGenerator.useBlurVarianceShadowMap = true;
  10514. if (parsedShadowGenerator.blurScale) {
  10515. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10516. }
  10517. if (parsedShadowGenerator.blurBoxOffset) {
  10518. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10519. }
  10520. }
  10521. if (parsedShadowGenerator.bias !== undefined) {
  10522. shadowGenerator.bias = parsedShadowGenerator.bias;
  10523. }
  10524. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10525. return shadowGenerator;
  10526. };
  10527. ShadowGenerator._FILTER_NONE = 0;
  10528. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10529. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10530. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10531. return ShadowGenerator;
  10532. })();
  10533. BABYLON.ShadowGenerator = ShadowGenerator;
  10534. })(BABYLON || (BABYLON = {}));
  10535. var BABYLON;
  10536. (function (BABYLON) {
  10537. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10538. if (boxMin.x > sphereCenter.x + sphereRadius)
  10539. return false;
  10540. if (sphereCenter.x - sphereRadius > boxMax.x)
  10541. return false;
  10542. if (boxMin.y > sphereCenter.y + sphereRadius)
  10543. return false;
  10544. if (sphereCenter.y - sphereRadius > boxMax.y)
  10545. return false;
  10546. if (boxMin.z > sphereCenter.z + sphereRadius)
  10547. return false;
  10548. if (sphereCenter.z - sphereRadius > boxMax.z)
  10549. return false;
  10550. return true;
  10551. };
  10552. var getLowestRoot = function (a, b, c, maxR) {
  10553. var determinant = b * b - 4.0 * a * c;
  10554. var result = { root: 0, found: false };
  10555. if (determinant < 0)
  10556. return result;
  10557. var sqrtD = Math.sqrt(determinant);
  10558. var r1 = (-b - sqrtD) / (2.0 * a);
  10559. var r2 = (-b + sqrtD) / (2.0 * a);
  10560. if (r1 > r2) {
  10561. var temp = r2;
  10562. r2 = r1;
  10563. r1 = temp;
  10564. }
  10565. if (r1 > 0 && r1 < maxR) {
  10566. result.root = r1;
  10567. result.found = true;
  10568. return result;
  10569. }
  10570. if (r2 > 0 && r2 < maxR) {
  10571. result.root = r2;
  10572. result.found = true;
  10573. return result;
  10574. }
  10575. return result;
  10576. };
  10577. var Collider = (function () {
  10578. function Collider() {
  10579. this.radius = new BABYLON.Vector3(1, 1, 1);
  10580. this.retry = 0;
  10581. this.basePointWorld = BABYLON.Vector3.Zero();
  10582. this.velocityWorld = BABYLON.Vector3.Zero();
  10583. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10584. this._collisionPoint = BABYLON.Vector3.Zero();
  10585. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10586. this._tempVector = BABYLON.Vector3.Zero();
  10587. this._tempVector2 = BABYLON.Vector3.Zero();
  10588. this._tempVector3 = BABYLON.Vector3.Zero();
  10589. this._tempVector4 = BABYLON.Vector3.Zero();
  10590. this._edge = BABYLON.Vector3.Zero();
  10591. this._baseToVertex = BABYLON.Vector3.Zero();
  10592. this._destinationPoint = BABYLON.Vector3.Zero();
  10593. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10594. this._displacementVector = BABYLON.Vector3.Zero();
  10595. }
  10596. // Methods
  10597. Collider.prototype._initialize = function (source, dir, e) {
  10598. this.velocity = dir;
  10599. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10600. this.basePoint = source;
  10601. source.multiplyToRef(this.radius, this.basePointWorld);
  10602. dir.multiplyToRef(this.radius, this.velocityWorld);
  10603. this.velocityWorldLength = this.velocityWorld.length();
  10604. this.epsilon = e;
  10605. this.collisionFound = false;
  10606. };
  10607. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10608. pa.subtractToRef(point, this._tempVector);
  10609. pb.subtractToRef(point, this._tempVector2);
  10610. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10611. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10612. if (d < 0)
  10613. return false;
  10614. pc.subtractToRef(point, this._tempVector3);
  10615. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10616. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10617. if (d < 0)
  10618. return false;
  10619. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10620. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10621. return d >= 0;
  10622. };
  10623. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10624. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10625. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10626. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10627. return false;
  10628. }
  10629. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10630. return false;
  10631. return true;
  10632. };
  10633. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10634. var t0;
  10635. var embeddedInPlane = false;
  10636. //defensive programming, actually not needed.
  10637. if (!trianglePlaneArray) {
  10638. trianglePlaneArray = [];
  10639. }
  10640. if (!trianglePlaneArray[faceIndex]) {
  10641. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10642. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10643. }
  10644. var trianglePlane = trianglePlaneArray[faceIndex];
  10645. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10646. return;
  10647. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10648. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10649. if (normalDotVelocity == 0) {
  10650. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10651. return;
  10652. embeddedInPlane = true;
  10653. t0 = 0;
  10654. }
  10655. else {
  10656. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10657. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10658. if (t0 > t1) {
  10659. var temp = t1;
  10660. t1 = t0;
  10661. t0 = temp;
  10662. }
  10663. if (t0 > 1.0 || t1 < 0.0)
  10664. return;
  10665. if (t0 < 0)
  10666. t0 = 0;
  10667. if (t0 > 1.0)
  10668. t0 = 1.0;
  10669. }
  10670. this._collisionPoint.copyFromFloats(0, 0, 0);
  10671. var found = false;
  10672. var t = 1.0;
  10673. if (!embeddedInPlane) {
  10674. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10675. this.velocity.scaleToRef(t0, this._tempVector);
  10676. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10677. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10678. found = true;
  10679. t = t0;
  10680. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10681. }
  10682. }
  10683. if (!found) {
  10684. var velocitySquaredLength = this.velocity.lengthSquared();
  10685. var a = velocitySquaredLength;
  10686. this.basePoint.subtractToRef(p1, this._tempVector);
  10687. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10688. var c = this._tempVector.lengthSquared() - 1.0;
  10689. var lowestRoot = getLowestRoot(a, b, c, t);
  10690. if (lowestRoot.found) {
  10691. t = lowestRoot.root;
  10692. found = true;
  10693. this._collisionPoint.copyFrom(p1);
  10694. }
  10695. this.basePoint.subtractToRef(p2, this._tempVector);
  10696. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10697. c = this._tempVector.lengthSquared() - 1.0;
  10698. lowestRoot = getLowestRoot(a, b, c, t);
  10699. if (lowestRoot.found) {
  10700. t = lowestRoot.root;
  10701. found = true;
  10702. this._collisionPoint.copyFrom(p2);
  10703. }
  10704. this.basePoint.subtractToRef(p3, this._tempVector);
  10705. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10706. c = this._tempVector.lengthSquared() - 1.0;
  10707. lowestRoot = getLowestRoot(a, b, c, t);
  10708. if (lowestRoot.found) {
  10709. t = lowestRoot.root;
  10710. found = true;
  10711. this._collisionPoint.copyFrom(p3);
  10712. }
  10713. p2.subtractToRef(p1, this._edge);
  10714. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10715. var edgeSquaredLength = this._edge.lengthSquared();
  10716. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10717. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10718. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10719. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10720. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10721. lowestRoot = getLowestRoot(a, b, c, t);
  10722. if (lowestRoot.found) {
  10723. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10724. if (f >= 0.0 && f <= 1.0) {
  10725. t = lowestRoot.root;
  10726. found = true;
  10727. this._edge.scaleInPlace(f);
  10728. p1.addToRef(this._edge, this._collisionPoint);
  10729. }
  10730. }
  10731. p3.subtractToRef(p2, this._edge);
  10732. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10733. edgeSquaredLength = this._edge.lengthSquared();
  10734. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10735. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10736. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10737. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10738. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10739. lowestRoot = getLowestRoot(a, b, c, t);
  10740. if (lowestRoot.found) {
  10741. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10742. if (f >= 0.0 && f <= 1.0) {
  10743. t = lowestRoot.root;
  10744. found = true;
  10745. this._edge.scaleInPlace(f);
  10746. p2.addToRef(this._edge, this._collisionPoint);
  10747. }
  10748. }
  10749. p1.subtractToRef(p3, this._edge);
  10750. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10751. edgeSquaredLength = this._edge.lengthSquared();
  10752. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10753. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10754. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10755. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10756. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10757. lowestRoot = getLowestRoot(a, b, c, t);
  10758. if (lowestRoot.found) {
  10759. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10760. if (f >= 0.0 && f <= 1.0) {
  10761. t = lowestRoot.root;
  10762. found = true;
  10763. this._edge.scaleInPlace(f);
  10764. p3.addToRef(this._edge, this._collisionPoint);
  10765. }
  10766. }
  10767. }
  10768. if (found) {
  10769. var distToCollision = t * this.velocity.length();
  10770. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10771. if (!this.intersectionPoint) {
  10772. this.intersectionPoint = this._collisionPoint.clone();
  10773. }
  10774. else {
  10775. this.intersectionPoint.copyFrom(this._collisionPoint);
  10776. }
  10777. this.nearestDistance = distToCollision;
  10778. this.collisionFound = true;
  10779. }
  10780. }
  10781. };
  10782. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10783. for (var i = indexStart; i < indexEnd; i += 3) {
  10784. var p1 = pts[indices[i] - decal];
  10785. var p2 = pts[indices[i + 1] - decal];
  10786. var p3 = pts[indices[i + 2] - decal];
  10787. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10788. }
  10789. };
  10790. Collider.prototype._getResponse = function (pos, vel) {
  10791. pos.addToRef(vel, this._destinationPoint);
  10792. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10793. this.basePoint.addToRef(vel, pos);
  10794. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10795. this._slidePlaneNormal.normalize();
  10796. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10797. pos.addInPlace(this._displacementVector);
  10798. this.intersectionPoint.addInPlace(this._displacementVector);
  10799. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10800. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10801. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10802. };
  10803. return Collider;
  10804. })();
  10805. BABYLON.Collider = Collider;
  10806. })(BABYLON || (BABYLON = {}));
  10807. var BABYLON;
  10808. (function (BABYLON) {
  10809. //WebWorker code will be inserted to this variable.
  10810. BABYLON.CollisionWorker = "";
  10811. (function (WorkerTaskType) {
  10812. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10813. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10814. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10815. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10816. var WorkerTaskType = BABYLON.WorkerTaskType;
  10817. (function (WorkerReplyType) {
  10818. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10819. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10820. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10821. var WorkerReplyType = BABYLON.WorkerReplyType;
  10822. var CollisionCoordinatorWorker = (function () {
  10823. function CollisionCoordinatorWorker() {
  10824. var _this = this;
  10825. this._scaledPosition = BABYLON.Vector3.Zero();
  10826. this._scaledVelocity = BABYLON.Vector3.Zero();
  10827. this.onMeshUpdated = function (mesh) {
  10828. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10829. };
  10830. this.onGeometryUpdated = function (geometry) {
  10831. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10832. };
  10833. this._afterRender = function () {
  10834. if (!_this._init)
  10835. return;
  10836. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10837. return;
  10838. }
  10839. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10840. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10841. if (_this._runningUpdated > 4) {
  10842. return;
  10843. }
  10844. ++_this._runningUpdated;
  10845. var payload = {
  10846. updatedMeshes: _this._addUpdateMeshesList,
  10847. updatedGeometries: _this._addUpdateGeometriesList,
  10848. removedGeometries: _this._toRemoveGeometryArray,
  10849. removedMeshes: _this._toRemoveMeshesArray
  10850. };
  10851. var message = {
  10852. payload: payload,
  10853. taskType: WorkerTaskType.UPDATE
  10854. };
  10855. var serializable = [];
  10856. for (var id in payload.updatedGeometries) {
  10857. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10858. //prepare transferables
  10859. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10860. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10861. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10862. }
  10863. }
  10864. _this._worker.postMessage(message, serializable);
  10865. _this._addUpdateMeshesList = {};
  10866. _this._addUpdateGeometriesList = {};
  10867. _this._toRemoveGeometryArray = [];
  10868. _this._toRemoveMeshesArray = [];
  10869. };
  10870. this._onMessageFromWorker = function (e) {
  10871. var returnData = e.data;
  10872. if (returnData.error != WorkerReplyType.SUCCESS) {
  10873. //TODO what errors can be returned from the worker?
  10874. BABYLON.Tools.Warn("error returned from worker!");
  10875. return;
  10876. }
  10877. switch (returnData.taskType) {
  10878. case WorkerTaskType.INIT:
  10879. _this._init = true;
  10880. //Update the worked with ALL of the scene's current state
  10881. _this._scene.meshes.forEach(function (mesh) {
  10882. _this.onMeshAdded(mesh);
  10883. });
  10884. _this._scene.getGeometries().forEach(function (geometry) {
  10885. _this.onGeometryAdded(geometry);
  10886. });
  10887. break;
  10888. case WorkerTaskType.UPDATE:
  10889. _this._runningUpdated--;
  10890. break;
  10891. case WorkerTaskType.COLLIDE:
  10892. _this._runningCollisionTask = false;
  10893. var returnPayload = returnData.payload;
  10894. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10895. return;
  10896. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10897. //cleanup
  10898. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10899. break;
  10900. }
  10901. };
  10902. this._collisionsCallbackArray = [];
  10903. this._init = false;
  10904. this._runningUpdated = 0;
  10905. this._runningCollisionTask = false;
  10906. this._addUpdateMeshesList = {};
  10907. this._addUpdateGeometriesList = {};
  10908. this._toRemoveGeometryArray = [];
  10909. this._toRemoveMeshesArray = [];
  10910. }
  10911. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10912. if (!this._init)
  10913. return;
  10914. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10915. return;
  10916. position.divideToRef(collider.radius, this._scaledPosition);
  10917. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10918. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10919. var payload = {
  10920. collider: {
  10921. position: this._scaledPosition.asArray(),
  10922. velocity: this._scaledVelocity.asArray(),
  10923. radius: collider.radius.asArray()
  10924. },
  10925. collisionId: collisionIndex,
  10926. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10927. maximumRetry: maximumRetry
  10928. };
  10929. var message = {
  10930. payload: payload,
  10931. taskType: WorkerTaskType.COLLIDE
  10932. };
  10933. this._worker.postMessage(message);
  10934. };
  10935. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10936. this._scene = scene;
  10937. this._scene.registerAfterRender(this._afterRender);
  10938. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10939. this._worker = new Worker(workerUrl);
  10940. this._worker.onmessage = this._onMessageFromWorker;
  10941. var message = {
  10942. payload: {},
  10943. taskType: WorkerTaskType.INIT
  10944. };
  10945. this._worker.postMessage(message);
  10946. };
  10947. CollisionCoordinatorWorker.prototype.destroy = function () {
  10948. this._scene.unregisterAfterRender(this._afterRender);
  10949. this._worker.terminate();
  10950. };
  10951. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10952. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10953. this.onMeshUpdated(mesh);
  10954. };
  10955. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10956. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10957. };
  10958. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10959. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10960. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10961. this.onGeometryUpdated(geometry);
  10962. };
  10963. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10964. this._toRemoveGeometryArray.push(geometry.id);
  10965. };
  10966. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10967. var submeshes = [];
  10968. if (mesh.subMeshes) {
  10969. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10970. return {
  10971. position: idx,
  10972. verticesStart: sm.verticesStart,
  10973. verticesCount: sm.verticesCount,
  10974. indexStart: sm.indexStart,
  10975. indexCount: sm.indexCount,
  10976. hasMaterial: !!sm.getMaterial(),
  10977. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10978. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10979. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10980. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10981. };
  10982. });
  10983. }
  10984. var geometryId = null;
  10985. if (mesh instanceof BABYLON.Mesh) {
  10986. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10987. }
  10988. else if (mesh instanceof BABYLON.InstancedMesh) {
  10989. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10990. }
  10991. return {
  10992. uniqueId: mesh.uniqueId,
  10993. id: mesh.id,
  10994. name: mesh.name,
  10995. geometryId: geometryId,
  10996. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10997. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10998. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10999. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11000. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11001. subMeshes: submeshes,
  11002. checkCollisions: mesh.checkCollisions
  11003. };
  11004. };
  11005. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11006. return {
  11007. id: geometry.id,
  11008. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11009. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11010. indices: new Int32Array(geometry.getIndices() || []),
  11011. };
  11012. };
  11013. return CollisionCoordinatorWorker;
  11014. })();
  11015. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11016. var CollisionCoordinatorLegacy = (function () {
  11017. function CollisionCoordinatorLegacy() {
  11018. this._scaledPosition = BABYLON.Vector3.Zero();
  11019. this._scaledVelocity = BABYLON.Vector3.Zero();
  11020. this._finalPosition = BABYLON.Vector3.Zero();
  11021. }
  11022. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11023. position.divideToRef(collider.radius, this._scaledPosition);
  11024. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11025. collider.collidedMesh = null;
  11026. collider.retry = 0;
  11027. collider.initialVelocity = this._scaledVelocity;
  11028. collider.initialPosition = this._scaledPosition;
  11029. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11030. this._finalPosition.multiplyInPlace(collider.radius);
  11031. //run the callback
  11032. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11033. };
  11034. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11035. this._scene = scene;
  11036. };
  11037. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11038. //Legacy need no destruction method.
  11039. };
  11040. //No update in legacy mode
  11041. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11042. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11043. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11044. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11045. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11046. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11047. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11048. if (excludedMesh === void 0) { excludedMesh = null; }
  11049. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11050. if (collider.retry >= maximumRetry) {
  11051. finalPosition.copyFrom(position);
  11052. return;
  11053. }
  11054. collider._initialize(position, velocity, closeDistance);
  11055. // Check all meshes
  11056. for (var index = 0; index < this._scene.meshes.length; index++) {
  11057. var mesh = this._scene.meshes[index];
  11058. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11059. mesh._checkCollision(collider);
  11060. }
  11061. }
  11062. if (!collider.collisionFound) {
  11063. position.addToRef(velocity, finalPosition);
  11064. return;
  11065. }
  11066. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11067. collider._getResponse(position, velocity);
  11068. }
  11069. if (velocity.length() <= closeDistance) {
  11070. finalPosition.copyFrom(position);
  11071. return;
  11072. }
  11073. collider.retry++;
  11074. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11075. };
  11076. return CollisionCoordinatorLegacy;
  11077. })();
  11078. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11079. })(BABYLON || (BABYLON = {}));
  11080. var BABYLON;
  11081. (function (BABYLON) {
  11082. var Camera = (function (_super) {
  11083. __extends(Camera, _super);
  11084. function Camera(name, position, scene) {
  11085. _super.call(this, name, scene);
  11086. this.upVector = BABYLON.Vector3.Up();
  11087. this.orthoLeft = null;
  11088. this.orthoRight = null;
  11089. this.orthoBottom = null;
  11090. this.orthoTop = null;
  11091. this.fov = 0.8;
  11092. this.minZ = 1.0;
  11093. this.maxZ = 10000.0;
  11094. this.inertia = 0.9;
  11095. this.mode = Camera.PERSPECTIVE_CAMERA;
  11096. this.isIntermediate = false;
  11097. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11098. this.layerMask = 0x0FFFFFFF;
  11099. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11100. // Camera rig members
  11101. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11102. this._rigCameras = new Array();
  11103. // Cache
  11104. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11105. this._projectionMatrix = new BABYLON.Matrix();
  11106. this._postProcesses = new Array();
  11107. this._activeMeshes = new BABYLON.SmartArray(256);
  11108. this._globalPosition = BABYLON.Vector3.Zero();
  11109. scene.addCamera(this);
  11110. if (!scene.activeCamera) {
  11111. scene.activeCamera = this;
  11112. }
  11113. this.position = position;
  11114. }
  11115. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11116. get: function () {
  11117. return Camera._PERSPECTIVE_CAMERA;
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11123. get: function () {
  11124. return Camera._ORTHOGRAPHIC_CAMERA;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11130. get: function () {
  11131. return Camera._FOVMODE_VERTICAL_FIXED;
  11132. },
  11133. enumerable: true,
  11134. configurable: true
  11135. });
  11136. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11137. get: function () {
  11138. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11144. get: function () {
  11145. return Camera._RIG_MODE_NONE;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11151. get: function () {
  11152. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11153. },
  11154. enumerable: true,
  11155. configurable: true
  11156. });
  11157. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11158. get: function () {
  11159. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11165. get: function () {
  11166. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11167. },
  11168. enumerable: true,
  11169. configurable: true
  11170. });
  11171. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11172. get: function () {
  11173. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11174. },
  11175. enumerable: true,
  11176. configurable: true
  11177. });
  11178. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11179. get: function () {
  11180. return Camera._RIG_MODE_VR;
  11181. },
  11182. enumerable: true,
  11183. configurable: true
  11184. });
  11185. /**
  11186. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11187. */
  11188. Camera.prototype.toString = function (fullDetails) {
  11189. var ret = "Name: " + this.name;
  11190. ret += ", type: " + this.getTypeName();
  11191. if (this.animations) {
  11192. for (var i = 0; i < this.animations.length; i++) {
  11193. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11194. }
  11195. }
  11196. if (fullDetails) {
  11197. }
  11198. return ret;
  11199. };
  11200. Object.defineProperty(Camera.prototype, "globalPosition", {
  11201. get: function () {
  11202. return this._globalPosition;
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Camera.prototype.getActiveMeshes = function () {
  11208. return this._activeMeshes;
  11209. };
  11210. Camera.prototype.isActiveMesh = function (mesh) {
  11211. return (this._activeMeshes.indexOf(mesh) !== -1);
  11212. };
  11213. //Cache
  11214. Camera.prototype._initCache = function () {
  11215. _super.prototype._initCache.call(this);
  11216. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11217. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11218. this._cache.mode = undefined;
  11219. this._cache.minZ = undefined;
  11220. this._cache.maxZ = undefined;
  11221. this._cache.fov = undefined;
  11222. this._cache.aspectRatio = undefined;
  11223. this._cache.orthoLeft = undefined;
  11224. this._cache.orthoRight = undefined;
  11225. this._cache.orthoBottom = undefined;
  11226. this._cache.orthoTop = undefined;
  11227. this._cache.renderWidth = undefined;
  11228. this._cache.renderHeight = undefined;
  11229. };
  11230. Camera.prototype._updateCache = function (ignoreParentClass) {
  11231. if (!ignoreParentClass) {
  11232. _super.prototype._updateCache.call(this);
  11233. }
  11234. var engine = this.getEngine();
  11235. this._cache.position.copyFrom(this.position);
  11236. this._cache.upVector.copyFrom(this.upVector);
  11237. this._cache.mode = this.mode;
  11238. this._cache.minZ = this.minZ;
  11239. this._cache.maxZ = this.maxZ;
  11240. this._cache.fov = this.fov;
  11241. this._cache.aspectRatio = engine.getAspectRatio(this);
  11242. this._cache.orthoLeft = this.orthoLeft;
  11243. this._cache.orthoRight = this.orthoRight;
  11244. this._cache.orthoBottom = this.orthoBottom;
  11245. this._cache.orthoTop = this.orthoTop;
  11246. this._cache.renderWidth = engine.getRenderWidth();
  11247. this._cache.renderHeight = engine.getRenderHeight();
  11248. };
  11249. Camera.prototype._updateFromScene = function () {
  11250. this.updateCache();
  11251. this._update();
  11252. };
  11253. // Synchronized
  11254. Camera.prototype._isSynchronized = function () {
  11255. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11256. };
  11257. Camera.prototype._isSynchronizedViewMatrix = function () {
  11258. if (!_super.prototype._isSynchronized.call(this))
  11259. return false;
  11260. return this._cache.position.equals(this.position)
  11261. && this._cache.upVector.equals(this.upVector)
  11262. && this.isSynchronizedWithParent();
  11263. };
  11264. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11265. var check = this._cache.mode === this.mode
  11266. && this._cache.minZ === this.minZ
  11267. && this._cache.maxZ === this.maxZ;
  11268. if (!check) {
  11269. return false;
  11270. }
  11271. var engine = this.getEngine();
  11272. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11273. check = this._cache.fov === this.fov
  11274. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11275. }
  11276. else {
  11277. check = this._cache.orthoLeft === this.orthoLeft
  11278. && this._cache.orthoRight === this.orthoRight
  11279. && this._cache.orthoBottom === this.orthoBottom
  11280. && this._cache.orthoTop === this.orthoTop
  11281. && this._cache.renderWidth === engine.getRenderWidth()
  11282. && this._cache.renderHeight === engine.getRenderHeight();
  11283. }
  11284. return check;
  11285. };
  11286. // Controls
  11287. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11288. };
  11289. Camera.prototype.detachControl = function (element) {
  11290. };
  11291. Camera.prototype._update = function () {
  11292. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11293. this._updateRigCameras();
  11294. }
  11295. this._checkInputs();
  11296. };
  11297. Camera.prototype._checkInputs = function () {
  11298. };
  11299. Camera.prototype._cascadePostProcessesToRigCams = function () {
  11300. // invalidate framebuffer
  11301. if (this._postProcesses.length > 0) {
  11302. this._postProcesses[0].markTextureDirty();
  11303. }
  11304. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  11305. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  11306. var cam = this._rigCameras[i];
  11307. var rigPostProcess = cam._rigPostProcess;
  11308. // for VR rig, there does not have to be a post process
  11309. if (rigPostProcess) {
  11310. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  11311. if (isPass) {
  11312. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  11313. cam.isIntermediate = this._postProcesses.length === 0;
  11314. }
  11315. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  11316. rigPostProcess.markTextureDirty();
  11317. }
  11318. }
  11319. };
  11320. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11321. if (insertAt === void 0) { insertAt = null; }
  11322. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11323. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11324. return 0;
  11325. }
  11326. if (insertAt == null || insertAt < 0) {
  11327. this._postProcesses.push(postProcess);
  11328. }
  11329. else {
  11330. this._postProcesses.splice(insertAt, 0, postProcess);
  11331. }
  11332. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11333. return this._postProcesses.indexOf(postProcess);
  11334. };
  11335. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11336. if (atIndices === void 0) { atIndices = null; }
  11337. var result = [];
  11338. var i;
  11339. var index;
  11340. if (!atIndices) {
  11341. var idx = this._postProcesses.indexOf(postProcess);
  11342. if (idx !== -1) {
  11343. this._postProcesses.splice(idx, 1);
  11344. }
  11345. }
  11346. else {
  11347. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11348. // iterate descending, so can just splice as we go
  11349. for (i = atIndices.length - 1; i >= 0; i--) {
  11350. if (this._postProcesses[atIndices[i]] !== postProcess) {
  11351. result.push(i);
  11352. continue;
  11353. }
  11354. this._postProcesses.splice(index, 1);
  11355. }
  11356. }
  11357. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11358. return result;
  11359. };
  11360. Camera.prototype.getWorldMatrix = function () {
  11361. if (!this._worldMatrix) {
  11362. this._worldMatrix = BABYLON.Matrix.Identity();
  11363. }
  11364. var viewMatrix = this.getViewMatrix();
  11365. viewMatrix.invertToRef(this._worldMatrix);
  11366. return this._worldMatrix;
  11367. };
  11368. Camera.prototype._getViewMatrix = function () {
  11369. return BABYLON.Matrix.Identity();
  11370. };
  11371. Camera.prototype.getViewMatrix = function (force) {
  11372. this._computedViewMatrix = this._computeViewMatrix(force);
  11373. if (!force && this._isSynchronizedViewMatrix()) {
  11374. return this._computedViewMatrix;
  11375. }
  11376. if (!this.parent || !this.parent.getWorldMatrix) {
  11377. this._globalPosition.copyFrom(this.position);
  11378. }
  11379. else {
  11380. if (!this._worldMatrix) {
  11381. this._worldMatrix = BABYLON.Matrix.Identity();
  11382. }
  11383. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11384. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11385. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11386. this._computedViewMatrix.invert();
  11387. this._markSyncedWithParent();
  11388. }
  11389. this._currentRenderId = this.getScene().getRenderId();
  11390. return this._computedViewMatrix;
  11391. };
  11392. Camera.prototype._computeViewMatrix = function (force) {
  11393. if (!force && this._isSynchronizedViewMatrix()) {
  11394. return this._computedViewMatrix;
  11395. }
  11396. this._computedViewMatrix = this._getViewMatrix();
  11397. this._currentRenderId = this.getScene().getRenderId();
  11398. return this._computedViewMatrix;
  11399. };
  11400. Camera.prototype.getProjectionMatrix = function (force) {
  11401. if (!force && this._isSynchronizedProjectionMatrix()) {
  11402. return this._projectionMatrix;
  11403. }
  11404. var engine = this.getEngine();
  11405. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11406. if (this.minZ <= 0) {
  11407. this.minZ = 0.1;
  11408. }
  11409. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11410. return this._projectionMatrix;
  11411. }
  11412. var halfWidth = engine.getRenderWidth() / 2.0;
  11413. var halfHeight = engine.getRenderHeight() / 2.0;
  11414. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11415. return this._projectionMatrix;
  11416. };
  11417. Camera.prototype.dispose = function () {
  11418. // Animations
  11419. this.getScene().stopAnimation(this);
  11420. // Remove from scene
  11421. this.getScene().removeCamera(this);
  11422. while (this._rigCameras.length > 0) {
  11423. this._rigCameras.pop().dispose();
  11424. }
  11425. // Postprocesses
  11426. for (var i = 0; i < this._postProcesses.length; ++i) {
  11427. this._postProcesses[i].dispose(this);
  11428. }
  11429. _super.prototype.dispose.call(this);
  11430. };
  11431. // ---- Camera rigs section ----
  11432. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11433. while (this._rigCameras.length > 0) {
  11434. this._rigCameras.pop().dispose();
  11435. }
  11436. this.cameraRigMode = mode;
  11437. this._cameraRigParams = {};
  11438. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11439. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11440. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11441. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11442. // create the rig cameras, unless none
  11443. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11444. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11445. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11446. }
  11447. switch (this.cameraRigMode) {
  11448. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11449. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11450. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  11451. break;
  11452. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11453. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11454. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11455. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11456. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11457. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  11458. break;
  11459. case Camera.RIG_MODE_VR:
  11460. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11461. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11462. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11463. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11464. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11465. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11466. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11467. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  11468. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11469. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11470. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11471. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11472. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11473. if (metrics.compensateDistortion) {
  11474. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  11475. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  11476. }
  11477. break;
  11478. }
  11479. this._cascadePostProcessesToRigCams();
  11480. this._update();
  11481. };
  11482. Camera.prototype._getVRProjectionMatrix = function () {
  11483. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11484. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11485. return this._projectionMatrix;
  11486. };
  11487. Camera.prototype.setCameraRigParameter = function (name, value) {
  11488. if (!this._cameraRigParams) {
  11489. this._cameraRigParams = {};
  11490. }
  11491. this._cameraRigParams[name] = value;
  11492. //provisionnally:
  11493. if (name === "interaxialDistance") {
  11494. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11495. }
  11496. };
  11497. /**
  11498. * needs to be overridden by children so sub has required properties to be copied
  11499. */
  11500. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11501. return null;
  11502. };
  11503. /**
  11504. * May need to be overridden by children
  11505. */
  11506. Camera.prototype._updateRigCameras = function () {
  11507. for (var i = 0; i < this._rigCameras.length; i++) {
  11508. this._rigCameras[i].minZ = this.minZ;
  11509. this._rigCameras[i].maxZ = this.maxZ;
  11510. this._rigCameras[i].fov = this.fov;
  11511. }
  11512. // only update viewport when ANAGLYPH
  11513. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11514. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11515. }
  11516. };
  11517. Camera.prototype._setupInputs = function () {
  11518. };
  11519. Camera.prototype.serialize = function () {
  11520. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11521. // Type
  11522. serializationObject.type = this.getTypeName();
  11523. // Parent
  11524. if (this.parent) {
  11525. serializationObject.parentId = this.parent.id;
  11526. }
  11527. if (this.inputs) {
  11528. this.inputs.serialize(serializationObject);
  11529. }
  11530. // Animations
  11531. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11532. serializationObject.ranges = this.serializeAnimationRanges();
  11533. return serializationObject;
  11534. };
  11535. Camera.prototype.getTypeName = function () {
  11536. return "Camera";
  11537. };
  11538. Camera.prototype.clone = function (name) {
  11539. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11540. };
  11541. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11542. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11543. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11544. switch (type) {
  11545. case "ArcRotateCamera":
  11546. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11547. case "DeviceOrientationCamera":
  11548. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11549. case "FollowCamera":
  11550. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11551. case "ArcFollowCamera":
  11552. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11553. case "GamepadCamera":
  11554. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11555. case "TouchCamera":
  11556. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11557. case "VirtualJoysticksCamera":
  11558. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11559. case "WebVRFreeCamera":
  11560. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11561. case "VRDeviceOrientationFreeCamera":
  11562. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11563. case "AnaglyphArcRotateCamera":
  11564. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11565. case "AnaglyphFreeCamera":
  11566. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11567. case "AnaglyphGamepadCamera":
  11568. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11569. case "AnaglyphUniversalCamera":
  11570. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11571. case "StereoscopicArcRotateCamera":
  11572. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11573. case "StereoscopicFreeCamera":
  11574. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11575. case "StereoscopicGamepadCamera":
  11576. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11577. case "StereoscopicUniversalCamera":
  11578. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11579. case "FreeCamera":
  11580. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11581. default:
  11582. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11583. }
  11584. };
  11585. Camera.Parse = function (parsedCamera, scene) {
  11586. var type = parsedCamera.type;
  11587. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11588. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11589. // Parent
  11590. if (parsedCamera.parentId) {
  11591. camera._waitingParentId = parsedCamera.parentId;
  11592. }
  11593. //If camera has an input manager, let it parse inputs settings
  11594. if (camera.inputs) {
  11595. camera.inputs.parse(parsedCamera);
  11596. camera._setupInputs();
  11597. }
  11598. // Target
  11599. if (parsedCamera.target) {
  11600. if (camera.setTarget) {
  11601. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11602. }
  11603. }
  11604. // Apply 3d rig, when found
  11605. if (parsedCamera.cameraRigMode) {
  11606. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11607. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11608. }
  11609. // Animations
  11610. if (parsedCamera.animations) {
  11611. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11612. var parsedAnimation = parsedCamera.animations[animationIndex];
  11613. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11614. }
  11615. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11616. }
  11617. if (parsedCamera.autoAnimate) {
  11618. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11619. }
  11620. return camera;
  11621. };
  11622. // Statics
  11623. Camera._PERSPECTIVE_CAMERA = 0;
  11624. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11625. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11626. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11627. Camera._RIG_MODE_NONE = 0;
  11628. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11629. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11630. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11631. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11632. Camera._RIG_MODE_VR = 20;
  11633. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11634. __decorate([
  11635. BABYLON.serializeAsVector3()
  11636. ], Camera.prototype, "position", void 0);
  11637. __decorate([
  11638. BABYLON.serializeAsVector3()
  11639. ], Camera.prototype, "upVector", void 0);
  11640. __decorate([
  11641. BABYLON.serialize()
  11642. ], Camera.prototype, "orthoLeft", void 0);
  11643. __decorate([
  11644. BABYLON.serialize()
  11645. ], Camera.prototype, "orthoRight", void 0);
  11646. __decorate([
  11647. BABYLON.serialize()
  11648. ], Camera.prototype, "orthoBottom", void 0);
  11649. __decorate([
  11650. BABYLON.serialize()
  11651. ], Camera.prototype, "orthoTop", void 0);
  11652. __decorate([
  11653. BABYLON.serialize()
  11654. ], Camera.prototype, "fov", void 0);
  11655. __decorate([
  11656. BABYLON.serialize()
  11657. ], Camera.prototype, "minZ", void 0);
  11658. __decorate([
  11659. BABYLON.serialize()
  11660. ], Camera.prototype, "maxZ", void 0);
  11661. __decorate([
  11662. BABYLON.serialize()
  11663. ], Camera.prototype, "inertia", void 0);
  11664. __decorate([
  11665. BABYLON.serialize()
  11666. ], Camera.prototype, "mode", void 0);
  11667. __decorate([
  11668. BABYLON.serialize()
  11669. ], Camera.prototype, "layerMask", void 0);
  11670. __decorate([
  11671. BABYLON.serialize()
  11672. ], Camera.prototype, "fovMode", void 0);
  11673. __decorate([
  11674. BABYLON.serialize()
  11675. ], Camera.prototype, "cameraRigMode", void 0);
  11676. __decorate([
  11677. BABYLON.serialize()
  11678. ], Camera.prototype, "interaxialDistance", void 0);
  11679. __decorate([
  11680. BABYLON.serialize()
  11681. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11682. return Camera;
  11683. })(BABYLON.Node);
  11684. BABYLON.Camera = Camera;
  11685. })(BABYLON || (BABYLON = {}));
  11686. var BABYLON;
  11687. (function (BABYLON) {
  11688. BABYLON.CameraInputTypes = {};
  11689. var CameraInputsManager = (function () {
  11690. function CameraInputsManager(camera) {
  11691. this.attached = {};
  11692. this.camera = camera;
  11693. this.checkInputs = function () { };
  11694. }
  11695. CameraInputsManager.prototype.add = function (input) {
  11696. var type = input.getSimpleName();
  11697. if (this.attached[type]) {
  11698. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11699. return;
  11700. }
  11701. this.attached[type] = input;
  11702. input.camera = this.camera;
  11703. //for checkInputs, we are dynamically creating a function
  11704. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11705. if (input.checkInputs) {
  11706. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11707. }
  11708. if (this.attachedElement) {
  11709. input.attachControl(this.attachedElement);
  11710. }
  11711. };
  11712. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11713. for (var cam in this.attached) {
  11714. var input = this.attached[cam];
  11715. if (input === inputToRemove) {
  11716. input.detachControl(this.attachedElement);
  11717. delete this.attached[cam];
  11718. this.rebuildInputCheck();
  11719. }
  11720. }
  11721. };
  11722. CameraInputsManager.prototype.removeByType = function (inputType) {
  11723. for (var cam in this.attached) {
  11724. var input = this.attached[cam];
  11725. if (input.getTypeName() === inputType) {
  11726. input.detachControl(this.attachedElement);
  11727. delete this.attached[cam];
  11728. this.rebuildInputCheck();
  11729. }
  11730. }
  11731. };
  11732. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11733. var current = this.checkInputs;
  11734. return function () {
  11735. current();
  11736. fn();
  11737. };
  11738. };
  11739. CameraInputsManager.prototype.attachInput = function (input) {
  11740. input.attachControl(this.attachedElement, this.noPreventDefault);
  11741. };
  11742. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11743. if (this.attachedElement) {
  11744. return;
  11745. }
  11746. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11747. this.attachedElement = element;
  11748. this.noPreventDefault = noPreventDefault;
  11749. for (var cam in this.attached) {
  11750. var input = this.attached[cam];
  11751. this.attached[cam].attachControl(element, noPreventDefault);
  11752. }
  11753. };
  11754. CameraInputsManager.prototype.detachElement = function (element) {
  11755. if (this.attachedElement !== element) {
  11756. return;
  11757. }
  11758. for (var cam in this.attached) {
  11759. var input = this.attached[cam];
  11760. this.attached[cam].detachControl(element);
  11761. }
  11762. this.attachedElement = null;
  11763. };
  11764. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11765. this.checkInputs = function () { };
  11766. for (var cam in this.attached) {
  11767. var input = this.attached[cam];
  11768. if (input.checkInputs) {
  11769. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11770. }
  11771. }
  11772. };
  11773. CameraInputsManager.prototype.clear = function () {
  11774. if (this.attachedElement) {
  11775. this.detachElement(this.attachedElement);
  11776. }
  11777. this.attached = {};
  11778. this.attachedElement = null;
  11779. this.checkInputs = function () { };
  11780. };
  11781. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11782. var inputs = {};
  11783. for (var cam in this.attached) {
  11784. var input = this.attached[cam];
  11785. var res = BABYLON.SerializationHelper.Serialize(input);
  11786. inputs[input.getTypeName()] = res;
  11787. }
  11788. serializedCamera.inputsmgr = inputs;
  11789. };
  11790. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11791. var parsedInputs = parsedCamera.inputsmgr;
  11792. if (parsedInputs) {
  11793. this.clear();
  11794. for (var n in parsedInputs) {
  11795. var construct = BABYLON.CameraInputTypes[n];
  11796. if (construct) {
  11797. var parsedinput = parsedInputs[n];
  11798. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11799. this.add(input);
  11800. }
  11801. }
  11802. }
  11803. else {
  11804. //2016-03-08 this part is for managing backward compatibility
  11805. for (var n in this.attached) {
  11806. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11807. if (construct) {
  11808. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11809. this.remove(this.attached[n]);
  11810. this.add(input);
  11811. }
  11812. }
  11813. }
  11814. };
  11815. return CameraInputsManager;
  11816. })();
  11817. BABYLON.CameraInputsManager = CameraInputsManager;
  11818. })(BABYLON || (BABYLON = {}));
  11819. var BABYLON;
  11820. (function (BABYLON) {
  11821. var FreeCameraMouseInput = (function () {
  11822. function FreeCameraMouseInput(touchEnabled) {
  11823. if (touchEnabled === void 0) { touchEnabled = true; }
  11824. this.touchEnabled = touchEnabled;
  11825. this.angularSensibility = 2000.0;
  11826. }
  11827. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11828. var _this = this;
  11829. if (!this._pointerInput) {
  11830. var camera = this.camera;
  11831. var engine = this.camera.getEngine();
  11832. this._pointerInput = function (p, s) {
  11833. var evt = p.event;
  11834. if (!_this.touchEnabled && evt.pointerType === "touch") {
  11835. return;
  11836. }
  11837. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11838. try {
  11839. evt.srcElement.setPointerCapture(evt.pointerId);
  11840. }
  11841. catch (e) {
  11842. }
  11843. _this.previousPosition = {
  11844. x: evt.clientX,
  11845. y: evt.clientY
  11846. };
  11847. if (!noPreventDefault) {
  11848. evt.preventDefault();
  11849. }
  11850. }
  11851. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11852. try {
  11853. evt.srcElement.releasePointerCapture(evt.pointerId);
  11854. }
  11855. catch (e) {
  11856. }
  11857. _this.previousPosition = null;
  11858. if (!noPreventDefault) {
  11859. evt.preventDefault();
  11860. }
  11861. }
  11862. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11863. if (!_this.previousPosition && !engine.isPointerLock) {
  11864. return;
  11865. }
  11866. var offsetX;
  11867. var offsetY;
  11868. if (!engine.isPointerLock) {
  11869. offsetX = evt.clientX - _this.previousPosition.x;
  11870. offsetY = evt.clientY - _this.previousPosition.y;
  11871. }
  11872. else {
  11873. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11874. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11875. }
  11876. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11877. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11878. _this.previousPosition = {
  11879. x: evt.clientX,
  11880. y: evt.clientY
  11881. };
  11882. if (!noPreventDefault) {
  11883. evt.preventDefault();
  11884. }
  11885. }
  11886. };
  11887. }
  11888. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11889. };
  11890. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11891. if (this._observer && element) {
  11892. this.camera.getScene().onPointerObservable.remove(this._observer);
  11893. this._observer = null;
  11894. this.previousPosition = null;
  11895. }
  11896. };
  11897. FreeCameraMouseInput.prototype.getTypeName = function () {
  11898. return "FreeCameraMouseInput";
  11899. };
  11900. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11901. return "mouse";
  11902. };
  11903. __decorate([
  11904. BABYLON.serialize()
  11905. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11906. return FreeCameraMouseInput;
  11907. })();
  11908. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11909. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11910. })(BABYLON || (BABYLON = {}));
  11911. var BABYLON;
  11912. (function (BABYLON) {
  11913. var FreeCameraKeyboardMoveInput = (function () {
  11914. function FreeCameraKeyboardMoveInput() {
  11915. this._keys = [];
  11916. this.keysUp = [38];
  11917. this.keysDown = [40];
  11918. this.keysLeft = [37];
  11919. this.keysRight = [39];
  11920. }
  11921. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11922. var _this = this;
  11923. if (!this._onKeyDown) {
  11924. this._onKeyDown = function (evt) {
  11925. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11926. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11927. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11928. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11929. var index = _this._keys.indexOf(evt.keyCode);
  11930. if (index === -1) {
  11931. _this._keys.push(evt.keyCode);
  11932. }
  11933. if (!noPreventDefault) {
  11934. evt.preventDefault();
  11935. }
  11936. }
  11937. };
  11938. this._onKeyUp = function (evt) {
  11939. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11940. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11941. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11942. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11943. var index = _this._keys.indexOf(evt.keyCode);
  11944. if (index >= 0) {
  11945. _this._keys.splice(index, 1);
  11946. }
  11947. if (!noPreventDefault) {
  11948. evt.preventDefault();
  11949. }
  11950. }
  11951. };
  11952. BABYLON.Tools.RegisterTopRootEvents([
  11953. { name: "keydown", handler: this._onKeyDown },
  11954. { name: "keyup", handler: this._onKeyUp },
  11955. { name: "blur", handler: this._onLostFocus }
  11956. ]);
  11957. }
  11958. };
  11959. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11960. if (this._onKeyDown) {
  11961. BABYLON.Tools.UnregisterTopRootEvents([
  11962. { name: "keydown", handler: this._onKeyDown },
  11963. { name: "keyup", handler: this._onKeyUp },
  11964. { name: "blur", handler: this._onLostFocus }
  11965. ]);
  11966. this._keys = [];
  11967. this._onKeyDown = null;
  11968. this._onKeyUp = null;
  11969. }
  11970. };
  11971. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11972. if (this._onKeyDown) {
  11973. var camera = this.camera;
  11974. // Keyboard
  11975. for (var index = 0; index < this._keys.length; index++) {
  11976. var keyCode = this._keys[index];
  11977. var speed = camera._computeLocalCameraSpeed();
  11978. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11979. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11980. }
  11981. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11982. camera._localDirection.copyFromFloats(0, 0, speed);
  11983. }
  11984. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11985. camera._localDirection.copyFromFloats(speed, 0, 0);
  11986. }
  11987. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11988. camera._localDirection.copyFromFloats(0, 0, -speed);
  11989. }
  11990. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11991. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11992. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11993. }
  11994. }
  11995. };
  11996. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11997. return "FreeCameraKeyboardMoveInput";
  11998. };
  11999. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12000. this._keys = [];
  12001. };
  12002. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12003. return "keyboard";
  12004. };
  12005. __decorate([
  12006. BABYLON.serialize()
  12007. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12008. __decorate([
  12009. BABYLON.serialize()
  12010. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12011. __decorate([
  12012. BABYLON.serialize()
  12013. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12014. __decorate([
  12015. BABYLON.serialize()
  12016. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12017. return FreeCameraKeyboardMoveInput;
  12018. })();
  12019. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12020. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12021. })(BABYLON || (BABYLON = {}));
  12022. var BABYLON;
  12023. (function (BABYLON) {
  12024. var FreeCameraTouchInput = (function () {
  12025. function FreeCameraTouchInput() {
  12026. this._offsetX = null;
  12027. this._offsetY = null;
  12028. this._pointerCount = 0;
  12029. this._pointerPressed = [];
  12030. this.touchAngularSensibility = 200000.0;
  12031. this.touchMoveSensibility = 250.0;
  12032. }
  12033. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12034. var _this = this;
  12035. var previousPosition;
  12036. if (this._pointerInput === undefined) {
  12037. this._onLostFocus = function (evt) {
  12038. _this._offsetX = null;
  12039. _this._offsetY = null;
  12040. };
  12041. this._pointerInput = function (p, s) {
  12042. var evt = p.event;
  12043. if (evt.pointerType === "mouse") {
  12044. return;
  12045. }
  12046. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12047. if (!noPreventDefault) {
  12048. evt.preventDefault();
  12049. }
  12050. _this._pointerPressed.push(evt.pointerId);
  12051. if (_this._pointerPressed.length !== 1) {
  12052. return;
  12053. }
  12054. previousPosition = {
  12055. x: evt.clientX,
  12056. y: evt.clientY
  12057. };
  12058. }
  12059. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12060. if (!noPreventDefault) {
  12061. evt.preventDefault();
  12062. }
  12063. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12064. if (index === -1) {
  12065. return;
  12066. }
  12067. _this._pointerPressed.splice(index, 1);
  12068. if (index != 0) {
  12069. return;
  12070. }
  12071. previousPosition = null;
  12072. _this._offsetX = null;
  12073. _this._offsetY = null;
  12074. }
  12075. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12076. if (!noPreventDefault) {
  12077. evt.preventDefault();
  12078. }
  12079. if (!previousPosition) {
  12080. return;
  12081. }
  12082. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12083. if (index != 0) {
  12084. return;
  12085. }
  12086. _this._offsetX = evt.clientX - previousPosition.x;
  12087. _this._offsetY = -(evt.clientY - previousPosition.y);
  12088. }
  12089. };
  12090. }
  12091. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12092. element.addEventListener("blur", this._onLostFocus);
  12093. };
  12094. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12095. if (this._pointerInput && element) {
  12096. this.camera.getScene().onPointerObservable.remove(this._observer);
  12097. this._observer = null;
  12098. element.removeEventListener("blur", this._onLostFocus);
  12099. this._onLostFocus = null;
  12100. this._pointerPressed = [];
  12101. this._offsetX = null;
  12102. this._offsetY = null;
  12103. this._pointerCount = 0;
  12104. }
  12105. };
  12106. FreeCameraTouchInput.prototype.checkInputs = function () {
  12107. if (this._offsetX) {
  12108. var camera = this.camera;
  12109. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12110. if (this._pointerPressed.length > 1) {
  12111. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12112. }
  12113. else {
  12114. var speed = camera._computeLocalCameraSpeed();
  12115. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12116. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12117. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12118. }
  12119. }
  12120. };
  12121. FreeCameraTouchInput.prototype.getTypeName = function () {
  12122. return "FreeCameraTouchInput";
  12123. };
  12124. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12125. return "touch";
  12126. };
  12127. __decorate([
  12128. BABYLON.serialize()
  12129. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12130. __decorate([
  12131. BABYLON.serialize()
  12132. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12133. return FreeCameraTouchInput;
  12134. })();
  12135. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12136. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12137. })(BABYLON || (BABYLON = {}));
  12138. var BABYLON;
  12139. (function (BABYLON) {
  12140. var FreeCameraDeviceOrientationInput = (function () {
  12141. function FreeCameraDeviceOrientationInput() {
  12142. var _this = this;
  12143. this._screenOrientationAngle = 0;
  12144. this._screenQuaternion = new BABYLON.Quaternion();
  12145. this._alpha = 0;
  12146. this._beta = 0;
  12147. this._gamma = 0;
  12148. this._orientationChanged = function () {
  12149. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12150. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12151. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12152. };
  12153. this._deviceOrientation = function (evt) {
  12154. _this._alpha = evt.alpha;
  12155. _this._beta = evt.beta;
  12156. _this._gamma = evt.gamma;
  12157. };
  12158. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12159. this._orientationChanged();
  12160. }
  12161. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12162. get: function () {
  12163. return this._camera;
  12164. },
  12165. set: function (camera) {
  12166. this._camera = camera;
  12167. if (!this._camera.rotationQuaternion)
  12168. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12169. },
  12170. enumerable: true,
  12171. configurable: true
  12172. });
  12173. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12174. window.addEventListener("orientationchange", this._orientationChanged);
  12175. window.addEventListener("deviceorientation", this._deviceOrientation);
  12176. };
  12177. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12178. window.removeEventListener("orientationchange", this._orientationChanged);
  12179. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12180. };
  12181. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12182. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12183. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12184. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12185. //Mirror on XY Plane
  12186. this._camera.rotationQuaternion.z *= -1;
  12187. this._camera.rotationQuaternion.w *= -1;
  12188. };
  12189. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12190. return "FreeCameraDeviceOrientationInput";
  12191. };
  12192. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12193. return "deviceOrientation";
  12194. };
  12195. return FreeCameraDeviceOrientationInput;
  12196. })();
  12197. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12198. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12199. })(BABYLON || (BABYLON = {}));
  12200. var BABYLON;
  12201. (function (BABYLON) {
  12202. var FreeCameraVRDeviceOrientationInput = (function () {
  12203. function FreeCameraVRDeviceOrientationInput() {
  12204. this.alphaCorrection = 1;
  12205. this.betaCorrection = 1;
  12206. this.gammaCorrection = 1;
  12207. this._alpha = 0;
  12208. this._beta = 0;
  12209. this._gamma = 0;
  12210. this._dirty = false;
  12211. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12212. }
  12213. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12214. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12215. };
  12216. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12217. var camera = this.camera;
  12218. this._alpha = evt.alpha;
  12219. this._beta = evt.beta;
  12220. this._gamma = evt.gamma;
  12221. this._dirty = true;
  12222. };
  12223. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12224. if (this._dirty) {
  12225. this._dirty = false;
  12226. var rotationX = this._gamma;
  12227. if (rotationX < 0) {
  12228. rotationX = 90 + rotationX;
  12229. }
  12230. else {
  12231. // Incline it in the correct angle.
  12232. rotationX = 270 - rotationX;
  12233. }
  12234. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12235. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12236. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12237. }
  12238. };
  12239. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12240. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12241. };
  12242. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12243. return "FreeCameraVRDeviceOrientationInput";
  12244. };
  12245. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12246. return "VRDeviceOrientation";
  12247. };
  12248. return FreeCameraVRDeviceOrientationInput;
  12249. })();
  12250. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12251. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12252. })(BABYLON || (BABYLON = {}));
  12253. var BABYLON;
  12254. (function (BABYLON) {
  12255. var FreeCameraGamepadInput = (function () {
  12256. function FreeCameraGamepadInput() {
  12257. this.gamepadAngularSensibility = 200;
  12258. this.gamepadMoveSensibility = 40;
  12259. }
  12260. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12261. var _this = this;
  12262. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12263. };
  12264. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12265. if (this._gamepads) {
  12266. this._gamepads.dispose();
  12267. }
  12268. this.gamepad = null;
  12269. };
  12270. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12271. if (this.gamepad) {
  12272. var camera = this.camera;
  12273. var LSValues = this.gamepad.leftStick;
  12274. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12275. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12276. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12277. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12278. var RSValues = this.gamepad.rightStick;
  12279. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12280. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12281. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12282. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12283. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12284. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12285. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12286. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12287. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12288. }
  12289. };
  12290. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12291. // Only the first gamepad can control the camera
  12292. if (gamepad.index === 0) {
  12293. this.gamepad = gamepad;
  12294. }
  12295. };
  12296. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12297. return "FreeCameraGamepadInput";
  12298. };
  12299. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12300. return "gamepad";
  12301. };
  12302. __decorate([
  12303. BABYLON.serialize()
  12304. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12305. __decorate([
  12306. BABYLON.serialize()
  12307. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12308. return FreeCameraGamepadInput;
  12309. })();
  12310. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12311. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12312. })(BABYLON || (BABYLON = {}));
  12313. var BABYLON;
  12314. (function (BABYLON) {
  12315. var ArcRotateCameraKeyboardMoveInput = (function () {
  12316. function ArcRotateCameraKeyboardMoveInput() {
  12317. this._keys = [];
  12318. this.keysUp = [38];
  12319. this.keysDown = [40];
  12320. this.keysLeft = [37];
  12321. this.keysRight = [39];
  12322. }
  12323. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12324. var _this = this;
  12325. this._onKeyDown = function (evt) {
  12326. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12327. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12328. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12329. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12330. var index = _this._keys.indexOf(evt.keyCode);
  12331. if (index === -1) {
  12332. _this._keys.push(evt.keyCode);
  12333. }
  12334. if (evt.preventDefault) {
  12335. if (!noPreventDefault) {
  12336. evt.preventDefault();
  12337. }
  12338. }
  12339. }
  12340. };
  12341. this._onKeyUp = function (evt) {
  12342. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12343. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12344. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12345. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12346. var index = _this._keys.indexOf(evt.keyCode);
  12347. if (index >= 0) {
  12348. _this._keys.splice(index, 1);
  12349. }
  12350. if (evt.preventDefault) {
  12351. if (!noPreventDefault) {
  12352. evt.preventDefault();
  12353. }
  12354. }
  12355. }
  12356. };
  12357. this._onLostFocus = function () {
  12358. _this._keys = [];
  12359. };
  12360. BABYLON.Tools.RegisterTopRootEvents([
  12361. { name: "keydown", handler: this._onKeyDown },
  12362. { name: "keyup", handler: this._onKeyUp },
  12363. { name: "blur", handler: this._onLostFocus }
  12364. ]);
  12365. };
  12366. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12367. BABYLON.Tools.UnregisterTopRootEvents([
  12368. { name: "keydown", handler: this._onKeyDown },
  12369. { name: "keyup", handler: this._onKeyUp },
  12370. { name: "blur", handler: this._onLostFocus }
  12371. ]);
  12372. this._keys = [];
  12373. this._onKeyDown = null;
  12374. this._onKeyUp = null;
  12375. this._onLostFocus = null;
  12376. };
  12377. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12378. if (this._onKeyDown) {
  12379. var camera = this.camera;
  12380. for (var index = 0; index < this._keys.length; index++) {
  12381. var keyCode = this._keys[index];
  12382. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12383. camera.inertialAlphaOffset -= 0.01;
  12384. }
  12385. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12386. camera.inertialBetaOffset -= 0.01;
  12387. }
  12388. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12389. camera.inertialAlphaOffset += 0.01;
  12390. }
  12391. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12392. camera.inertialBetaOffset += 0.01;
  12393. }
  12394. }
  12395. }
  12396. };
  12397. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12398. return "ArcRotateCameraKeyboardMoveInput";
  12399. };
  12400. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12401. return "keyboard";
  12402. };
  12403. __decorate([
  12404. BABYLON.serialize()
  12405. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12406. __decorate([
  12407. BABYLON.serialize()
  12408. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12409. __decorate([
  12410. BABYLON.serialize()
  12411. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12412. __decorate([
  12413. BABYLON.serialize()
  12414. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12415. return ArcRotateCameraKeyboardMoveInput;
  12416. })();
  12417. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12418. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12419. })(BABYLON || (BABYLON = {}));
  12420. var BABYLON;
  12421. (function (BABYLON) {
  12422. var ArcRotateCameraMouseWheelInput = (function () {
  12423. function ArcRotateCameraMouseWheelInput() {
  12424. this.wheelPrecision = 3.0;
  12425. }
  12426. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12427. var _this = this;
  12428. this._wheel = function (p, s) {
  12429. //sanity check - this should be a PointerWheel event.
  12430. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12431. return;
  12432. var event = p.event;
  12433. var delta = 0;
  12434. if (event.wheelDelta) {
  12435. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12436. }
  12437. else if (event.detail) {
  12438. delta = -event.detail / _this.wheelPrecision;
  12439. }
  12440. if (delta)
  12441. _this.camera.inertialRadiusOffset += delta;
  12442. if (event.preventDefault) {
  12443. if (!noPreventDefault) {
  12444. event.preventDefault();
  12445. }
  12446. }
  12447. };
  12448. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12449. };
  12450. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12451. if (this._observer && element) {
  12452. this.camera.getScene().onPointerObservable.remove(this._observer);
  12453. this._observer = null;
  12454. this._wheel = null;
  12455. }
  12456. };
  12457. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12458. return "ArcRotateCameraMouseWheelInput";
  12459. };
  12460. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12461. return "mousewheel";
  12462. };
  12463. __decorate([
  12464. BABYLON.serialize()
  12465. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12466. return ArcRotateCameraMouseWheelInput;
  12467. })();
  12468. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12469. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12470. })(BABYLON || (BABYLON = {}));
  12471. var BABYLON;
  12472. (function (BABYLON) {
  12473. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12474. var ArcRotateCameraPointersInput = (function () {
  12475. function ArcRotateCameraPointersInput() {
  12476. this.angularSensibilityX = 1000.0;
  12477. this.angularSensibilityY = 1000.0;
  12478. this.pinchPrecision = 6.0;
  12479. this.panningSensibility = 50.0;
  12480. this._isRightClick = false;
  12481. this._isCtrlPushed = false;
  12482. this.pinchInwards = true;
  12483. }
  12484. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12485. var _this = this;
  12486. var engine = this.camera.getEngine();
  12487. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12488. var pointA, pointB;
  12489. var previousPinchDistance = 0;
  12490. this._pointerInput = function (p, s) {
  12491. var evt = p.event;
  12492. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12493. try {
  12494. evt.srcElement.setPointerCapture(evt.pointerId);
  12495. }
  12496. catch (e) {
  12497. }
  12498. // Manage panning with right click
  12499. _this._isRightClick = evt.button === 2;
  12500. // manage pointers
  12501. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  12502. if (pointA === undefined) {
  12503. pointA = cacheSoloPointer;
  12504. }
  12505. else if (pointB === undefined) {
  12506. pointB = cacheSoloPointer;
  12507. }
  12508. if (!noPreventDefault) {
  12509. evt.preventDefault();
  12510. }
  12511. }
  12512. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12513. try {
  12514. evt.srcElement.releasePointerCapture(evt.pointerId);
  12515. }
  12516. catch (e) {
  12517. }
  12518. cacheSoloPointer = null;
  12519. previousPinchDistance = 0;
  12520. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12521. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12522. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12523. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12524. pointA = pointB = undefined;
  12525. if (!noPreventDefault) {
  12526. evt.preventDefault();
  12527. }
  12528. }
  12529. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12530. if (!noPreventDefault) {
  12531. evt.preventDefault();
  12532. }
  12533. // One button down
  12534. if (pointA && pointB === undefined) {
  12535. if (_this.panningSensibility !== 0 &&
  12536. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  12537. (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12538. _this.camera
  12539. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12540. _this.camera
  12541. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12542. }
  12543. else {
  12544. var offsetX = evt.clientX - cacheSoloPointer.x;
  12545. var offsetY = evt.clientY - cacheSoloPointer.y;
  12546. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12547. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12548. }
  12549. cacheSoloPointer.x = evt.clientX;
  12550. cacheSoloPointer.y = evt.clientY;
  12551. }
  12552. else if (pointA && pointB) {
  12553. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12554. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  12555. ed.x = evt.clientX;
  12556. ed.y = evt.clientY;
  12557. var direction = _this.pinchInwards ? 1 : -1;
  12558. var distX = pointA.x - pointB.x;
  12559. var distY = pointA.y - pointB.y;
  12560. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12561. if (previousPinchDistance === 0) {
  12562. previousPinchDistance = pinchSquaredDistance;
  12563. return;
  12564. }
  12565. if (pinchSquaredDistance !== previousPinchDistance) {
  12566. _this.camera
  12567. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  12568. (_this.pinchPrecision *
  12569. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  12570. direction);
  12571. previousPinchDistance = pinchSquaredDistance;
  12572. }
  12573. }
  12574. }
  12575. };
  12576. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12577. this._onContextMenu = function (evt) {
  12578. evt.preventDefault();
  12579. };
  12580. if (!this.camera._useCtrlForPanning) {
  12581. element.addEventListener("contextmenu", this._onContextMenu, false);
  12582. }
  12583. this._onLostFocus = function () {
  12584. //this._keys = [];
  12585. pointA = pointB = undefined;
  12586. previousPinchDistance = 0;
  12587. cacheSoloPointer = null;
  12588. };
  12589. this._onKeyDown = function (evt) {
  12590. _this._isCtrlPushed = evt.ctrlKey;
  12591. };
  12592. this._onKeyUp = function (evt) {
  12593. _this._isCtrlPushed = evt.ctrlKey;
  12594. };
  12595. this._onMouseMove = function (evt) {
  12596. if (!engine.isPointerLock) {
  12597. return;
  12598. }
  12599. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12600. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12601. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12602. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12603. if (!noPreventDefault) {
  12604. evt.preventDefault();
  12605. }
  12606. };
  12607. this._onGestureStart = function (e) {
  12608. if (window.MSGesture === undefined) {
  12609. return;
  12610. }
  12611. if (!_this._MSGestureHandler) {
  12612. _this._MSGestureHandler = new MSGesture();
  12613. _this._MSGestureHandler.target = element;
  12614. }
  12615. _this._MSGestureHandler.addPointer(e.pointerId);
  12616. };
  12617. this._onGesture = function (e) {
  12618. _this.camera.radius *= e.scale;
  12619. if (e.preventDefault) {
  12620. if (!noPreventDefault) {
  12621. e.stopPropagation();
  12622. e.preventDefault();
  12623. }
  12624. }
  12625. };
  12626. element.addEventListener("mousemove", this._onMouseMove, false);
  12627. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12628. element.addEventListener("MSGestureChange", this._onGesture, false);
  12629. BABYLON.Tools.RegisterTopRootEvents([
  12630. { name: "keydown", handler: this._onKeyDown },
  12631. { name: "keyup", handler: this._onKeyUp },
  12632. { name: "blur", handler: this._onLostFocus }
  12633. ]);
  12634. };
  12635. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12636. if (element && this._observer) {
  12637. this.camera.getScene().onPointerObservable.remove(this._observer);
  12638. this._observer = null;
  12639. element.removeEventListener("contextmenu", this._onContextMenu);
  12640. element.removeEventListener("mousemove", this._onMouseMove);
  12641. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12642. element.removeEventListener("MSGestureChange", this._onGesture);
  12643. this._isRightClick = false;
  12644. this._isCtrlPushed = false;
  12645. this.pinchInwards = true;
  12646. this._onKeyDown = null;
  12647. this._onKeyUp = null;
  12648. this._onMouseMove = null;
  12649. this._onGestureStart = null;
  12650. this._onGesture = null;
  12651. this._MSGestureHandler = null;
  12652. this._onLostFocus = null;
  12653. this._onContextMenu = null;
  12654. }
  12655. BABYLON.Tools.UnregisterTopRootEvents([
  12656. { name: "keydown", handler: this._onKeyDown },
  12657. { name: "keyup", handler: this._onKeyUp },
  12658. { name: "blur", handler: this._onLostFocus }
  12659. ]);
  12660. };
  12661. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12662. return "ArcRotateCameraPointersInput";
  12663. };
  12664. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12665. return "pointers";
  12666. };
  12667. __decorate([
  12668. BABYLON.serialize()
  12669. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12670. __decorate([
  12671. BABYLON.serialize()
  12672. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12673. __decorate([
  12674. BABYLON.serialize()
  12675. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12676. __decorate([
  12677. BABYLON.serialize()
  12678. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12679. return ArcRotateCameraPointersInput;
  12680. })();
  12681. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12682. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12683. })(BABYLON || (BABYLON = {}));
  12684. var BABYLON;
  12685. (function (BABYLON) {
  12686. var ArcRotateCameraGamepadInput = (function () {
  12687. function ArcRotateCameraGamepadInput() {
  12688. this.gamepadRotationSensibility = 80;
  12689. this.gamepadMoveSensibility = 40;
  12690. }
  12691. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12692. var _this = this;
  12693. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12694. };
  12695. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12696. if (this._gamepads) {
  12697. this._gamepads.dispose();
  12698. }
  12699. this.gamepad = null;
  12700. };
  12701. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12702. if (this.gamepad) {
  12703. var camera = this.camera;
  12704. var RSValues = this.gamepad.rightStick;
  12705. if (RSValues.x != 0) {
  12706. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12707. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12708. camera.inertialAlphaOffset += normalizedRX;
  12709. }
  12710. }
  12711. if (RSValues.y != 0) {
  12712. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12713. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12714. camera.inertialBetaOffset += normalizedRY;
  12715. }
  12716. }
  12717. var LSValues = this.gamepad.leftStick;
  12718. if (LSValues.y != 0) {
  12719. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12720. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12721. this.camera.inertialRadiusOffset -= normalizedLY;
  12722. }
  12723. }
  12724. }
  12725. };
  12726. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12727. // Only the first gamepad can control the camera
  12728. if (gamepad.index === 0) {
  12729. this.gamepad = gamepad;
  12730. }
  12731. };
  12732. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12733. return "ArcRotateCameraGamepadInput";
  12734. };
  12735. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12736. return "gamepad";
  12737. };
  12738. __decorate([
  12739. BABYLON.serialize()
  12740. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12741. __decorate([
  12742. BABYLON.serialize()
  12743. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12744. return ArcRotateCameraGamepadInput;
  12745. })();
  12746. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12747. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12748. })(BABYLON || (BABYLON = {}));
  12749. var BABYLON;
  12750. (function (BABYLON) {
  12751. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12752. function ArcRotateCameraVRDeviceOrientationInput() {
  12753. this.alphaCorrection = 1;
  12754. this.betaCorrection = 1;
  12755. this.gammaCorrection = 1;
  12756. this._alpha = 0;
  12757. this._beta = 0;
  12758. this._gamma = 0;
  12759. this._dirty = false;
  12760. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12761. }
  12762. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12763. this.camera.attachControl(element, noPreventDefault);
  12764. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12765. };
  12766. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12767. var camera = this.camera;
  12768. this._alpha = +evt.alpha | 0;
  12769. this._beta = +evt.beta | 0;
  12770. this._gamma = +evt.gamma | 0;
  12771. this._dirty = true;
  12772. };
  12773. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12774. if (this._dirty) {
  12775. this._dirty = false;
  12776. if (this._gamma < 0) {
  12777. this._gamma = 180 + this._gamma;
  12778. }
  12779. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12780. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12781. }
  12782. };
  12783. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12784. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12785. };
  12786. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12787. return "ArcRotateCameraVRDeviceOrientationInput";
  12788. };
  12789. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12790. return "VRDeviceOrientation";
  12791. };
  12792. return ArcRotateCameraVRDeviceOrientationInput;
  12793. })();
  12794. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12795. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12796. })(BABYLON || (BABYLON = {}));
  12797. var BABYLON;
  12798. (function (BABYLON) {
  12799. var TargetCamera = (function (_super) {
  12800. __extends(TargetCamera, _super);
  12801. function TargetCamera(name, position, scene) {
  12802. _super.call(this, name, position, scene);
  12803. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12804. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12805. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12806. this.speed = 2.0;
  12807. this.noRotationConstraint = false;
  12808. this.lockedTarget = null;
  12809. this._currentTarget = BABYLON.Vector3.Zero();
  12810. this._viewMatrix = BABYLON.Matrix.Zero();
  12811. this._camMatrix = BABYLON.Matrix.Zero();
  12812. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12813. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12814. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12815. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  12816. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12817. this._lookAtTemp = BABYLON.Matrix.Zero();
  12818. this._tempMatrix = BABYLON.Matrix.Zero();
  12819. }
  12820. TargetCamera.prototype.getFrontPosition = function (distance) {
  12821. var direction = this.getTarget().subtract(this.position);
  12822. direction.normalize();
  12823. direction.scaleInPlace(distance);
  12824. return this.globalPosition.add(direction);
  12825. };
  12826. TargetCamera.prototype._getLockedTargetPosition = function () {
  12827. if (!this.lockedTarget) {
  12828. return null;
  12829. }
  12830. return this.lockedTarget.position || this.lockedTarget;
  12831. };
  12832. // Cache
  12833. TargetCamera.prototype._initCache = function () {
  12834. _super.prototype._initCache.call(this);
  12835. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12836. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12837. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12838. };
  12839. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12840. if (!ignoreParentClass) {
  12841. _super.prototype._updateCache.call(this);
  12842. }
  12843. var lockedTargetPosition = this._getLockedTargetPosition();
  12844. if (!lockedTargetPosition) {
  12845. this._cache.lockedTarget = null;
  12846. }
  12847. else {
  12848. if (!this._cache.lockedTarget) {
  12849. this._cache.lockedTarget = lockedTargetPosition.clone();
  12850. }
  12851. else {
  12852. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12853. }
  12854. }
  12855. this._cache.rotation.copyFrom(this.rotation);
  12856. if (this.rotationQuaternion)
  12857. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12858. };
  12859. // Synchronized
  12860. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12861. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12862. return false;
  12863. }
  12864. var lockedTargetPosition = this._getLockedTargetPosition();
  12865. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12866. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  12867. };
  12868. // Methods
  12869. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12870. var engine = this.getEngine();
  12871. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12872. };
  12873. // Target
  12874. TargetCamera.prototype.setTarget = function (target) {
  12875. this.upVector.normalize();
  12876. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  12877. this._camMatrix.invert();
  12878. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12879. var vDir = target.subtract(this.position);
  12880. if (vDir.x >= 0.0) {
  12881. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12882. }
  12883. else {
  12884. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12885. }
  12886. this.rotation.z = 0;
  12887. if (isNaN(this.rotation.x)) {
  12888. this.rotation.x = 0;
  12889. }
  12890. if (isNaN(this.rotation.y)) {
  12891. this.rotation.y = 0;
  12892. }
  12893. if (isNaN(this.rotation.z)) {
  12894. this.rotation.z = 0;
  12895. }
  12896. if (this.rotationQuaternion) {
  12897. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  12898. }
  12899. };
  12900. TargetCamera.prototype.getTarget = function () {
  12901. return this._currentTarget;
  12902. };
  12903. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12904. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12905. };
  12906. TargetCamera.prototype._updatePosition = function () {
  12907. this.position.addInPlace(this.cameraDirection);
  12908. };
  12909. TargetCamera.prototype._checkInputs = function () {
  12910. var needToMove = this._decideIfNeedsToMove();
  12911. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12912. // Move
  12913. if (needToMove) {
  12914. this._updatePosition();
  12915. }
  12916. // Rotate
  12917. if (needToRotate) {
  12918. this.rotation.x += this.cameraRotation.x;
  12919. this.rotation.y += this.cameraRotation.y;
  12920. if (!this.noRotationConstraint) {
  12921. var limit = (Math.PI / 2) * 0.95;
  12922. if (this.rotation.x > limit)
  12923. this.rotation.x = limit;
  12924. if (this.rotation.x < -limit)
  12925. this.rotation.x = -limit;
  12926. }
  12927. }
  12928. // Inertia
  12929. if (needToMove) {
  12930. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12931. this.cameraDirection.x = 0;
  12932. }
  12933. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12934. this.cameraDirection.y = 0;
  12935. }
  12936. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12937. this.cameraDirection.z = 0;
  12938. }
  12939. this.cameraDirection.scaleInPlace(this.inertia);
  12940. }
  12941. if (needToRotate) {
  12942. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12943. this.cameraRotation.x = 0;
  12944. }
  12945. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12946. this.cameraRotation.y = 0;
  12947. }
  12948. this.cameraRotation.scaleInPlace(this.inertia);
  12949. }
  12950. _super.prototype._checkInputs.call(this);
  12951. };
  12952. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  12953. if (this.rotationQuaternion) {
  12954. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  12955. //update the up vector!
  12956. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  12957. }
  12958. else {
  12959. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12960. }
  12961. };
  12962. TargetCamera.prototype._getViewMatrix = function () {
  12963. if (!this.lockedTarget) {
  12964. // Compute
  12965. this._updateCameraRotationMatrix();
  12966. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12967. // Computing target and final matrix
  12968. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12969. }
  12970. else {
  12971. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12972. }
  12973. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12974. return this._viewMatrix;
  12975. };
  12976. TargetCamera.prototype._getVRViewMatrix = function () {
  12977. this._updateCameraRotationMatrix();
  12978. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12979. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12980. // Computing target and final matrix
  12981. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12982. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12983. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12984. return this._viewMatrix;
  12985. };
  12986. /**
  12987. * @override
  12988. * Override Camera.createRigCamera
  12989. */
  12990. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12991. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12992. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12993. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12994. if (!this.rotationQuaternion) {
  12995. this.rotationQuaternion = new BABYLON.Quaternion();
  12996. }
  12997. rigCamera._cameraRigParams = {};
  12998. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12999. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  13000. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13001. }
  13002. return rigCamera;
  13003. }
  13004. return null;
  13005. };
  13006. /**
  13007. * @override
  13008. * Override Camera._updateRigCameras
  13009. */
  13010. TargetCamera.prototype._updateRigCameras = function () {
  13011. var camLeft = this._rigCameras[0];
  13012. var camRight = this._rigCameras[1];
  13013. switch (this.cameraRigMode) {
  13014. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13015. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13016. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13017. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13018. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13019. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13020. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13021. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13022. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13023. camLeft.setTarget(this.getTarget());
  13024. camRight.setTarget(this.getTarget());
  13025. break;
  13026. case BABYLON.Camera.RIG_MODE_VR:
  13027. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13028. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13029. camLeft.position.copyFrom(this.position);
  13030. camRight.position.copyFrom(this.position);
  13031. break;
  13032. }
  13033. _super.prototype._updateRigCameras.call(this);
  13034. };
  13035. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13036. if (!this._rigCamTransformMatrix) {
  13037. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13038. }
  13039. var target = this.getTarget();
  13040. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13041. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13042. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13043. };
  13044. TargetCamera.prototype.getTypeName = function () {
  13045. return "TargetCamera";
  13046. };
  13047. __decorate([
  13048. BABYLON.serializeAsVector3()
  13049. ], TargetCamera.prototype, "rotation", void 0);
  13050. __decorate([
  13051. BABYLON.serialize()
  13052. ], TargetCamera.prototype, "speed", void 0);
  13053. __decorate([
  13054. BABYLON.serializeAsMeshReference("lockedTargetId")
  13055. ], TargetCamera.prototype, "lockedTarget", void 0);
  13056. return TargetCamera;
  13057. })(BABYLON.Camera);
  13058. BABYLON.TargetCamera = TargetCamera;
  13059. })(BABYLON || (BABYLON = {}));
  13060. var BABYLON;
  13061. (function (BABYLON) {
  13062. var FreeCamera = (function (_super) {
  13063. __extends(FreeCamera, _super);
  13064. function FreeCamera(name, position, scene) {
  13065. var _this = this;
  13066. _super.call(this, name, position, scene);
  13067. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13068. this.checkCollisions = false;
  13069. this.applyGravity = false;
  13070. this._collider = new BABYLON.Collider();
  13071. this._needMoveForGravity = false;
  13072. this._oldPosition = BABYLON.Vector3.Zero();
  13073. this._diffPosition = BABYLON.Vector3.Zero();
  13074. this._newPosition = BABYLON.Vector3.Zero();
  13075. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13076. if (collidedMesh === void 0) { collidedMesh = null; }
  13077. //TODO move this to the collision coordinator!
  13078. if (_this.getScene().workerCollisions)
  13079. newPosition.multiplyInPlace(_this._collider.radius);
  13080. var updatePosition = function (newPos) {
  13081. _this._newPosition.copyFrom(newPos);
  13082. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13083. var oldPosition = _this.position.clone();
  13084. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13085. _this.position.addInPlace(_this._diffPosition);
  13086. if (_this.onCollide && collidedMesh) {
  13087. _this.onCollide(collidedMesh);
  13088. }
  13089. }
  13090. };
  13091. updatePosition(newPosition);
  13092. };
  13093. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13094. this.inputs.addKeyboard().addMouse();
  13095. }
  13096. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13097. //-- begin properties for backward compatibility for inputs
  13098. get: function () {
  13099. var mouse = this.inputs.attached["mouse"];
  13100. if (mouse)
  13101. return mouse.angularSensibility;
  13102. },
  13103. set: function (value) {
  13104. var mouse = this.inputs.attached["mouse"];
  13105. if (mouse)
  13106. mouse.angularSensibility = value;
  13107. },
  13108. enumerable: true,
  13109. configurable: true
  13110. });
  13111. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13112. get: function () {
  13113. var keyboard = this.inputs.attached["keyboard"];
  13114. if (keyboard)
  13115. return keyboard.keysUp;
  13116. },
  13117. set: function (value) {
  13118. var keyboard = this.inputs.attached["keyboard"];
  13119. if (keyboard)
  13120. keyboard.keysUp = value;
  13121. },
  13122. enumerable: true,
  13123. configurable: true
  13124. });
  13125. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13126. get: function () {
  13127. var keyboard = this.inputs.attached["keyboard"];
  13128. if (keyboard)
  13129. return keyboard.keysDown;
  13130. },
  13131. set: function (value) {
  13132. var keyboard = this.inputs.attached["keyboard"];
  13133. if (keyboard)
  13134. keyboard.keysDown = value;
  13135. },
  13136. enumerable: true,
  13137. configurable: true
  13138. });
  13139. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13140. get: function () {
  13141. var keyboard = this.inputs.attached["keyboard"];
  13142. if (keyboard)
  13143. return keyboard.keysLeft;
  13144. },
  13145. set: function (value) {
  13146. var keyboard = this.inputs.attached["keyboard"];
  13147. if (keyboard)
  13148. keyboard.keysLeft = value;
  13149. },
  13150. enumerable: true,
  13151. configurable: true
  13152. });
  13153. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13154. get: function () {
  13155. var keyboard = this.inputs.attached["keyboard"];
  13156. if (keyboard)
  13157. return keyboard.keysRight;
  13158. },
  13159. set: function (value) {
  13160. var keyboard = this.inputs.attached["keyboard"];
  13161. if (keyboard)
  13162. keyboard.keysRight = value;
  13163. },
  13164. enumerable: true,
  13165. configurable: true
  13166. });
  13167. // Controls
  13168. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13169. this.inputs.attachElement(element, noPreventDefault);
  13170. };
  13171. FreeCamera.prototype.detachControl = function (element) {
  13172. this.inputs.detachElement(element);
  13173. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13174. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13175. };
  13176. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13177. var globalPosition;
  13178. if (this.parent) {
  13179. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13180. }
  13181. else {
  13182. globalPosition = this.position;
  13183. }
  13184. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13185. this._collider.radius = this.ellipsoid;
  13186. //no need for clone, as long as gravity is not on.
  13187. var actualVelocity = velocity;
  13188. //add gravity to the velocity to prevent the dual-collision checking
  13189. if (this.applyGravity) {
  13190. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13191. actualVelocity = velocity.add(this.getScene().gravity);
  13192. }
  13193. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13194. };
  13195. FreeCamera.prototype._checkInputs = function () {
  13196. if (!this._localDirection) {
  13197. this._localDirection = BABYLON.Vector3.Zero();
  13198. this._transformedDirection = BABYLON.Vector3.Zero();
  13199. }
  13200. this.inputs.checkInputs();
  13201. _super.prototype._checkInputs.call(this);
  13202. };
  13203. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13204. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13205. };
  13206. FreeCamera.prototype._updatePosition = function () {
  13207. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13208. this._collideWithWorld(this.cameraDirection);
  13209. }
  13210. else {
  13211. this.position.addInPlace(this.cameraDirection);
  13212. }
  13213. };
  13214. FreeCamera.prototype.dispose = function () {
  13215. this.inputs.clear();
  13216. _super.prototype.dispose.call(this);
  13217. };
  13218. FreeCamera.prototype.getTypeName = function () {
  13219. return "FreeCamera";
  13220. };
  13221. __decorate([
  13222. BABYLON.serializeAsVector3()
  13223. ], FreeCamera.prototype, "ellipsoid", void 0);
  13224. __decorate([
  13225. BABYLON.serialize()
  13226. ], FreeCamera.prototype, "checkCollisions", void 0);
  13227. __decorate([
  13228. BABYLON.serialize()
  13229. ], FreeCamera.prototype, "applyGravity", void 0);
  13230. return FreeCamera;
  13231. })(BABYLON.TargetCamera);
  13232. BABYLON.FreeCamera = FreeCamera;
  13233. })(BABYLON || (BABYLON = {}));
  13234. var BABYLON;
  13235. (function (BABYLON) {
  13236. var FreeCameraInputsManager = (function (_super) {
  13237. __extends(FreeCameraInputsManager, _super);
  13238. function FreeCameraInputsManager(camera) {
  13239. _super.call(this, camera);
  13240. }
  13241. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13242. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13243. return this;
  13244. };
  13245. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13246. if (touchEnabled === void 0) { touchEnabled = true; }
  13247. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13248. return this;
  13249. };
  13250. FreeCameraInputsManager.prototype.addGamepad = function () {
  13251. this.add(new BABYLON.FreeCameraGamepadInput());
  13252. return this;
  13253. };
  13254. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13255. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13256. return this;
  13257. };
  13258. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13259. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13260. return this;
  13261. };
  13262. FreeCameraInputsManager.prototype.addTouch = function () {
  13263. this.add(new BABYLON.FreeCameraTouchInput());
  13264. return this;
  13265. };
  13266. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13267. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13268. return this;
  13269. };
  13270. return FreeCameraInputsManager;
  13271. })(BABYLON.CameraInputsManager);
  13272. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13273. })(BABYLON || (BABYLON = {}));
  13274. var BABYLON;
  13275. (function (BABYLON) {
  13276. var FollowCamera = (function (_super) {
  13277. __extends(FollowCamera, _super);
  13278. function FollowCamera(name, position, scene, target) {
  13279. _super.call(this, name, position, scene);
  13280. this.radius = 12;
  13281. this.rotationOffset = 0;
  13282. this.heightOffset = 4;
  13283. this.cameraAcceleration = 0.05;
  13284. this.maxCameraSpeed = 20;
  13285. this.target = target;
  13286. }
  13287. FollowCamera.prototype.getRadians = function (degrees) {
  13288. return degrees * Math.PI / 180;
  13289. };
  13290. FollowCamera.prototype.follow = function (cameraTarget) {
  13291. if (!cameraTarget)
  13292. return;
  13293. var yRotation;
  13294. if (cameraTarget.rotationQuaternion) {
  13295. var rotMatrix = new BABYLON.Matrix();
  13296. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13297. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13298. }
  13299. else {
  13300. yRotation = cameraTarget.rotation.y;
  13301. }
  13302. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13303. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13304. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13305. var dx = targetX - this.position.x;
  13306. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13307. var dz = (targetZ) - this.position.z;
  13308. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13309. var vy = dy * this.cameraAcceleration;
  13310. var vz = dz * this.cameraAcceleration * 2;
  13311. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13312. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13313. }
  13314. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13315. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13316. }
  13317. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13318. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13319. }
  13320. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13321. this.setTarget(cameraTarget.position);
  13322. };
  13323. FollowCamera.prototype._checkInputs = function () {
  13324. _super.prototype._checkInputs.call(this);
  13325. this.follow(this.target);
  13326. };
  13327. FollowCamera.prototype.getTypeName = function () {
  13328. return "FollowCamera";
  13329. };
  13330. __decorate([
  13331. BABYLON.serialize()
  13332. ], FollowCamera.prototype, "radius", void 0);
  13333. __decorate([
  13334. BABYLON.serialize()
  13335. ], FollowCamera.prototype, "rotationOffset", void 0);
  13336. __decorate([
  13337. BABYLON.serialize()
  13338. ], FollowCamera.prototype, "heightOffset", void 0);
  13339. __decorate([
  13340. BABYLON.serialize()
  13341. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13342. __decorate([
  13343. BABYLON.serialize()
  13344. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13345. __decorate([
  13346. BABYLON.serializeAsMeshReference("lockedTargetId")
  13347. ], FollowCamera.prototype, "target", void 0);
  13348. return FollowCamera;
  13349. })(BABYLON.TargetCamera);
  13350. BABYLON.FollowCamera = FollowCamera;
  13351. var ArcFollowCamera = (function (_super) {
  13352. __extends(ArcFollowCamera, _super);
  13353. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13354. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13355. this.alpha = alpha;
  13356. this.beta = beta;
  13357. this.radius = radius;
  13358. this.target = target;
  13359. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13360. this.follow();
  13361. }
  13362. ArcFollowCamera.prototype.follow = function () {
  13363. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13364. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13365. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13366. this.position = this.target.position.add(this._cartesianCoordinates);
  13367. this.setTarget(this.target.position);
  13368. };
  13369. ArcFollowCamera.prototype._checkInputs = function () {
  13370. _super.prototype._checkInputs.call(this);
  13371. this.follow();
  13372. };
  13373. ArcFollowCamera.prototype.getTypeName = function () {
  13374. return "ArcFollowCamera";
  13375. };
  13376. return ArcFollowCamera;
  13377. })(BABYLON.TargetCamera);
  13378. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13379. })(BABYLON || (BABYLON = {}));
  13380. var BABYLON;
  13381. (function (BABYLON) {
  13382. // We're mainly based on the logic defined into the FreeCamera code
  13383. var TouchCamera = (function (_super) {
  13384. __extends(TouchCamera, _super);
  13385. //-- end properties for backward compatibility for inputs
  13386. function TouchCamera(name, position, scene) {
  13387. _super.call(this, name, position, scene);
  13388. this.inputs.addTouch();
  13389. this._setupInputs();
  13390. }
  13391. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13392. //-- Begin properties for backward compatibility for inputs
  13393. get: function () {
  13394. var touch = this.inputs.attached["touch"];
  13395. if (touch)
  13396. return touch.touchAngularSensibility;
  13397. },
  13398. set: function (value) {
  13399. var touch = this.inputs.attached["touch"];
  13400. if (touch)
  13401. touch.touchAngularSensibility = value;
  13402. },
  13403. enumerable: true,
  13404. configurable: true
  13405. });
  13406. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13407. get: function () {
  13408. var touch = this.inputs.attached["touch"];
  13409. if (touch)
  13410. return touch.touchMoveSensibility;
  13411. },
  13412. set: function (value) {
  13413. var touch = this.inputs.attached["touch"];
  13414. if (touch)
  13415. touch.touchMoveSensibility = value;
  13416. },
  13417. enumerable: true,
  13418. configurable: true
  13419. });
  13420. TouchCamera.prototype.getTypeName = function () {
  13421. return "TouchCamera";
  13422. };
  13423. TouchCamera.prototype._setupInputs = function () {
  13424. var mouse = this.inputs.attached["mouse"];
  13425. if (mouse) {
  13426. mouse.touchEnabled = false;
  13427. }
  13428. };
  13429. return TouchCamera;
  13430. })(BABYLON.FreeCamera);
  13431. BABYLON.TouchCamera = TouchCamera;
  13432. })(BABYLON || (BABYLON = {}));
  13433. var BABYLON;
  13434. (function (BABYLON) {
  13435. var ArcRotateCamera = (function (_super) {
  13436. __extends(ArcRotateCamera, _super);
  13437. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13438. var _this = this;
  13439. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13440. this.inertialAlphaOffset = 0;
  13441. this.inertialBetaOffset = 0;
  13442. this.inertialRadiusOffset = 0;
  13443. this.lowerAlphaLimit = null;
  13444. this.upperAlphaLimit = null;
  13445. this.lowerBetaLimit = 0.01;
  13446. this.upperBetaLimit = Math.PI;
  13447. this.lowerRadiusLimit = null;
  13448. this.upperRadiusLimit = null;
  13449. this.inertialPanningX = 0;
  13450. this.inertialPanningY = 0;
  13451. //-- end properties for backward compatibility for inputs
  13452. this.zoomOnFactor = 1;
  13453. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13454. this.allowUpsideDown = true;
  13455. this._viewMatrix = new BABYLON.Matrix();
  13456. // Panning
  13457. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13458. this.checkCollisions = false;
  13459. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13460. this._collider = new BABYLON.Collider();
  13461. this._previousPosition = BABYLON.Vector3.Zero();
  13462. this._collisionVelocity = BABYLON.Vector3.Zero();
  13463. this._newPosition = BABYLON.Vector3.Zero();
  13464. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13465. if (collidedMesh === void 0) { collidedMesh = null; }
  13466. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13467. newPosition.multiplyInPlace(_this._collider.radius);
  13468. }
  13469. if (!collidedMesh) {
  13470. _this._previousPosition.copyFrom(_this.position);
  13471. }
  13472. else {
  13473. _this.setPosition(newPosition);
  13474. if (_this.onCollide) {
  13475. _this.onCollide(collidedMesh);
  13476. }
  13477. }
  13478. // Recompute because of constraints
  13479. var cosa = Math.cos(_this.alpha);
  13480. var sina = Math.sin(_this.alpha);
  13481. var cosb = Math.cos(_this.beta);
  13482. var sinb = Math.sin(_this.beta);
  13483. if (sinb === 0) {
  13484. sinb = 0.0001;
  13485. }
  13486. var target = _this._getTargetPosition();
  13487. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13488. _this.position.copyFrom(_this._newPosition);
  13489. var up = _this.upVector;
  13490. if (_this.allowUpsideDown && _this.beta < 0) {
  13491. up = up.clone();
  13492. up = up.negate();
  13493. }
  13494. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13495. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13496. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13497. _this._collisionTriggered = false;
  13498. };
  13499. if (!target) {
  13500. this.target = BABYLON.Vector3.Zero();
  13501. }
  13502. else {
  13503. this.target = target;
  13504. }
  13505. this.alpha = alpha;
  13506. this.beta = beta;
  13507. this.radius = radius;
  13508. this.getViewMatrix();
  13509. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13510. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13511. }
  13512. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13513. //-- begin properties for backward compatibility for inputs
  13514. get: function () {
  13515. var pointers = this.inputs.attached["pointers"];
  13516. if (pointers)
  13517. return pointers.angularSensibilityX;
  13518. },
  13519. set: function (value) {
  13520. var pointers = this.inputs.attached["pointers"];
  13521. if (pointers) {
  13522. pointers.angularSensibilityX = value;
  13523. }
  13524. },
  13525. enumerable: true,
  13526. configurable: true
  13527. });
  13528. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13529. get: function () {
  13530. var pointers = this.inputs.attached["pointers"];
  13531. if (pointers)
  13532. return pointers.angularSensibilityY;
  13533. },
  13534. set: function (value) {
  13535. var pointers = this.inputs.attached["pointers"];
  13536. if (pointers) {
  13537. pointers.angularSensibilityY = value;
  13538. }
  13539. },
  13540. enumerable: true,
  13541. configurable: true
  13542. });
  13543. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13544. get: function () {
  13545. var pointers = this.inputs.attached["pointers"];
  13546. if (pointers)
  13547. return pointers.pinchPrecision;
  13548. },
  13549. set: function (value) {
  13550. var pointers = this.inputs.attached["pointers"];
  13551. if (pointers) {
  13552. pointers.pinchPrecision = value;
  13553. }
  13554. },
  13555. enumerable: true,
  13556. configurable: true
  13557. });
  13558. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13559. get: function () {
  13560. var pointers = this.inputs.attached["pointers"];
  13561. if (pointers)
  13562. return pointers.panningSensibility;
  13563. },
  13564. set: function (value) {
  13565. var pointers = this.inputs.attached["pointers"];
  13566. if (pointers) {
  13567. pointers.panningSensibility = value;
  13568. }
  13569. },
  13570. enumerable: true,
  13571. configurable: true
  13572. });
  13573. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13574. get: function () {
  13575. var keyboard = this.inputs.attached["keyboard"];
  13576. if (keyboard)
  13577. return keyboard.keysUp;
  13578. },
  13579. set: function (value) {
  13580. var keyboard = this.inputs.attached["keyboard"];
  13581. if (keyboard)
  13582. keyboard.keysUp = value;
  13583. },
  13584. enumerable: true,
  13585. configurable: true
  13586. });
  13587. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13588. get: function () {
  13589. var keyboard = this.inputs.attached["keyboard"];
  13590. if (keyboard)
  13591. return keyboard.keysDown;
  13592. },
  13593. set: function (value) {
  13594. var keyboard = this.inputs.attached["keyboard"];
  13595. if (keyboard)
  13596. keyboard.keysDown = value;
  13597. },
  13598. enumerable: true,
  13599. configurable: true
  13600. });
  13601. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13602. get: function () {
  13603. var keyboard = this.inputs.attached["keyboard"];
  13604. if (keyboard)
  13605. return keyboard.keysLeft;
  13606. },
  13607. set: function (value) {
  13608. var keyboard = this.inputs.attached["keyboard"];
  13609. if (keyboard)
  13610. keyboard.keysLeft = value;
  13611. },
  13612. enumerable: true,
  13613. configurable: true
  13614. });
  13615. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13616. get: function () {
  13617. var keyboard = this.inputs.attached["keyboard"];
  13618. if (keyboard)
  13619. return keyboard.keysRight;
  13620. },
  13621. set: function (value) {
  13622. var keyboard = this.inputs.attached["keyboard"];
  13623. if (keyboard)
  13624. keyboard.keysRight = value;
  13625. },
  13626. enumerable: true,
  13627. configurable: true
  13628. });
  13629. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13630. get: function () {
  13631. var mousewheel = this.inputs.attached["mousewheel"];
  13632. if (mousewheel)
  13633. return mousewheel.wheelPrecision;
  13634. },
  13635. set: function (value) {
  13636. var mousewheel = this.inputs.attached["mousewheel"];
  13637. if (mousewheel)
  13638. mousewheel.wheelPrecision = value;
  13639. },
  13640. enumerable: true,
  13641. configurable: true
  13642. });
  13643. // Cache
  13644. ArcRotateCamera.prototype._initCache = function () {
  13645. _super.prototype._initCache.call(this);
  13646. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13647. this._cache.alpha = undefined;
  13648. this._cache.beta = undefined;
  13649. this._cache.radius = undefined;
  13650. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13651. };
  13652. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13653. if (!ignoreParentClass) {
  13654. _super.prototype._updateCache.call(this);
  13655. }
  13656. this._cache.target.copyFrom(this._getTargetPosition());
  13657. this._cache.alpha = this.alpha;
  13658. this._cache.beta = this.beta;
  13659. this._cache.radius = this.radius;
  13660. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13661. };
  13662. ArcRotateCamera.prototype._getTargetPosition = function () {
  13663. if (this.target.getAbsolutePosition) {
  13664. return this.target.getAbsolutePosition();
  13665. }
  13666. return this.target;
  13667. };
  13668. // Synchronized
  13669. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13670. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13671. return false;
  13672. return this._cache.target.equals(this.target)
  13673. && this._cache.alpha === this.alpha
  13674. && this._cache.beta === this.beta
  13675. && this._cache.radius === this.radius
  13676. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13677. };
  13678. // Methods
  13679. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13680. var _this = this;
  13681. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13682. this._useCtrlForPanning = useCtrlForPanning;
  13683. this.inputs.attachElement(element, noPreventDefault);
  13684. this._reset = function () {
  13685. _this.inertialAlphaOffset = 0;
  13686. _this.inertialBetaOffset = 0;
  13687. _this.inertialRadiusOffset = 0;
  13688. };
  13689. };
  13690. ArcRotateCamera.prototype.detachControl = function (element) {
  13691. this.inputs.detachElement(element);
  13692. if (this._reset) {
  13693. this._reset();
  13694. }
  13695. };
  13696. ArcRotateCamera.prototype._checkInputs = function () {
  13697. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13698. if (this._collisionTriggered) {
  13699. return;
  13700. }
  13701. this.inputs.checkInputs();
  13702. // Inertia
  13703. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13704. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13705. this.beta += this.inertialBetaOffset;
  13706. this.radius -= this.inertialRadiusOffset;
  13707. this.inertialAlphaOffset *= this.inertia;
  13708. this.inertialBetaOffset *= this.inertia;
  13709. this.inertialRadiusOffset *= this.inertia;
  13710. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13711. this.inertialAlphaOffset = 0;
  13712. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13713. this.inertialBetaOffset = 0;
  13714. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13715. this.inertialRadiusOffset = 0;
  13716. }
  13717. // Panning inertia
  13718. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13719. if (!this._localDirection) {
  13720. this._localDirection = BABYLON.Vector3.Zero();
  13721. this._transformedDirection = BABYLON.Vector3.Zero();
  13722. }
  13723. this.inertialPanningX *= this.inertia;
  13724. this.inertialPanningY *= this.inertia;
  13725. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13726. this.inertialPanningX = 0;
  13727. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13728. this.inertialPanningY = 0;
  13729. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13730. this._localDirection.multiplyInPlace(this.panningAxis);
  13731. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13732. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13733. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13734. if (!this.panningAxis.y) {
  13735. this._transformedDirection.y = 0;
  13736. }
  13737. if (!this.target.getAbsolutePosition) {
  13738. this.target.addInPlace(this._transformedDirection);
  13739. }
  13740. }
  13741. // Limits
  13742. this._checkLimits();
  13743. _super.prototype._checkInputs.call(this);
  13744. };
  13745. ArcRotateCamera.prototype._checkLimits = function () {
  13746. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13747. if (this.allowUpsideDown && this.beta > Math.PI) {
  13748. this.beta = this.beta - (2 * Math.PI);
  13749. }
  13750. }
  13751. else {
  13752. if (this.beta < this.lowerBetaLimit) {
  13753. this.beta = this.lowerBetaLimit;
  13754. }
  13755. }
  13756. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13757. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13758. this.beta = this.beta + (2 * Math.PI);
  13759. }
  13760. }
  13761. else {
  13762. if (this.beta > this.upperBetaLimit) {
  13763. this.beta = this.upperBetaLimit;
  13764. }
  13765. }
  13766. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13767. this.alpha = this.lowerAlphaLimit;
  13768. }
  13769. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13770. this.alpha = this.upperAlphaLimit;
  13771. }
  13772. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13773. this.radius = this.lowerRadiusLimit;
  13774. }
  13775. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13776. this.radius = this.upperRadiusLimit;
  13777. }
  13778. };
  13779. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13780. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13781. this.radius = radiusv3.length();
  13782. // Alpha
  13783. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13784. if (radiusv3.z < 0) {
  13785. this.alpha = 2 * Math.PI - this.alpha;
  13786. }
  13787. // Beta
  13788. this.beta = Math.acos(radiusv3.y / this.radius);
  13789. this._checkLimits();
  13790. };
  13791. ArcRotateCamera.prototype.setPosition = function (position) {
  13792. if (this.position.equals(position)) {
  13793. return;
  13794. }
  13795. this.position = position;
  13796. this.rebuildAnglesAndRadius();
  13797. };
  13798. ArcRotateCamera.prototype.setTarget = function (target) {
  13799. if (this._getTargetPosition().equals(target)) {
  13800. return;
  13801. }
  13802. this.target = target;
  13803. this.rebuildAnglesAndRadius();
  13804. };
  13805. ArcRotateCamera.prototype._getViewMatrix = function () {
  13806. // Compute
  13807. var cosa = Math.cos(this.alpha);
  13808. var sina = Math.sin(this.alpha);
  13809. var cosb = Math.cos(this.beta);
  13810. var sinb = Math.sin(this.beta);
  13811. if (sinb === 0) {
  13812. sinb = 0.0001;
  13813. }
  13814. var target = this._getTargetPosition();
  13815. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13816. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13817. this._collider.radius = this.collisionRadius;
  13818. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13819. this._collisionTriggered = true;
  13820. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13821. }
  13822. else {
  13823. this.position.copyFrom(this._newPosition);
  13824. var up = this.upVector;
  13825. if (this.allowUpsideDown && this.beta < 0) {
  13826. up = up.clone();
  13827. up = up.negate();
  13828. }
  13829. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13830. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13831. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13832. }
  13833. return this._viewMatrix;
  13834. };
  13835. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13836. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13837. meshes = meshes || this.getScene().meshes;
  13838. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13839. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13840. this.radius = distance * this.zoomOnFactor;
  13841. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13842. };
  13843. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13844. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13845. var meshesOrMinMaxVector;
  13846. var distance;
  13847. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13848. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13849. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13850. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13851. }
  13852. else {
  13853. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13854. distance = meshesOrMinMaxVectorAndDistance.distance;
  13855. }
  13856. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13857. if (!doNotUpdateMaxZ) {
  13858. this.maxZ = distance * 2;
  13859. }
  13860. };
  13861. /**
  13862. * @override
  13863. * Override Camera.createRigCamera
  13864. */
  13865. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13866. var alphaShift;
  13867. switch (this.cameraRigMode) {
  13868. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13869. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13870. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13871. case BABYLON.Camera.RIG_MODE_VR:
  13872. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13873. break;
  13874. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13875. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  13876. break;
  13877. }
  13878. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13879. rigCam._cameraRigParams = {};
  13880. return rigCam;
  13881. };
  13882. /**
  13883. * @override
  13884. * Override Camera._updateRigCameras
  13885. */
  13886. ArcRotateCamera.prototype._updateRigCameras = function () {
  13887. var camLeft = this._rigCameras[0];
  13888. var camRight = this._rigCameras[1];
  13889. camLeft.beta = camRight.beta = this.beta;
  13890. camLeft.radius = camRight.radius = this.radius;
  13891. switch (this.cameraRigMode) {
  13892. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13895. case BABYLON.Camera.RIG_MODE_VR:
  13896. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13897. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13898. break;
  13899. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13900. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13901. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13902. break;
  13903. }
  13904. _super.prototype._updateRigCameras.call(this);
  13905. };
  13906. ArcRotateCamera.prototype.dispose = function () {
  13907. this.inputs.clear();
  13908. _super.prototype.dispose.call(this);
  13909. };
  13910. ArcRotateCamera.prototype.getTypeName = function () {
  13911. return "ArcRotateCamera";
  13912. };
  13913. __decorate([
  13914. BABYLON.serialize()
  13915. ], ArcRotateCamera.prototype, "alpha", void 0);
  13916. __decorate([
  13917. BABYLON.serialize()
  13918. ], ArcRotateCamera.prototype, "beta", void 0);
  13919. __decorate([
  13920. BABYLON.serialize()
  13921. ], ArcRotateCamera.prototype, "radius", void 0);
  13922. __decorate([
  13923. BABYLON.serializeAsVector3()
  13924. ], ArcRotateCamera.prototype, "target", void 0);
  13925. __decorate([
  13926. BABYLON.serialize()
  13927. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13928. __decorate([
  13929. BABYLON.serialize()
  13930. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13931. __decorate([
  13932. BABYLON.serialize()
  13933. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13934. __decorate([
  13935. BABYLON.serialize()
  13936. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13937. __decorate([
  13938. BABYLON.serialize()
  13939. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13940. __decorate([
  13941. BABYLON.serialize()
  13942. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13943. __decorate([
  13944. BABYLON.serialize()
  13945. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13946. __decorate([
  13947. BABYLON.serialize()
  13948. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13949. __decorate([
  13950. BABYLON.serialize()
  13951. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13952. __decorate([
  13953. BABYLON.serialize()
  13954. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13955. __decorate([
  13956. BABYLON.serialize()
  13957. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13958. __decorate([
  13959. BABYLON.serialize()
  13960. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13961. __decorate([
  13962. BABYLON.serialize()
  13963. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13964. return ArcRotateCamera;
  13965. })(BABYLON.TargetCamera);
  13966. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13967. })(BABYLON || (BABYLON = {}));
  13968. var BABYLON;
  13969. (function (BABYLON) {
  13970. var ArcRotateCameraInputsManager = (function (_super) {
  13971. __extends(ArcRotateCameraInputsManager, _super);
  13972. function ArcRotateCameraInputsManager(camera) {
  13973. _super.call(this, camera);
  13974. }
  13975. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13976. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13977. return this;
  13978. };
  13979. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13980. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13981. return this;
  13982. };
  13983. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13984. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13985. return this;
  13986. };
  13987. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13988. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13989. return this;
  13990. };
  13991. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13992. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13993. return this;
  13994. };
  13995. return ArcRotateCameraInputsManager;
  13996. })(BABYLON.CameraInputsManager);
  13997. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13998. })(BABYLON || (BABYLON = {}));
  13999. var BABYLON;
  14000. (function (BABYLON) {
  14001. var RenderingManager = (function () {
  14002. function RenderingManager(scene) {
  14003. this._renderingGroups = new Array();
  14004. this._scene = scene;
  14005. }
  14006. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14007. if (this._scene._activeParticleSystems.length === 0) {
  14008. return;
  14009. }
  14010. // Particles
  14011. var activeCamera = this._scene.activeCamera;
  14012. var beforeParticlesDate = BABYLON.Tools.Now;
  14013. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14014. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14015. if (particleSystem.renderingGroupId !== index) {
  14016. continue;
  14017. }
  14018. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14019. continue;
  14020. }
  14021. this._clearDepthBuffer();
  14022. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14023. this._scene._activeParticles += particleSystem.render();
  14024. }
  14025. }
  14026. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  14027. };
  14028. RenderingManager.prototype._renderSprites = function (index) {
  14029. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14030. return;
  14031. }
  14032. // Sprites
  14033. var activeCamera = this._scene.activeCamera;
  14034. var beforeSpritessDate = BABYLON.Tools.Now;
  14035. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14036. var spriteManager = this._scene.spriteManagers[id];
  14037. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14038. this._clearDepthBuffer();
  14039. spriteManager.render();
  14040. }
  14041. }
  14042. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  14043. };
  14044. RenderingManager.prototype._clearDepthBuffer = function () {
  14045. if (this._depthBufferAlreadyCleaned) {
  14046. return;
  14047. }
  14048. this._scene.getEngine().clear(0, false, true);
  14049. this._depthBufferAlreadyCleaned = true;
  14050. };
  14051. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14052. if (this._currentRenderSprites) {
  14053. this._renderSprites(this._currentIndex);
  14054. }
  14055. if (this._currentRenderParticles) {
  14056. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14057. }
  14058. };
  14059. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14060. this._currentActiveMeshes = activeMeshes;
  14061. this._currentRenderParticles = renderParticles;
  14062. this._currentRenderSprites = renderSprites;
  14063. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14064. this._depthBufferAlreadyCleaned = index == 0;
  14065. var renderingGroup = this._renderingGroups[index];
  14066. var needToStepBack = false;
  14067. this._currentIndex = index;
  14068. if (renderingGroup) {
  14069. this._clearDepthBuffer();
  14070. if (!renderingGroup.onBeforeTransparentRendering) {
  14071. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14072. }
  14073. if (!renderingGroup.render(customRenderFunction)) {
  14074. this._renderingGroups.splice(index, 1);
  14075. needToStepBack = true;
  14076. this._renderSpritesAndParticles();
  14077. }
  14078. }
  14079. else {
  14080. this._renderSpritesAndParticles();
  14081. }
  14082. if (needToStepBack) {
  14083. index--;
  14084. }
  14085. }
  14086. };
  14087. RenderingManager.prototype.reset = function () {
  14088. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14089. if (renderingGroup) {
  14090. renderingGroup.prepare();
  14091. }
  14092. });
  14093. };
  14094. RenderingManager.prototype.dispatch = function (subMesh) {
  14095. var mesh = subMesh.getMesh();
  14096. var renderingGroupId = mesh.renderingGroupId || 0;
  14097. if (!this._renderingGroups[renderingGroupId]) {
  14098. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14099. }
  14100. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14101. };
  14102. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14103. return RenderingManager;
  14104. })();
  14105. BABYLON.RenderingManager = RenderingManager;
  14106. })(BABYLON || (BABYLON = {}));
  14107. var BABYLON;
  14108. (function (BABYLON) {
  14109. var RenderingGroup = (function () {
  14110. function RenderingGroup(index, scene) {
  14111. this.index = index;
  14112. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14113. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14114. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14115. this._scene = scene;
  14116. }
  14117. RenderingGroup.prototype.render = function (customRenderFunction) {
  14118. if (customRenderFunction) {
  14119. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14120. return true;
  14121. }
  14122. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14123. if (this.onBeforeTransparentRendering) {
  14124. this.onBeforeTransparentRendering();
  14125. }
  14126. return false;
  14127. }
  14128. var engine = this._scene.getEngine();
  14129. // Opaque
  14130. var subIndex;
  14131. var submesh;
  14132. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14133. submesh = this._opaqueSubMeshes.data[subIndex];
  14134. submesh.render(false);
  14135. }
  14136. // Alpha test
  14137. engine.setAlphaTesting(true);
  14138. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14139. submesh = this._alphaTestSubMeshes.data[subIndex];
  14140. submesh.render(false);
  14141. }
  14142. engine.setAlphaTesting(false);
  14143. if (this.onBeforeTransparentRendering) {
  14144. this.onBeforeTransparentRendering();
  14145. }
  14146. // Transparent
  14147. if (this._transparentSubMeshes.length) {
  14148. // Sorting
  14149. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14150. submesh = this._transparentSubMeshes.data[subIndex];
  14151. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14152. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14153. }
  14154. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14155. sortedArray.sort(function (a, b) {
  14156. // Alpha index first
  14157. if (a._alphaIndex > b._alphaIndex) {
  14158. return 1;
  14159. }
  14160. if (a._alphaIndex < b._alphaIndex) {
  14161. return -1;
  14162. }
  14163. // Then distance to camera
  14164. if (a._distanceToCamera < b._distanceToCamera) {
  14165. return 1;
  14166. }
  14167. if (a._distanceToCamera > b._distanceToCamera) {
  14168. return -1;
  14169. }
  14170. return 0;
  14171. });
  14172. // Rendering
  14173. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14174. submesh = sortedArray[subIndex];
  14175. submesh.render(true);
  14176. }
  14177. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14178. }
  14179. return true;
  14180. };
  14181. RenderingGroup.prototype.prepare = function () {
  14182. this._opaqueSubMeshes.reset();
  14183. this._transparentSubMeshes.reset();
  14184. this._alphaTestSubMeshes.reset();
  14185. };
  14186. RenderingGroup.prototype.dispatch = function (subMesh) {
  14187. var material = subMesh.getMaterial();
  14188. var mesh = subMesh.getMesh();
  14189. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14190. this._transparentSubMeshes.push(subMesh);
  14191. }
  14192. else if (material.needAlphaTesting()) {
  14193. this._alphaTestSubMeshes.push(subMesh);
  14194. }
  14195. else {
  14196. this._opaqueSubMeshes.push(subMesh); // Opaque
  14197. }
  14198. };
  14199. return RenderingGroup;
  14200. })();
  14201. BABYLON.RenderingGroup = RenderingGroup;
  14202. })(BABYLON || (BABYLON = {}));
  14203. var BABYLON;
  14204. (function (BABYLON) {
  14205. var PointerEventTypes = (function () {
  14206. function PointerEventTypes() {
  14207. }
  14208. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14209. get: function () {
  14210. return PointerEventTypes._POINTERDOWN;
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14216. get: function () {
  14217. return PointerEventTypes._POINTERUP;
  14218. },
  14219. enumerable: true,
  14220. configurable: true
  14221. });
  14222. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14223. get: function () {
  14224. return PointerEventTypes._POINTERMOVE;
  14225. },
  14226. enumerable: true,
  14227. configurable: true
  14228. });
  14229. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14230. get: function () {
  14231. return PointerEventTypes._POINTERWHEEL;
  14232. },
  14233. enumerable: true,
  14234. configurable: true
  14235. });
  14236. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14237. get: function () {
  14238. return PointerEventTypes._POINTERPICK;
  14239. },
  14240. enumerable: true,
  14241. configurable: true
  14242. });
  14243. PointerEventTypes._POINTERDOWN = 0x01;
  14244. PointerEventTypes._POINTERUP = 0x02;
  14245. PointerEventTypes._POINTERMOVE = 0x04;
  14246. PointerEventTypes._POINTERWHEEL = 0x08;
  14247. PointerEventTypes._POINTERPICK = 0x10;
  14248. return PointerEventTypes;
  14249. })();
  14250. BABYLON.PointerEventTypes = PointerEventTypes;
  14251. /**
  14252. * This class is used to store pointer related info for the onPrePointerObservable event.
  14253. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14254. */
  14255. var PointerInfoPre = (function () {
  14256. function PointerInfoPre(type, event, localX, localY) {
  14257. this.type = type;
  14258. this.event = event;
  14259. this.skipOnPointerObservable = false;
  14260. this.localPosition = new BABYLON.Vector2(localX, localY);
  14261. }
  14262. return PointerInfoPre;
  14263. })();
  14264. BABYLON.PointerInfoPre = PointerInfoPre;
  14265. /**
  14266. * This type contains all the data related to a pointer event in Babylon.js.
  14267. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  14268. */
  14269. var PointerInfo = (function () {
  14270. function PointerInfo(type, event, pickInfo) {
  14271. this.type = type;
  14272. this.event = event;
  14273. this.pickInfo = pickInfo;
  14274. }
  14275. return PointerInfo;
  14276. })();
  14277. BABYLON.PointerInfo = PointerInfo;
  14278. /**
  14279. * Represents a scene to be rendered by the engine.
  14280. * @see http://doc.babylonjs.com/page.php?p=21911
  14281. */
  14282. var Scene = (function () {
  14283. /**
  14284. * @constructor
  14285. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14286. */
  14287. function Scene(engine) {
  14288. // Members
  14289. this.autoClear = true;
  14290. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14291. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14292. this.forceWireframe = false;
  14293. this.forcePointsCloud = false;
  14294. this.forceShowBoundingBoxes = false;
  14295. this.animationsEnabled = true;
  14296. this.constantlyUpdateMeshUnderPointer = false;
  14297. // Events
  14298. /**
  14299. * An event triggered when the scene is disposed.
  14300. * @type {BABYLON.Observable}
  14301. */
  14302. this.onDisposeObservable = new BABYLON.Observable();
  14303. /**
  14304. * An event triggered before rendering the scene
  14305. * @type {BABYLON.Observable}
  14306. */
  14307. this.onBeforeRenderObservable = new BABYLON.Observable();
  14308. /**
  14309. * An event triggered after rendering the scene
  14310. * @type {BABYLON.Observable}
  14311. */
  14312. this.onAfterRenderObservable = new BABYLON.Observable();
  14313. /**
  14314. * An event triggered when the scene is ready
  14315. * @type {BABYLON.Observable}
  14316. */
  14317. this.onReadyObservable = new BABYLON.Observable();
  14318. /**
  14319. * An event triggered before rendering a camera
  14320. * @type {BABYLON.Observable}
  14321. */
  14322. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14323. /**
  14324. * An event triggered after rendering a camera
  14325. * @type {BABYLON.Observable}
  14326. */
  14327. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14328. /**
  14329. * An event triggered when a camera is created
  14330. * @type {BABYLON.Observable}
  14331. */
  14332. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14333. /**
  14334. * An event triggered when a camera is removed
  14335. * @type {BABYLON.Observable}
  14336. */
  14337. this.onCameraRemovedObservable = new BABYLON.Observable();
  14338. /**
  14339. * An event triggered when a light is created
  14340. * @type {BABYLON.Observable}
  14341. */
  14342. this.onNewLightAddedObservable = new BABYLON.Observable();
  14343. /**
  14344. * An event triggered when a light is removed
  14345. * @type {BABYLON.Observable}
  14346. */
  14347. this.onLightRemovedObservable = new BABYLON.Observable();
  14348. /**
  14349. * An event triggered when a geometry is created
  14350. * @type {BABYLON.Observable}
  14351. */
  14352. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14353. /**
  14354. * An event triggered when a geometry is removed
  14355. * @type {BABYLON.Observable}
  14356. */
  14357. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14358. /**
  14359. * An event triggered when a mesh is created
  14360. * @type {BABYLON.Observable}
  14361. */
  14362. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14363. /**
  14364. * An event triggered when a mesh is removed
  14365. * @type {BABYLON.Observable}
  14366. */
  14367. this.onMeshRemovedObservable = new BABYLON.Observable();
  14368. // Animations
  14369. this.animations = [];
  14370. /**
  14371. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  14372. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14373. */
  14374. this.onPrePointerObservable = new BABYLON.Observable();
  14375. /**
  14376. * Observable event triggered each time an input event is received from the rendering canvas
  14377. */
  14378. this.onPointerObservable = new BABYLON.Observable();
  14379. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  14380. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14381. this._startingPointerTime = 0;
  14382. // Fog
  14383. /**
  14384. * is fog enabled on this scene.
  14385. * @type {boolean}
  14386. */
  14387. this.fogEnabled = true;
  14388. this.fogMode = Scene.FOGMODE_NONE;
  14389. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14390. this.fogDensity = 0.1;
  14391. this.fogStart = 0;
  14392. this.fogEnd = 1000.0;
  14393. // Lights
  14394. /**
  14395. * is shadow enabled on this scene.
  14396. * @type {boolean}
  14397. */
  14398. this.shadowsEnabled = true;
  14399. /**
  14400. * is light enabled on this scene.
  14401. * @type {boolean}
  14402. */
  14403. this.lightsEnabled = true;
  14404. /**
  14405. * All of the lights added to this scene.
  14406. * @see BABYLON.Light
  14407. * @type {BABYLON.Light[]}
  14408. */
  14409. this.lights = new Array();
  14410. // Cameras
  14411. /**
  14412. * All of the cameras added to this scene.
  14413. * @see BABYLON.Camera
  14414. * @type {BABYLON.Camera[]}
  14415. */
  14416. this.cameras = new Array();
  14417. this.activeCameras = new Array();
  14418. // Meshes
  14419. /**
  14420. * All of the (abstract) meshes added to this scene.
  14421. * @see BABYLON.AbstractMesh
  14422. * @type {BABYLON.AbstractMesh[]}
  14423. */
  14424. this.meshes = new Array();
  14425. // Geometries
  14426. this._geometries = new Array();
  14427. this.materials = new Array();
  14428. this.multiMaterials = new Array();
  14429. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14430. // Textures
  14431. this.texturesEnabled = true;
  14432. this.textures = new Array();
  14433. // Particles
  14434. this.particlesEnabled = true;
  14435. this.particleSystems = new Array();
  14436. // Sprites
  14437. this.spritesEnabled = true;
  14438. this.spriteManagers = new Array();
  14439. // Layers
  14440. this.layers = new Array();
  14441. // Skeletons
  14442. this.skeletonsEnabled = true;
  14443. this.skeletons = new Array();
  14444. // Lens flares
  14445. this.lensFlaresEnabled = true;
  14446. this.lensFlareSystems = new Array();
  14447. // Collisions
  14448. this.collisionsEnabled = true;
  14449. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14450. // Postprocesses
  14451. this.postProcessesEnabled = true;
  14452. // Customs render targets
  14453. this.renderTargetsEnabled = true;
  14454. this.dumpNextRenderTargets = false;
  14455. this.customRenderTargets = new Array();
  14456. // Imported meshes
  14457. this.importedMeshesFiles = new Array();
  14458. // Probes
  14459. this.probesEnabled = true;
  14460. this.reflectionProbes = new Array();
  14461. this._actionManagers = new Array();
  14462. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14463. // Procedural textures
  14464. this.proceduralTexturesEnabled = true;
  14465. this._proceduralTextures = new Array();
  14466. this.soundTracks = new Array();
  14467. this._audioEnabled = true;
  14468. this._headphone = false;
  14469. this._totalVertices = 0;
  14470. this._activeIndices = 0;
  14471. this._activeParticles = 0;
  14472. this._lastFrameDuration = 0;
  14473. this._evaluateActiveMeshesDuration = 0;
  14474. this._renderTargetsDuration = 0;
  14475. this._particlesDuration = 0;
  14476. this._renderDuration = 0;
  14477. this._spritesDuration = 0;
  14478. this._animationRatio = 0;
  14479. this._renderId = 0;
  14480. this._executeWhenReadyTimeoutId = -1;
  14481. this._intermediateRendering = false;
  14482. this._toBeDisposed = new BABYLON.SmartArray(256);
  14483. this._pendingData = []; //ANY
  14484. this._activeMeshes = new BABYLON.SmartArray(256);
  14485. this._processedMaterials = new BABYLON.SmartArray(256);
  14486. this._renderTargets = new BABYLON.SmartArray(256);
  14487. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14488. this._activeSkeletons = new BABYLON.SmartArray(32);
  14489. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14490. this._activeBones = 0;
  14491. this._activeAnimatables = new Array();
  14492. this._transformMatrix = BABYLON.Matrix.Zero();
  14493. this._edgesRenderers = new BABYLON.SmartArray(16);
  14494. this._uniqueIdCounter = 0;
  14495. this._engine = engine;
  14496. engine.scenes.push(this);
  14497. this._renderingManager = new BABYLON.RenderingManager(this);
  14498. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14499. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14500. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14501. if (BABYLON.OutlineRenderer) {
  14502. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14503. }
  14504. this.attachControl();
  14505. if (BABYLON.SoundTrack) {
  14506. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14507. }
  14508. //simplification queue
  14509. if (BABYLON.SimplificationQueue) {
  14510. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14511. }
  14512. //collision coordinator initialization. For now legacy per default.
  14513. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14514. }
  14515. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14516. get: function () {
  14517. return Scene._FOGMODE_NONE;
  14518. },
  14519. enumerable: true,
  14520. configurable: true
  14521. });
  14522. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14523. get: function () {
  14524. return Scene._FOGMODE_EXP;
  14525. },
  14526. enumerable: true,
  14527. configurable: true
  14528. });
  14529. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14530. get: function () {
  14531. return Scene._FOGMODE_EXP2;
  14532. },
  14533. enumerable: true,
  14534. configurable: true
  14535. });
  14536. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14537. get: function () {
  14538. return Scene._FOGMODE_LINEAR;
  14539. },
  14540. enumerable: true,
  14541. configurable: true
  14542. });
  14543. Object.defineProperty(Scene.prototype, "onDispose", {
  14544. set: function (callback) {
  14545. if (this._onDisposeObserver) {
  14546. this.onDisposeObservable.remove(this._onDisposeObserver);
  14547. }
  14548. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14549. },
  14550. enumerable: true,
  14551. configurable: true
  14552. });
  14553. Object.defineProperty(Scene.prototype, "beforeRender", {
  14554. set: function (callback) {
  14555. if (this._onBeforeRenderObserver) {
  14556. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14557. }
  14558. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14559. },
  14560. enumerable: true,
  14561. configurable: true
  14562. });
  14563. Object.defineProperty(Scene.prototype, "afterRender", {
  14564. set: function (callback) {
  14565. if (this._onAfterRenderObserver) {
  14566. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14567. }
  14568. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14569. },
  14570. enumerable: true,
  14571. configurable: true
  14572. });
  14573. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14574. set: function (callback) {
  14575. if (this._onBeforeCameraRenderObserver) {
  14576. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14577. }
  14578. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14579. },
  14580. enumerable: true,
  14581. configurable: true
  14582. });
  14583. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14584. set: function (callback) {
  14585. if (this._onAfterCameraRenderObserver) {
  14586. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14587. }
  14588. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14589. },
  14590. enumerable: true,
  14591. configurable: true
  14592. });
  14593. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14594. get: function () {
  14595. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14596. },
  14597. enumerable: true,
  14598. configurable: true
  14599. });
  14600. Object.defineProperty(Scene.prototype, "debugLayer", {
  14601. // Properties
  14602. get: function () {
  14603. if (!this._debugLayer) {
  14604. this._debugLayer = new BABYLON.DebugLayer(this);
  14605. }
  14606. return this._debugLayer;
  14607. },
  14608. enumerable: true,
  14609. configurable: true
  14610. });
  14611. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14612. get: function () {
  14613. return this._workerCollisions;
  14614. },
  14615. set: function (enabled) {
  14616. enabled = (enabled && !!Worker);
  14617. this._workerCollisions = enabled;
  14618. if (this.collisionCoordinator) {
  14619. this.collisionCoordinator.destroy();
  14620. }
  14621. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14622. this.collisionCoordinator.init(this);
  14623. },
  14624. enumerable: true,
  14625. configurable: true
  14626. });
  14627. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14628. get: function () {
  14629. return this._selectionOctree;
  14630. },
  14631. enumerable: true,
  14632. configurable: true
  14633. });
  14634. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14635. /**
  14636. * The mesh that is currently under the pointer.
  14637. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14638. */
  14639. get: function () {
  14640. return this._pointerOverMesh;
  14641. },
  14642. enumerable: true,
  14643. configurable: true
  14644. });
  14645. Object.defineProperty(Scene.prototype, "pointerX", {
  14646. /**
  14647. * Current on-screen X position of the pointer
  14648. * @return {number} X position of the pointer
  14649. */
  14650. get: function () {
  14651. return this._pointerX;
  14652. },
  14653. enumerable: true,
  14654. configurable: true
  14655. });
  14656. Object.defineProperty(Scene.prototype, "pointerY", {
  14657. /**
  14658. * Current on-screen Y position of the pointer
  14659. * @return {number} Y position of the pointer
  14660. */
  14661. get: function () {
  14662. return this._pointerY;
  14663. },
  14664. enumerable: true,
  14665. configurable: true
  14666. });
  14667. Scene.prototype.getCachedMaterial = function () {
  14668. return this._cachedMaterial;
  14669. };
  14670. Scene.prototype.getBoundingBoxRenderer = function () {
  14671. return this._boundingBoxRenderer;
  14672. };
  14673. Scene.prototype.getOutlineRenderer = function () {
  14674. return this._outlineRenderer;
  14675. };
  14676. Scene.prototype.getEngine = function () {
  14677. return this._engine;
  14678. };
  14679. Scene.prototype.getTotalVertices = function () {
  14680. return this._totalVertices;
  14681. };
  14682. Scene.prototype.getActiveIndices = function () {
  14683. return this._activeIndices;
  14684. };
  14685. Scene.prototype.getActiveParticles = function () {
  14686. return this._activeParticles;
  14687. };
  14688. Scene.prototype.getActiveBones = function () {
  14689. return this._activeBones;
  14690. };
  14691. // Stats
  14692. Scene.prototype.getLastFrameDuration = function () {
  14693. return this._lastFrameDuration;
  14694. };
  14695. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14696. return this._evaluateActiveMeshesDuration;
  14697. };
  14698. Scene.prototype.getActiveMeshes = function () {
  14699. return this._activeMeshes;
  14700. };
  14701. Scene.prototype.getRenderTargetsDuration = function () {
  14702. return this._renderTargetsDuration;
  14703. };
  14704. Scene.prototype.getRenderDuration = function () {
  14705. return this._renderDuration;
  14706. };
  14707. Scene.prototype.getParticlesDuration = function () {
  14708. return this._particlesDuration;
  14709. };
  14710. Scene.prototype.getSpritesDuration = function () {
  14711. return this._spritesDuration;
  14712. };
  14713. Scene.prototype.getAnimationRatio = function () {
  14714. return this._animationRatio;
  14715. };
  14716. Scene.prototype.getRenderId = function () {
  14717. return this._renderId;
  14718. };
  14719. Scene.prototype.incrementRenderId = function () {
  14720. this._renderId++;
  14721. };
  14722. Scene.prototype._updatePointerPosition = function (evt) {
  14723. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14724. this._pointerX = evt.clientX - canvasRect.left;
  14725. this._pointerY = evt.clientY - canvasRect.top;
  14726. this._unTranslatedPointerX = this._pointerX;
  14727. this._unTranslatedPointerY = this._pointerY;
  14728. if (this.cameraToUseForPointers) {
  14729. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14730. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14731. }
  14732. };
  14733. // Pointers handling
  14734. /**
  14735. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14736. * @param attachUp defines if you want to attach events to pointerup
  14737. * @param attachDown defines if you want to attach events to pointerdown
  14738. * @param attachMove defines if you want to attach events to pointermove
  14739. */
  14740. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14741. var _this = this;
  14742. if (attachUp === void 0) { attachUp = true; }
  14743. if (attachDown === void 0) { attachDown = true; }
  14744. if (attachMove === void 0) { attachMove = true; }
  14745. var spritePredicate = function (sprite) {
  14746. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14747. };
  14748. this._onPointerMove = function (evt) {
  14749. _this._updatePointerPosition(evt);
  14750. // PreObservable support
  14751. if (_this.onPrePointerObservable.hasObservers()) {
  14752. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14753. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  14754. _this.onPrePointerObservable.notifyObservers(pi, type);
  14755. if (pi.skipOnPointerObservable) {
  14756. return;
  14757. }
  14758. }
  14759. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14760. return;
  14761. }
  14762. var canvas = _this._engine.getRenderingCanvas();
  14763. if (!_this.pointerMovePredicate) {
  14764. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14765. }
  14766. // Meshes
  14767. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14768. if (pickResult.hit && pickResult.pickedMesh) {
  14769. _this.setPointerOverSprite(null);
  14770. _this.setPointerOverMesh(pickResult.pickedMesh);
  14771. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14772. canvas.style.cursor = "pointer";
  14773. }
  14774. else {
  14775. canvas.style.cursor = "";
  14776. }
  14777. }
  14778. else {
  14779. _this.setPointerOverMesh(null);
  14780. // Sprites
  14781. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14782. if (pickResult.hit && pickResult.pickedSprite) {
  14783. canvas.style.cursor = "pointer";
  14784. _this.setPointerOverSprite(pickResult.pickedSprite);
  14785. }
  14786. else {
  14787. _this.setPointerOverSprite(null);
  14788. // Restore pointer
  14789. canvas.style.cursor = "";
  14790. }
  14791. }
  14792. if (_this.onPointerMove) {
  14793. _this.onPointerMove(evt, pickResult);
  14794. }
  14795. if (_this.onPointerObservable.hasObservers()) {
  14796. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14797. var pi = new PointerInfo(type, evt, pickResult);
  14798. _this.onPointerObservable.notifyObservers(pi, type);
  14799. }
  14800. };
  14801. this._onPointerDown = function (evt) {
  14802. _this._updatePointerPosition(evt);
  14803. // PreObservable support
  14804. if (_this.onPrePointerObservable.hasObservers()) {
  14805. var type = PointerEventTypes.POINTERDOWN;
  14806. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  14807. _this.onPrePointerObservable.notifyObservers(pi, type);
  14808. if (pi.skipOnPointerObservable) {
  14809. return;
  14810. }
  14811. }
  14812. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14813. return;
  14814. }
  14815. _this._startingPointerPosition.x = _this._pointerX;
  14816. _this._startingPointerPosition.y = _this._pointerY;
  14817. _this._startingPointerTime = new Date().getTime();
  14818. if (!_this.pointerDownPredicate) {
  14819. _this.pointerDownPredicate = function (mesh) {
  14820. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14821. };
  14822. }
  14823. // Meshes
  14824. _this._pickedDownMesh = null;
  14825. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14826. if (pickResult.hit && pickResult.pickedMesh) {
  14827. if (pickResult.pickedMesh.actionManager) {
  14828. _this._pickedDownMesh = pickResult.pickedMesh;
  14829. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14830. switch (evt.button) {
  14831. case 0:
  14832. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14833. break;
  14834. case 1:
  14835. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14836. break;
  14837. case 2:
  14838. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14839. break;
  14840. }
  14841. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14842. }
  14843. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14844. var that = _this;
  14845. window.setTimeout(function () {
  14846. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  14847. if (pickResult.hit && pickResult.pickedMesh) {
  14848. if (pickResult.pickedMesh.actionManager) {
  14849. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  14850. that._startingPointerTime = 0;
  14851. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14852. }
  14853. }
  14854. }
  14855. }, BABYLON.ActionManager.LongPressDelay);
  14856. }
  14857. }
  14858. }
  14859. if (_this.onPointerDown) {
  14860. _this.onPointerDown(evt, pickResult);
  14861. }
  14862. if (_this.onPointerObservable.hasObservers()) {
  14863. var type = PointerEventTypes.POINTERDOWN;
  14864. var pi = new PointerInfo(type, evt, pickResult);
  14865. _this.onPointerObservable.notifyObservers(pi, type);
  14866. }
  14867. // Sprites
  14868. _this._pickedDownSprite = null;
  14869. if (_this.spriteManagers.length > 0) {
  14870. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14871. if (pickResult.hit && pickResult.pickedSprite) {
  14872. if (pickResult.pickedSprite.actionManager) {
  14873. _this._pickedDownSprite = pickResult.pickedSprite;
  14874. switch (evt.button) {
  14875. case 0:
  14876. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14877. break;
  14878. case 1:
  14879. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14880. break;
  14881. case 2:
  14882. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14883. break;
  14884. }
  14885. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14886. }
  14887. }
  14888. }
  14889. };
  14890. this._onPointerUp = function (evt) {
  14891. _this._updatePointerPosition(evt);
  14892. // PreObservable support
  14893. if (_this.onPrePointerObservable.hasObservers()) {
  14894. var type = PointerEventTypes.POINTERUP;
  14895. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  14896. _this.onPrePointerObservable.notifyObservers(pi, type);
  14897. if (pi.skipOnPointerObservable) {
  14898. return;
  14899. }
  14900. }
  14901. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14902. return;
  14903. }
  14904. if (!_this.pointerUpPredicate) {
  14905. _this.pointerUpPredicate = function (mesh) {
  14906. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14907. };
  14908. }
  14909. // Meshes
  14910. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14911. if (pickResult.hit && pickResult.pickedMesh) {
  14912. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14913. if (_this.onPointerPick) {
  14914. _this.onPointerPick(evt, pickResult);
  14915. }
  14916. if (_this.onPointerObservable.hasObservers()) {
  14917. var type = PointerEventTypes.POINTERPICK;
  14918. var pi = new PointerInfo(type, evt, pickResult);
  14919. _this.onPointerObservable.notifyObservers(pi, type);
  14920. }
  14921. }
  14922. if (pickResult.pickedMesh.actionManager) {
  14923. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14924. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14925. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14926. }
  14927. }
  14928. }
  14929. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14930. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14931. }
  14932. if (_this.onPointerUp) {
  14933. _this.onPointerUp(evt, pickResult);
  14934. }
  14935. if (_this.onPointerObservable.hasObservers()) {
  14936. var type = PointerEventTypes.POINTERUP;
  14937. var pi = new PointerInfo(type, evt, pickResult);
  14938. _this.onPointerObservable.notifyObservers(pi, type);
  14939. }
  14940. _this._startingPointerTime = 0;
  14941. // Sprites
  14942. if (_this.spriteManagers.length > 0) {
  14943. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14944. if (pickResult.hit && pickResult.pickedSprite) {
  14945. if (pickResult.pickedSprite.actionManager) {
  14946. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14947. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14948. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14949. }
  14950. }
  14951. }
  14952. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14953. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14954. }
  14955. }
  14956. };
  14957. this._onKeyDown = function (evt) {
  14958. if (_this.actionManager) {
  14959. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14960. }
  14961. };
  14962. this._onKeyUp = function (evt) {
  14963. if (_this.actionManager) {
  14964. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14965. }
  14966. };
  14967. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14968. if (attachMove) {
  14969. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14970. // Wheel
  14971. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14972. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14973. }
  14974. if (attachDown) {
  14975. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14976. }
  14977. if (attachUp) {
  14978. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14979. }
  14980. BABYLON.Tools.RegisterTopRootEvents([
  14981. { name: "keydown", handler: this._onKeyDown },
  14982. { name: "keyup", handler: this._onKeyUp }
  14983. ]);
  14984. };
  14985. Scene.prototype.detachControl = function () {
  14986. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14987. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14988. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14989. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14990. // Wheel
  14991. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14992. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14993. BABYLON.Tools.UnregisterTopRootEvents([
  14994. { name: "keydown", handler: this._onKeyDown },
  14995. { name: "keyup", handler: this._onKeyUp }
  14996. ]);
  14997. };
  14998. // Ready
  14999. Scene.prototype.isReady = function () {
  15000. if (this._pendingData.length > 0) {
  15001. return false;
  15002. }
  15003. var index;
  15004. for (index = 0; index < this._geometries.length; index++) {
  15005. var geometry = this._geometries[index];
  15006. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15007. return false;
  15008. }
  15009. }
  15010. for (index = 0; index < this.meshes.length; index++) {
  15011. var mesh = this.meshes[index];
  15012. if (!mesh.isReady()) {
  15013. return false;
  15014. }
  15015. var mat = mesh.material;
  15016. if (mat) {
  15017. if (!mat.isReady(mesh)) {
  15018. return false;
  15019. }
  15020. }
  15021. }
  15022. return true;
  15023. };
  15024. Scene.prototype.resetCachedMaterial = function () {
  15025. this._cachedMaterial = null;
  15026. };
  15027. Scene.prototype.registerBeforeRender = function (func) {
  15028. this.onBeforeRenderObservable.add(func);
  15029. };
  15030. Scene.prototype.unregisterBeforeRender = function (func) {
  15031. this.onBeforeRenderObservable.removeCallback(func);
  15032. };
  15033. Scene.prototype.registerAfterRender = function (func) {
  15034. this.onAfterRenderObservable.add(func);
  15035. };
  15036. Scene.prototype.unregisterAfterRender = function (func) {
  15037. this.onAfterRenderObservable.removeCallback(func);
  15038. };
  15039. Scene.prototype._addPendingData = function (data) {
  15040. this._pendingData.push(data);
  15041. };
  15042. Scene.prototype._removePendingData = function (data) {
  15043. var index = this._pendingData.indexOf(data);
  15044. if (index !== -1) {
  15045. this._pendingData.splice(index, 1);
  15046. }
  15047. };
  15048. Scene.prototype.getWaitingItemsCount = function () {
  15049. return this._pendingData.length;
  15050. };
  15051. /**
  15052. * Registers a function to be executed when the scene is ready.
  15053. * @param {Function} func - the function to be executed.
  15054. */
  15055. Scene.prototype.executeWhenReady = function (func) {
  15056. var _this = this;
  15057. this.onReadyObservable.add(func);
  15058. if (this._executeWhenReadyTimeoutId !== -1) {
  15059. return;
  15060. }
  15061. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15062. _this._checkIsReady();
  15063. }, 150);
  15064. };
  15065. Scene.prototype._checkIsReady = function () {
  15066. var _this = this;
  15067. if (this.isReady()) {
  15068. this.onReadyObservable.notifyObservers(this);
  15069. this.onReadyObservable.clear();
  15070. this._executeWhenReadyTimeoutId = -1;
  15071. return;
  15072. }
  15073. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15074. _this._checkIsReady();
  15075. }, 150);
  15076. };
  15077. // Animations
  15078. /**
  15079. * Will start the animation sequence of a given target
  15080. * @param target - the target
  15081. * @param {number} from - from which frame should animation start
  15082. * @param {number} to - till which frame should animation run.
  15083. * @param {boolean} [loop] - should the animation loop
  15084. * @param {number} [speedRatio] - the speed in which to run the animation
  15085. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15086. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15087. * @return {BABYLON.Animatable} the animatable object created for this animation
  15088. * @see BABYLON.Animatable
  15089. * @see http://doc.babylonjs.com/page.php?p=22081
  15090. */
  15091. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15092. if (speedRatio === void 0) { speedRatio = 1.0; }
  15093. this.stopAnimation(target);
  15094. if (!animatable) {
  15095. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15096. }
  15097. // Local animations
  15098. if (target.animations) {
  15099. animatable.appendAnimations(target, target.animations);
  15100. }
  15101. // Children animations
  15102. if (target.getAnimatables) {
  15103. var animatables = target.getAnimatables();
  15104. for (var index = 0; index < animatables.length; index++) {
  15105. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15106. }
  15107. }
  15108. animatable.reset();
  15109. return animatable;
  15110. };
  15111. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15112. if (speedRatio === undefined) {
  15113. speedRatio = 1.0;
  15114. }
  15115. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15116. return animatable;
  15117. };
  15118. Scene.prototype.getAnimatableByTarget = function (target) {
  15119. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15120. if (this._activeAnimatables[index].target === target) {
  15121. return this._activeAnimatables[index];
  15122. }
  15123. }
  15124. return null;
  15125. };
  15126. Object.defineProperty(Scene.prototype, "Animatables", {
  15127. get: function () {
  15128. return this._activeAnimatables;
  15129. },
  15130. enumerable: true,
  15131. configurable: true
  15132. });
  15133. /**
  15134. * Will stop the animation of the given target
  15135. * @param target - the target
  15136. * @see beginAnimation
  15137. */
  15138. Scene.prototype.stopAnimation = function (target) {
  15139. var animatable = this.getAnimatableByTarget(target);
  15140. if (animatable) {
  15141. animatable.stop();
  15142. }
  15143. };
  15144. Scene.prototype._animate = function () {
  15145. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15146. return;
  15147. }
  15148. if (!this._animationStartDate) {
  15149. if (this._pendingData.length > 0) {
  15150. return;
  15151. }
  15152. this._animationStartDate = BABYLON.Tools.Now;
  15153. }
  15154. // Getting time
  15155. var now = BABYLON.Tools.Now;
  15156. var delay = now - this._animationStartDate;
  15157. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15158. this._activeAnimatables[index]._animate(delay);
  15159. }
  15160. };
  15161. // Matrix
  15162. Scene.prototype.getViewMatrix = function () {
  15163. return this._viewMatrix;
  15164. };
  15165. Scene.prototype.getProjectionMatrix = function () {
  15166. return this._projectionMatrix;
  15167. };
  15168. Scene.prototype.getTransformMatrix = function () {
  15169. return this._transformMatrix;
  15170. };
  15171. Scene.prototype.setTransformMatrix = function (view, projection) {
  15172. this._viewMatrix = view;
  15173. this._projectionMatrix = projection;
  15174. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15175. };
  15176. // Methods
  15177. Scene.prototype.addMesh = function (newMesh) {
  15178. newMesh.uniqueId = this._uniqueIdCounter++;
  15179. var position = this.meshes.push(newMesh);
  15180. //notify the collision coordinator
  15181. this.collisionCoordinator.onMeshAdded(newMesh);
  15182. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15183. };
  15184. Scene.prototype.removeMesh = function (toRemove) {
  15185. var index = this.meshes.indexOf(toRemove);
  15186. if (index !== -1) {
  15187. // Remove from the scene if mesh found
  15188. this.meshes.splice(index, 1);
  15189. }
  15190. //notify the collision coordinator
  15191. this.collisionCoordinator.onMeshRemoved(toRemove);
  15192. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15193. return index;
  15194. };
  15195. Scene.prototype.removeSkeleton = function (toRemove) {
  15196. var index = this.skeletons.indexOf(toRemove);
  15197. if (index !== -1) {
  15198. // Remove from the scene if mesh found
  15199. this.skeletons.splice(index, 1);
  15200. }
  15201. return index;
  15202. };
  15203. Scene.prototype.removeLight = function (toRemove) {
  15204. var index = this.lights.indexOf(toRemove);
  15205. if (index !== -1) {
  15206. // Remove from the scene if mesh found
  15207. this.lights.splice(index, 1);
  15208. }
  15209. this.onLightRemovedObservable.notifyObservers(toRemove);
  15210. return index;
  15211. };
  15212. Scene.prototype.removeCamera = function (toRemove) {
  15213. var index = this.cameras.indexOf(toRemove);
  15214. if (index !== -1) {
  15215. // Remove from the scene if mesh found
  15216. this.cameras.splice(index, 1);
  15217. }
  15218. // Remove from activeCameras
  15219. var index2 = this.activeCameras.indexOf(toRemove);
  15220. if (index2 !== -1) {
  15221. // Remove from the scene if mesh found
  15222. this.activeCameras.splice(index2, 1);
  15223. }
  15224. // Reset the activeCamera
  15225. if (this.activeCamera === toRemove) {
  15226. if (this.cameras.length > 0) {
  15227. this.activeCamera = this.cameras[0];
  15228. }
  15229. else {
  15230. this.activeCamera = null;
  15231. }
  15232. }
  15233. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15234. return index;
  15235. };
  15236. Scene.prototype.addLight = function (newLight) {
  15237. newLight.uniqueId = this._uniqueIdCounter++;
  15238. var position = this.lights.push(newLight);
  15239. this.onNewLightAddedObservable.notifyObservers(newLight);
  15240. };
  15241. Scene.prototype.addCamera = function (newCamera) {
  15242. newCamera.uniqueId = this._uniqueIdCounter++;
  15243. var position = this.cameras.push(newCamera);
  15244. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15245. };
  15246. /**
  15247. * Switch active camera
  15248. * @param {Camera} newCamera - new active camera
  15249. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15250. */
  15251. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15252. if (attachControl === void 0) { attachControl = true; }
  15253. var canvas = this._engine.getRenderingCanvas();
  15254. this.activeCamera.detachControl(canvas);
  15255. this.activeCamera = newCamera;
  15256. if (attachControl) {
  15257. newCamera.attachControl(canvas);
  15258. }
  15259. };
  15260. /**
  15261. * sets the active camera of the scene using its ID
  15262. * @param {string} id - the camera's ID
  15263. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15264. * @see activeCamera
  15265. */
  15266. Scene.prototype.setActiveCameraByID = function (id) {
  15267. var camera = this.getCameraByID(id);
  15268. if (camera) {
  15269. this.activeCamera = camera;
  15270. return camera;
  15271. }
  15272. return null;
  15273. };
  15274. /**
  15275. * sets the active camera of the scene using its name
  15276. * @param {string} name - the camera's name
  15277. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15278. * @see activeCamera
  15279. */
  15280. Scene.prototype.setActiveCameraByName = function (name) {
  15281. var camera = this.getCameraByName(name);
  15282. if (camera) {
  15283. this.activeCamera = camera;
  15284. return camera;
  15285. }
  15286. return null;
  15287. };
  15288. /**
  15289. * get a material using its id
  15290. * @param {string} the material's ID
  15291. * @return {BABYLON.Material|null} the material or null if none found.
  15292. */
  15293. Scene.prototype.getMaterialByID = function (id) {
  15294. for (var index = 0; index < this.materials.length; index++) {
  15295. if (this.materials[index].id === id) {
  15296. return this.materials[index];
  15297. }
  15298. }
  15299. return null;
  15300. };
  15301. /**
  15302. * get a material using its name
  15303. * @param {string} the material's name
  15304. * @return {BABYLON.Material|null} the material or null if none found.
  15305. */
  15306. Scene.prototype.getMaterialByName = function (name) {
  15307. for (var index = 0; index < this.materials.length; index++) {
  15308. if (this.materials[index].name === name) {
  15309. return this.materials[index];
  15310. }
  15311. }
  15312. return null;
  15313. };
  15314. Scene.prototype.getLensFlareSystemByName = function (name) {
  15315. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15316. if (this.lensFlareSystems[index].name === name) {
  15317. return this.lensFlareSystems[index];
  15318. }
  15319. }
  15320. return null;
  15321. };
  15322. Scene.prototype.getLensFlareSystemByID = function (id) {
  15323. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15324. if (this.lensFlareSystems[index].id === id) {
  15325. return this.lensFlareSystems[index];
  15326. }
  15327. }
  15328. return null;
  15329. };
  15330. Scene.prototype.getCameraByID = function (id) {
  15331. for (var index = 0; index < this.cameras.length; index++) {
  15332. if (this.cameras[index].id === id) {
  15333. return this.cameras[index];
  15334. }
  15335. }
  15336. return null;
  15337. };
  15338. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15339. for (var index = 0; index < this.cameras.length; index++) {
  15340. if (this.cameras[index].uniqueId === uniqueId) {
  15341. return this.cameras[index];
  15342. }
  15343. }
  15344. return null;
  15345. };
  15346. /**
  15347. * get a camera using its name
  15348. * @param {string} the camera's name
  15349. * @return {BABYLON.Camera|null} the camera or null if none found.
  15350. */
  15351. Scene.prototype.getCameraByName = function (name) {
  15352. for (var index = 0; index < this.cameras.length; index++) {
  15353. if (this.cameras[index].name === name) {
  15354. return this.cameras[index];
  15355. }
  15356. }
  15357. return null;
  15358. };
  15359. /**
  15360. * get a bone using its id
  15361. * @param {string} the bone's id
  15362. * @return {BABYLON.Bone|null} the bone or null if not found
  15363. */
  15364. Scene.prototype.getBoneByID = function (id) {
  15365. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15366. var skeleton = this.skeletons[skeletonIndex];
  15367. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15368. if (skeleton.bones[boneIndex].id === id) {
  15369. return skeleton.bones[boneIndex];
  15370. }
  15371. }
  15372. }
  15373. return null;
  15374. };
  15375. /**
  15376. * get a bone using its id
  15377. * @param {string} the bone's name
  15378. * @return {BABYLON.Bone|null} the bone or null if not found
  15379. */
  15380. Scene.prototype.getBoneByName = function (name) {
  15381. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15382. var skeleton = this.skeletons[skeletonIndex];
  15383. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15384. if (skeleton.bones[boneIndex].name === name) {
  15385. return skeleton.bones[boneIndex];
  15386. }
  15387. }
  15388. }
  15389. return null;
  15390. };
  15391. /**
  15392. * get a light node using its name
  15393. * @param {string} the light's name
  15394. * @return {BABYLON.Light|null} the light or null if none found.
  15395. */
  15396. Scene.prototype.getLightByName = function (name) {
  15397. for (var index = 0; index < this.lights.length; index++) {
  15398. if (this.lights[index].name === name) {
  15399. return this.lights[index];
  15400. }
  15401. }
  15402. return null;
  15403. };
  15404. /**
  15405. * get a light node using its ID
  15406. * @param {string} the light's id
  15407. * @return {BABYLON.Light|null} the light or null if none found.
  15408. */
  15409. Scene.prototype.getLightByID = function (id) {
  15410. for (var index = 0; index < this.lights.length; index++) {
  15411. if (this.lights[index].id === id) {
  15412. return this.lights[index];
  15413. }
  15414. }
  15415. return null;
  15416. };
  15417. /**
  15418. * get a light node using its scene-generated unique ID
  15419. * @param {number} the light's unique id
  15420. * @return {BABYLON.Light|null} the light or null if none found.
  15421. */
  15422. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15423. for (var index = 0; index < this.lights.length; index++) {
  15424. if (this.lights[index].uniqueId === uniqueId) {
  15425. return this.lights[index];
  15426. }
  15427. }
  15428. return null;
  15429. };
  15430. /**
  15431. * get a particle system by id
  15432. * @param id {number} the particle system id
  15433. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15434. */
  15435. Scene.prototype.getParticleSystemByID = function (id) {
  15436. for (var index = 0; index < this.particleSystems.length; index++) {
  15437. if (this.particleSystems[index].id === id) {
  15438. return this.particleSystems[index];
  15439. }
  15440. }
  15441. return null;
  15442. };
  15443. /**
  15444. * get a geometry using its ID
  15445. * @param {string} the geometry's id
  15446. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15447. */
  15448. Scene.prototype.getGeometryByID = function (id) {
  15449. for (var index = 0; index < this._geometries.length; index++) {
  15450. if (this._geometries[index].id === id) {
  15451. return this._geometries[index];
  15452. }
  15453. }
  15454. return null;
  15455. };
  15456. /**
  15457. * add a new geometry to this scene.
  15458. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15459. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15460. * @return {boolean} was the geometry added or not
  15461. */
  15462. Scene.prototype.pushGeometry = function (geometry, force) {
  15463. if (!force && this.getGeometryByID(geometry.id)) {
  15464. return false;
  15465. }
  15466. this._geometries.push(geometry);
  15467. //notify the collision coordinator
  15468. this.collisionCoordinator.onGeometryAdded(geometry);
  15469. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15470. return true;
  15471. };
  15472. /**
  15473. * Removes an existing geometry
  15474. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15475. * @return {boolean} was the geometry removed or not
  15476. */
  15477. Scene.prototype.removeGeometry = function (geometry) {
  15478. var index = this._geometries.indexOf(geometry);
  15479. if (index > -1) {
  15480. this._geometries.splice(index, 1);
  15481. //notify the collision coordinator
  15482. this.collisionCoordinator.onGeometryDeleted(geometry);
  15483. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15484. return true;
  15485. }
  15486. return false;
  15487. };
  15488. Scene.prototype.getGeometries = function () {
  15489. return this._geometries;
  15490. };
  15491. /**
  15492. * Get the first added mesh found of a given ID
  15493. * @param {string} id - the id to search for
  15494. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15495. */
  15496. Scene.prototype.getMeshByID = function (id) {
  15497. for (var index = 0; index < this.meshes.length; index++) {
  15498. if (this.meshes[index].id === id) {
  15499. return this.meshes[index];
  15500. }
  15501. }
  15502. return null;
  15503. };
  15504. Scene.prototype.getMeshesByID = function (id) {
  15505. return this.meshes.filter(function (m) {
  15506. return m.id === id;
  15507. });
  15508. };
  15509. /**
  15510. * Get a mesh with its auto-generated unique id
  15511. * @param {number} uniqueId - the unique id to search for
  15512. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15513. */
  15514. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15515. for (var index = 0; index < this.meshes.length; index++) {
  15516. if (this.meshes[index].uniqueId === uniqueId) {
  15517. return this.meshes[index];
  15518. }
  15519. }
  15520. return null;
  15521. };
  15522. /**
  15523. * Get a the last added mesh found of a given ID
  15524. * @param {string} id - the id to search for
  15525. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15526. */
  15527. Scene.prototype.getLastMeshByID = function (id) {
  15528. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15529. if (this.meshes[index].id === id) {
  15530. return this.meshes[index];
  15531. }
  15532. }
  15533. return null;
  15534. };
  15535. /**
  15536. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15537. * @param {string} id - the id to search for
  15538. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15539. */
  15540. Scene.prototype.getLastEntryByID = function (id) {
  15541. var index;
  15542. for (index = this.meshes.length - 1; index >= 0; index--) {
  15543. if (this.meshes[index].id === id) {
  15544. return this.meshes[index];
  15545. }
  15546. }
  15547. for (index = this.cameras.length - 1; index >= 0; index--) {
  15548. if (this.cameras[index].id === id) {
  15549. return this.cameras[index];
  15550. }
  15551. }
  15552. for (index = this.lights.length - 1; index >= 0; index--) {
  15553. if (this.lights[index].id === id) {
  15554. return this.lights[index];
  15555. }
  15556. }
  15557. return null;
  15558. };
  15559. Scene.prototype.getNodeByID = function (id) {
  15560. var mesh = this.getMeshByID(id);
  15561. if (mesh) {
  15562. return mesh;
  15563. }
  15564. var light = this.getLightByID(id);
  15565. if (light) {
  15566. return light;
  15567. }
  15568. var camera = this.getCameraByID(id);
  15569. if (camera) {
  15570. return camera;
  15571. }
  15572. var bone = this.getBoneByID(id);
  15573. return bone;
  15574. };
  15575. Scene.prototype.getNodeByName = function (name) {
  15576. var mesh = this.getMeshByName(name);
  15577. if (mesh) {
  15578. return mesh;
  15579. }
  15580. var light = this.getLightByName(name);
  15581. if (light) {
  15582. return light;
  15583. }
  15584. var camera = this.getCameraByName(name);
  15585. if (camera) {
  15586. return camera;
  15587. }
  15588. var bone = this.getBoneByName(name);
  15589. return bone;
  15590. };
  15591. Scene.prototype.getMeshByName = function (name) {
  15592. for (var index = 0; index < this.meshes.length; index++) {
  15593. if (this.meshes[index].name === name) {
  15594. return this.meshes[index];
  15595. }
  15596. }
  15597. return null;
  15598. };
  15599. Scene.prototype.getSoundByName = function (name) {
  15600. var index;
  15601. if (BABYLON.AudioEngine) {
  15602. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15603. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15604. return this.mainSoundTrack.soundCollection[index];
  15605. }
  15606. }
  15607. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15608. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15609. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15610. return this.soundTracks[sdIndex].soundCollection[index];
  15611. }
  15612. }
  15613. }
  15614. }
  15615. return null;
  15616. };
  15617. Scene.prototype.getLastSkeletonByID = function (id) {
  15618. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15619. if (this.skeletons[index].id === id) {
  15620. return this.skeletons[index];
  15621. }
  15622. }
  15623. return null;
  15624. };
  15625. Scene.prototype.getSkeletonById = function (id) {
  15626. for (var index = 0; index < this.skeletons.length; index++) {
  15627. if (this.skeletons[index].id === id) {
  15628. return this.skeletons[index];
  15629. }
  15630. }
  15631. return null;
  15632. };
  15633. Scene.prototype.getSkeletonByName = function (name) {
  15634. for (var index = 0; index < this.skeletons.length; index++) {
  15635. if (this.skeletons[index].name === name) {
  15636. return this.skeletons[index];
  15637. }
  15638. }
  15639. return null;
  15640. };
  15641. Scene.prototype.isActiveMesh = function (mesh) {
  15642. return (this._activeMeshes.indexOf(mesh) !== -1);
  15643. };
  15644. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15645. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15646. var material = subMesh.getMaterial();
  15647. if (mesh.showSubMeshesBoundingBox) {
  15648. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15649. }
  15650. if (material) {
  15651. // Render targets
  15652. if (material.getRenderTargetTextures) {
  15653. if (this._processedMaterials.indexOf(material) === -1) {
  15654. this._processedMaterials.push(material);
  15655. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15656. }
  15657. }
  15658. // Dispatch
  15659. this._activeIndices += subMesh.indexCount;
  15660. this._renderingManager.dispatch(subMesh);
  15661. }
  15662. }
  15663. };
  15664. Scene.prototype._isInIntermediateRendering = function () {
  15665. return this._intermediateRendering;
  15666. };
  15667. Scene.prototype._evaluateActiveMeshes = function () {
  15668. this.activeCamera._activeMeshes.reset();
  15669. this._activeMeshes.reset();
  15670. this._renderingManager.reset();
  15671. this._processedMaterials.reset();
  15672. this._activeParticleSystems.reset();
  15673. this._activeSkeletons.reset();
  15674. this._softwareSkinnedMeshes.reset();
  15675. this._boundingBoxRenderer.reset();
  15676. this._edgesRenderers.reset();
  15677. if (!this._frustumPlanes) {
  15678. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15679. }
  15680. else {
  15681. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15682. }
  15683. // Meshes
  15684. var meshes;
  15685. var len;
  15686. if (this._selectionOctree) {
  15687. var selection = this._selectionOctree.select(this._frustumPlanes);
  15688. meshes = selection.data;
  15689. len = selection.length;
  15690. }
  15691. else {
  15692. len = this.meshes.length;
  15693. meshes = this.meshes;
  15694. }
  15695. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15696. var mesh = meshes[meshIndex];
  15697. if (mesh.isBlocked) {
  15698. continue;
  15699. }
  15700. this._totalVertices += mesh.getTotalVertices();
  15701. if (!mesh.isReady() || !mesh.isEnabled()) {
  15702. continue;
  15703. }
  15704. mesh.computeWorldMatrix();
  15705. // Intersections
  15706. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15707. this._meshesForIntersections.pushNoDuplicate(mesh);
  15708. }
  15709. // Switch to current LOD
  15710. var meshLOD = mesh.getLOD(this.activeCamera);
  15711. if (!meshLOD) {
  15712. continue;
  15713. }
  15714. mesh._preActivate();
  15715. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15716. this._activeMeshes.push(mesh);
  15717. this.activeCamera._activeMeshes.push(mesh);
  15718. mesh._activate(this._renderId);
  15719. this._activeMesh(meshLOD);
  15720. }
  15721. }
  15722. // Particle systems
  15723. var beforeParticlesDate = BABYLON.Tools.Now;
  15724. if (this.particlesEnabled) {
  15725. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15726. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15727. var particleSystem = this.particleSystems[particleIndex];
  15728. if (!particleSystem.isStarted()) {
  15729. continue;
  15730. }
  15731. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15732. this._activeParticleSystems.push(particleSystem);
  15733. particleSystem.animate();
  15734. }
  15735. }
  15736. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15737. }
  15738. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15739. };
  15740. Scene.prototype._activeMesh = function (mesh) {
  15741. if (mesh.skeleton && this.skeletonsEnabled) {
  15742. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15743. if (!mesh.computeBonesUsingShaders) {
  15744. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15745. }
  15746. }
  15747. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15748. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15749. }
  15750. if (mesh._edgesRenderer) {
  15751. this._edgesRenderers.push(mesh._edgesRenderer);
  15752. }
  15753. if (mesh && mesh.subMeshes) {
  15754. // Submeshes Octrees
  15755. var len;
  15756. var subMeshes;
  15757. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15758. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15759. len = intersections.length;
  15760. subMeshes = intersections.data;
  15761. }
  15762. else {
  15763. subMeshes = mesh.subMeshes;
  15764. len = subMeshes.length;
  15765. }
  15766. for (var subIndex = 0; subIndex < len; subIndex++) {
  15767. var subMesh = subMeshes[subIndex];
  15768. this._evaluateSubMesh(subMesh, mesh);
  15769. }
  15770. }
  15771. };
  15772. Scene.prototype.updateTransformMatrix = function (force) {
  15773. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15774. };
  15775. Scene.prototype._renderForCamera = function (camera) {
  15776. var engine = this._engine;
  15777. this.activeCamera = camera;
  15778. if (!this.activeCamera)
  15779. throw new Error("Active camera not set");
  15780. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15781. // Viewport
  15782. engine.setViewport(this.activeCamera.viewport);
  15783. // Camera
  15784. this.resetCachedMaterial();
  15785. this._renderId++;
  15786. this.updateTransformMatrix();
  15787. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15788. // Meshes
  15789. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15790. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15791. this._evaluateActiveMeshes();
  15792. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15793. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15794. // Skeletons
  15795. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15796. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15797. skeleton.prepare();
  15798. }
  15799. // Software skinning
  15800. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15801. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15802. mesh.applySkeleton(mesh.skeleton);
  15803. }
  15804. // Render targets
  15805. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15806. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15807. this._intermediateRendering = true;
  15808. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15809. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15810. var renderTarget = this._renderTargets.data[renderIndex];
  15811. if (renderTarget._shouldRender()) {
  15812. this._renderId++;
  15813. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15814. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15815. }
  15816. }
  15817. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15818. this._intermediateRendering = false;
  15819. this._renderId++;
  15820. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15821. }
  15822. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15823. // Prepare Frame
  15824. this.postProcessManager._prepareFrame();
  15825. var beforeRenderDate = BABYLON.Tools.Now;
  15826. // Backgrounds
  15827. var layerIndex;
  15828. var layer;
  15829. if (this.layers.length) {
  15830. engine.setDepthBuffer(false);
  15831. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15832. layer = this.layers[layerIndex];
  15833. if (layer.isBackground) {
  15834. layer.render();
  15835. }
  15836. }
  15837. engine.setDepthBuffer(true);
  15838. }
  15839. // Render
  15840. BABYLON.Tools.StartPerformanceCounter("Main render");
  15841. this._renderingManager.render(null, null, true, true);
  15842. BABYLON.Tools.EndPerformanceCounter("Main render");
  15843. // Bounding boxes
  15844. this._boundingBoxRenderer.render();
  15845. // Edges
  15846. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15847. this._edgesRenderers.data[edgesRendererIndex].render();
  15848. }
  15849. // Lens flares
  15850. if (this.lensFlaresEnabled) {
  15851. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15852. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15853. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15854. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15855. lensFlareSystem.render();
  15856. }
  15857. }
  15858. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15859. }
  15860. // Foregrounds
  15861. if (this.layers.length) {
  15862. engine.setDepthBuffer(false);
  15863. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15864. layer = this.layers[layerIndex];
  15865. if (!layer.isBackground) {
  15866. layer.render();
  15867. }
  15868. }
  15869. engine.setDepthBuffer(true);
  15870. }
  15871. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15872. // Finalize frame
  15873. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15874. // Update camera
  15875. this.activeCamera._updateFromScene();
  15876. // Reset some special arrays
  15877. this._renderTargets.reset();
  15878. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15879. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15880. };
  15881. Scene.prototype._processSubCameras = function (camera) {
  15882. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15883. this._renderForCamera(camera);
  15884. return;
  15885. }
  15886. // rig cameras
  15887. for (var index = 0; index < camera._rigCameras.length; index++) {
  15888. this._renderForCamera(camera._rigCameras[index]);
  15889. }
  15890. this.activeCamera = camera;
  15891. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15892. // Update camera
  15893. this.activeCamera._updateFromScene();
  15894. };
  15895. Scene.prototype._checkIntersections = function () {
  15896. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15897. var sourceMesh = this._meshesForIntersections.data[index];
  15898. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15899. var action = sourceMesh.actionManager.actions[actionIndex];
  15900. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15901. var parameters = action.getTriggerParameter();
  15902. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15903. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15904. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15905. if (areIntersecting && currentIntersectionInProgress === -1) {
  15906. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15907. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15908. sourceMesh._intersectionsInProgress.push(otherMesh);
  15909. }
  15910. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15911. sourceMesh._intersectionsInProgress.push(otherMesh);
  15912. }
  15913. }
  15914. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15915. //They intersected, and now they don't.
  15916. //is this trigger an exit trigger? execute an event.
  15917. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15918. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15919. }
  15920. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15921. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15922. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15923. }
  15924. }
  15925. }
  15926. }
  15927. }
  15928. };
  15929. Scene.prototype.render = function () {
  15930. var startDate = BABYLON.Tools.Now;
  15931. this._particlesDuration = 0;
  15932. this._spritesDuration = 0;
  15933. this._activeParticles = 0;
  15934. this._renderDuration = 0;
  15935. this._renderTargetsDuration = 0;
  15936. this._evaluateActiveMeshesDuration = 0;
  15937. this._totalVertices = 0;
  15938. this._activeIndices = 0;
  15939. this._activeBones = 0;
  15940. this.getEngine().resetDrawCalls();
  15941. this._meshesForIntersections.reset();
  15942. this.resetCachedMaterial();
  15943. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15944. // Actions
  15945. if (this.actionManager) {
  15946. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15947. }
  15948. //Simplification Queue
  15949. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15950. this.simplificationQueue.executeNext();
  15951. }
  15952. // Animations
  15953. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15954. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15955. this._animate();
  15956. // Physics
  15957. if (this._physicsEngine) {
  15958. BABYLON.Tools.StartPerformanceCounter("Physics");
  15959. this._physicsEngine._step(deltaTime / 1000.0);
  15960. BABYLON.Tools.EndPerformanceCounter("Physics");
  15961. }
  15962. // Before render
  15963. this.onBeforeRenderObservable.notifyObservers(this);
  15964. // Customs render targets
  15965. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15966. var engine = this.getEngine();
  15967. var currentActiveCamera = this.activeCamera;
  15968. if (this.renderTargetsEnabled) {
  15969. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15970. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15971. var renderTarget = this.customRenderTargets[customIndex];
  15972. if (renderTarget._shouldRender()) {
  15973. this._renderId++;
  15974. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15975. if (!this.activeCamera)
  15976. throw new Error("Active camera not set");
  15977. // Viewport
  15978. engine.setViewport(this.activeCamera.viewport);
  15979. // Camera
  15980. this.updateTransformMatrix();
  15981. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15982. }
  15983. }
  15984. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15985. this._renderId++;
  15986. }
  15987. if (this.customRenderTargets.length > 0) {
  15988. engine.restoreDefaultFramebuffer();
  15989. }
  15990. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15991. this.activeCamera = currentActiveCamera;
  15992. // Procedural textures
  15993. if (this.proceduralTexturesEnabled) {
  15994. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15995. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15996. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15997. if (proceduralTexture._shouldRender()) {
  15998. proceduralTexture.render();
  15999. }
  16000. }
  16001. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16002. }
  16003. // Clear
  16004. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16005. // Shadows
  16006. if (this.shadowsEnabled) {
  16007. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16008. var light = this.lights[lightIndex];
  16009. var shadowGenerator = light.getShadowGenerator();
  16010. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16011. this._renderTargets.push(shadowGenerator.getShadowMap());
  16012. }
  16013. }
  16014. }
  16015. // Depth renderer
  16016. if (this._depthRenderer) {
  16017. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16018. }
  16019. // RenderPipeline
  16020. this.postProcessRenderPipelineManager.update();
  16021. // Multi-cameras?
  16022. if (this.activeCameras.length > 0) {
  16023. var currentRenderId = this._renderId;
  16024. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16025. this._renderId = currentRenderId;
  16026. if (cameraIndex > 0) {
  16027. this._engine.clear(0, false, true);
  16028. }
  16029. this._processSubCameras(this.activeCameras[cameraIndex]);
  16030. }
  16031. }
  16032. else {
  16033. if (!this.activeCamera) {
  16034. throw new Error("No camera defined");
  16035. }
  16036. this._processSubCameras(this.activeCamera);
  16037. }
  16038. // Intersection checks
  16039. this._checkIntersections();
  16040. // Update the audio listener attached to the camera
  16041. if (BABYLON.AudioEngine) {
  16042. this._updateAudioParameters();
  16043. }
  16044. // After render
  16045. if (this.afterRender) {
  16046. this.afterRender();
  16047. }
  16048. this.onAfterRenderObservable.notifyObservers(this);
  16049. // Cleaning
  16050. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16051. this._toBeDisposed.data[index].dispose();
  16052. this._toBeDisposed[index] = null;
  16053. }
  16054. this._toBeDisposed.reset();
  16055. if (this.dumpNextRenderTargets) {
  16056. this.dumpNextRenderTargets = false;
  16057. }
  16058. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16059. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  16060. };
  16061. Scene.prototype._updateAudioParameters = function () {
  16062. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16063. return;
  16064. }
  16065. var listeningCamera;
  16066. var audioEngine = BABYLON.Engine.audioEngine;
  16067. if (this.activeCameras.length > 0) {
  16068. listeningCamera = this.activeCameras[0];
  16069. }
  16070. else {
  16071. listeningCamera = this.activeCamera;
  16072. }
  16073. if (listeningCamera && audioEngine.canUseWebAudio) {
  16074. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16075. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16076. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16077. cameraDirection.normalize();
  16078. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16079. var i;
  16080. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16081. var sound = this.mainSoundTrack.soundCollection[i];
  16082. if (sound.useCustomAttenuation) {
  16083. sound.updateDistanceFromListener();
  16084. }
  16085. }
  16086. for (i = 0; i < this.soundTracks.length; i++) {
  16087. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16088. sound = this.soundTracks[i].soundCollection[j];
  16089. if (sound.useCustomAttenuation) {
  16090. sound.updateDistanceFromListener();
  16091. }
  16092. }
  16093. }
  16094. }
  16095. };
  16096. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16097. // Audio
  16098. get: function () {
  16099. return this._audioEnabled;
  16100. },
  16101. set: function (value) {
  16102. this._audioEnabled = value;
  16103. if (BABYLON.AudioEngine) {
  16104. if (this._audioEnabled) {
  16105. this._enableAudio();
  16106. }
  16107. else {
  16108. this._disableAudio();
  16109. }
  16110. }
  16111. },
  16112. enumerable: true,
  16113. configurable: true
  16114. });
  16115. Scene.prototype._disableAudio = function () {
  16116. var i;
  16117. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16118. this.mainSoundTrack.soundCollection[i].pause();
  16119. }
  16120. for (i = 0; i < this.soundTracks.length; i++) {
  16121. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16122. this.soundTracks[i].soundCollection[j].pause();
  16123. }
  16124. }
  16125. };
  16126. Scene.prototype._enableAudio = function () {
  16127. var i;
  16128. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16129. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16130. this.mainSoundTrack.soundCollection[i].play();
  16131. }
  16132. }
  16133. for (i = 0; i < this.soundTracks.length; i++) {
  16134. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16135. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16136. this.soundTracks[i].soundCollection[j].play();
  16137. }
  16138. }
  16139. }
  16140. };
  16141. Object.defineProperty(Scene.prototype, "headphone", {
  16142. get: function () {
  16143. return this._headphone;
  16144. },
  16145. set: function (value) {
  16146. this._headphone = value;
  16147. if (BABYLON.AudioEngine) {
  16148. if (this._headphone) {
  16149. this._switchAudioModeForHeadphones();
  16150. }
  16151. else {
  16152. this._switchAudioModeForNormalSpeakers();
  16153. }
  16154. }
  16155. },
  16156. enumerable: true,
  16157. configurable: true
  16158. });
  16159. Scene.prototype._switchAudioModeForHeadphones = function () {
  16160. this.mainSoundTrack.switchPanningModelToHRTF();
  16161. for (var i = 0; i < this.soundTracks.length; i++) {
  16162. this.soundTracks[i].switchPanningModelToHRTF();
  16163. }
  16164. };
  16165. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16166. this.mainSoundTrack.switchPanningModelToEqualPower();
  16167. for (var i = 0; i < this.soundTracks.length; i++) {
  16168. this.soundTracks[i].switchPanningModelToEqualPower();
  16169. }
  16170. };
  16171. Scene.prototype.enableDepthRenderer = function () {
  16172. if (this._depthRenderer) {
  16173. return this._depthRenderer;
  16174. }
  16175. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16176. return this._depthRenderer;
  16177. };
  16178. Scene.prototype.disableDepthRenderer = function () {
  16179. if (!this._depthRenderer) {
  16180. return;
  16181. }
  16182. this._depthRenderer.dispose();
  16183. this._depthRenderer = null;
  16184. };
  16185. Scene.prototype.freezeMaterials = function () {
  16186. for (var i = 0; i < this.materials.length; i++) {
  16187. this.materials[i].freeze();
  16188. }
  16189. };
  16190. Scene.prototype.unfreezeMaterials = function () {
  16191. for (var i = 0; i < this.materials.length; i++) {
  16192. this.materials[i].unfreeze();
  16193. }
  16194. };
  16195. Scene.prototype.dispose = function () {
  16196. this.beforeRender = null;
  16197. this.afterRender = null;
  16198. this.skeletons = [];
  16199. this._boundingBoxRenderer.dispose();
  16200. if (this._depthRenderer) {
  16201. this._depthRenderer.dispose();
  16202. }
  16203. // Debug layer
  16204. if (this._debugLayer) {
  16205. this._debugLayer.hide();
  16206. }
  16207. // Events
  16208. this.onDisposeObservable.notifyObservers(this);
  16209. this.onDisposeObservable.clear();
  16210. this.onBeforeRenderObservable.clear();
  16211. this.onAfterRenderObservable.clear();
  16212. this.detachControl();
  16213. // Release sounds & sounds tracks
  16214. if (BABYLON.AudioEngine) {
  16215. this.disposeSounds();
  16216. }
  16217. // Detach cameras
  16218. var canvas = this._engine.getRenderingCanvas();
  16219. var index;
  16220. for (index = 0; index < this.cameras.length; index++) {
  16221. this.cameras[index].detachControl(canvas);
  16222. }
  16223. // Release lights
  16224. while (this.lights.length) {
  16225. this.lights[0].dispose();
  16226. }
  16227. // Release meshes
  16228. while (this.meshes.length) {
  16229. this.meshes[0].dispose(true);
  16230. }
  16231. // Release cameras
  16232. while (this.cameras.length) {
  16233. this.cameras[0].dispose();
  16234. }
  16235. // Release materials
  16236. while (this.materials.length) {
  16237. this.materials[0].dispose();
  16238. }
  16239. // Release particles
  16240. while (this.particleSystems.length) {
  16241. this.particleSystems[0].dispose();
  16242. }
  16243. // Release sprites
  16244. while (this.spriteManagers.length) {
  16245. this.spriteManagers[0].dispose();
  16246. }
  16247. // Release layers
  16248. while (this.layers.length) {
  16249. this.layers[0].dispose();
  16250. }
  16251. // Release textures
  16252. while (this.textures.length) {
  16253. this.textures[0].dispose();
  16254. }
  16255. // Post-processes
  16256. this.postProcessManager.dispose();
  16257. // Physics
  16258. if (this._physicsEngine) {
  16259. this.disablePhysicsEngine();
  16260. }
  16261. // Remove from engine
  16262. index = this._engine.scenes.indexOf(this);
  16263. if (index > -1) {
  16264. this._engine.scenes.splice(index, 1);
  16265. }
  16266. this._engine.wipeCaches();
  16267. };
  16268. // Release sounds & sounds tracks
  16269. Scene.prototype.disposeSounds = function () {
  16270. this.mainSoundTrack.dispose();
  16271. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16272. this.soundTracks[scIndex].dispose();
  16273. }
  16274. };
  16275. // Octrees
  16276. Scene.prototype.getWorldExtends = function () {
  16277. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16278. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16279. for (var index = 0; index < this.meshes.length; index++) {
  16280. var mesh = this.meshes[index];
  16281. mesh.computeWorldMatrix(true);
  16282. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16283. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16284. BABYLON.Tools.CheckExtends(minBox, min, max);
  16285. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16286. }
  16287. return {
  16288. min: min,
  16289. max: max
  16290. };
  16291. };
  16292. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16293. if (maxCapacity === void 0) { maxCapacity = 64; }
  16294. if (maxDepth === void 0) { maxDepth = 2; }
  16295. if (!this._selectionOctree) {
  16296. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16297. }
  16298. var worldExtends = this.getWorldExtends();
  16299. // Update octree
  16300. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16301. return this._selectionOctree;
  16302. };
  16303. // Picking
  16304. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16305. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16306. var engine = this._engine;
  16307. if (!camera) {
  16308. if (!this.activeCamera)
  16309. throw new Error("Active camera not set");
  16310. camera = this.activeCamera;
  16311. }
  16312. var cameraViewport = camera.viewport;
  16313. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16314. // Moving coordinates to local viewport world
  16315. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16316. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16317. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16318. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16319. };
  16320. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16321. var engine = this._engine;
  16322. if (!camera) {
  16323. if (!this.activeCamera)
  16324. throw new Error("Active camera not set");
  16325. camera = this.activeCamera;
  16326. }
  16327. var cameraViewport = camera.viewport;
  16328. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16329. var identity = BABYLON.Matrix.Identity();
  16330. // Moving coordinates to local viewport world
  16331. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16332. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16333. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16334. };
  16335. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16336. var pickingInfo = null;
  16337. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16338. var mesh = this.meshes[meshIndex];
  16339. if (predicate) {
  16340. if (!predicate(mesh)) {
  16341. continue;
  16342. }
  16343. }
  16344. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16345. continue;
  16346. }
  16347. var world = mesh.getWorldMatrix();
  16348. var ray = rayFunction(world);
  16349. var result = mesh.intersects(ray, fastCheck);
  16350. if (!result || !result.hit)
  16351. continue;
  16352. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16353. continue;
  16354. pickingInfo = result;
  16355. if (fastCheck) {
  16356. break;
  16357. }
  16358. }
  16359. return pickingInfo || new BABYLON.PickingInfo();
  16360. };
  16361. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16362. var pickingInfo = null;
  16363. camera = camera || this.activeCamera;
  16364. if (this.spriteManagers.length > 0) {
  16365. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16366. var spriteManager = this.spriteManagers[spriteIndex];
  16367. if (!spriteManager.isPickable) {
  16368. continue;
  16369. }
  16370. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16371. if (!result || !result.hit)
  16372. continue;
  16373. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16374. continue;
  16375. pickingInfo = result;
  16376. if (fastCheck) {
  16377. break;
  16378. }
  16379. }
  16380. }
  16381. return pickingInfo || new BABYLON.PickingInfo();
  16382. };
  16383. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16384. var _this = this;
  16385. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16386. /// <param name="x">X position on screen</param>
  16387. /// <param name="y">Y position on screen</param>
  16388. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  16389. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16390. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  16391. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16392. };
  16393. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16394. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16395. /// <param name="x">X position on screen</param>
  16396. /// <param name="y">Y position on screen</param>
  16397. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  16398. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16399. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  16400. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16401. };
  16402. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16403. var _this = this;
  16404. return this._internalPick(function (world) {
  16405. if (!_this._pickWithRayInverseMatrix) {
  16406. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16407. }
  16408. world.invertToRef(_this._pickWithRayInverseMatrix);
  16409. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16410. }, predicate, fastCheck);
  16411. };
  16412. Scene.prototype.setPointerOverMesh = function (mesh) {
  16413. if (this._pointerOverMesh === mesh) {
  16414. return;
  16415. }
  16416. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16417. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16418. }
  16419. this._pointerOverMesh = mesh;
  16420. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16421. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16422. }
  16423. };
  16424. Scene.prototype.getPointerOverMesh = function () {
  16425. return this._pointerOverMesh;
  16426. };
  16427. Scene.prototype.setPointerOverSprite = function (sprite) {
  16428. if (this._pointerOverSprite === sprite) {
  16429. return;
  16430. }
  16431. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16432. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16433. }
  16434. this._pointerOverSprite = sprite;
  16435. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16436. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16437. }
  16438. };
  16439. Scene.prototype.getPointerOverSprite = function () {
  16440. return this._pointerOverSprite;
  16441. };
  16442. // Physics
  16443. Scene.prototype.getPhysicsEngine = function () {
  16444. return this._physicsEngine;
  16445. };
  16446. /**
  16447. * Enables physics to the current scene
  16448. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16449. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16450. * @return {boolean} was the physics engine initialized
  16451. */
  16452. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16453. if (this._physicsEngine) {
  16454. return true;
  16455. }
  16456. try {
  16457. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16458. return true;
  16459. }
  16460. catch (e) {
  16461. BABYLON.Tools.Error(e.message);
  16462. return false;
  16463. }
  16464. };
  16465. Scene.prototype.disablePhysicsEngine = function () {
  16466. if (!this._physicsEngine) {
  16467. return;
  16468. }
  16469. this._physicsEngine.dispose();
  16470. this._physicsEngine = undefined;
  16471. };
  16472. Scene.prototype.isPhysicsEnabled = function () {
  16473. return this._physicsEngine !== undefined;
  16474. };
  16475. /**
  16476. *
  16477. * Sets the gravity of the physics engine (and NOT of the scene)
  16478. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16479. */
  16480. Scene.prototype.setGravity = function (gravity) {
  16481. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16482. if (!this._physicsEngine) {
  16483. return;
  16484. }
  16485. this._physicsEngine.setGravity(gravity);
  16486. };
  16487. /**
  16488. * Legacy support, using the new API
  16489. * @Deprecated
  16490. */
  16491. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16492. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16493. if (parts.parts) {
  16494. options = parts;
  16495. parts = parts.parts;
  16496. }
  16497. var mainMesh = parts[0].mesh;
  16498. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16499. for (var index = 1; index < parts.length; index++) {
  16500. var mesh = parts[index].mesh;
  16501. if (mesh.parent !== mainMesh) {
  16502. mesh.position = mesh.position.subtract(mainMesh.position);
  16503. mesh.parent = mainMesh;
  16504. }
  16505. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16506. }
  16507. mainMesh.physicsImpostor.forceUpdate();
  16508. };
  16509. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16510. var mesh = compound.parts[0].mesh;
  16511. mesh.physicsImpostor.dispose();
  16512. mesh.physicsImpostor = null;
  16513. };
  16514. // Misc.
  16515. Scene.prototype.createDefaultCameraOrLight = function () {
  16516. // Light
  16517. if (this.lights.length === 0) {
  16518. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16519. }
  16520. // Camera
  16521. if (!this.activeCamera) {
  16522. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16523. // Compute position
  16524. var worldExtends = this.getWorldExtends();
  16525. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16526. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16527. camera.setTarget(worldCenter);
  16528. this.activeCamera = camera;
  16529. }
  16530. };
  16531. // Tags
  16532. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16533. if (tagsQuery === undefined) {
  16534. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16535. return list;
  16536. }
  16537. var listByTags = [];
  16538. forEach = forEach || (function (item) { return; });
  16539. for (var i in list) {
  16540. var item = list[i];
  16541. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16542. listByTags.push(item);
  16543. forEach(item);
  16544. }
  16545. }
  16546. return listByTags;
  16547. };
  16548. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16549. return this._getByTags(this.meshes, tagsQuery, forEach);
  16550. };
  16551. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16552. return this._getByTags(this.cameras, tagsQuery, forEach);
  16553. };
  16554. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16555. return this._getByTags(this.lights, tagsQuery, forEach);
  16556. };
  16557. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16558. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16559. };
  16560. // Statics
  16561. Scene._FOGMODE_NONE = 0;
  16562. Scene._FOGMODE_EXP = 1;
  16563. Scene._FOGMODE_EXP2 = 2;
  16564. Scene._FOGMODE_LINEAR = 3;
  16565. Scene.MinDeltaTime = 1.0;
  16566. Scene.MaxDeltaTime = 1000.0;
  16567. return Scene;
  16568. })();
  16569. BABYLON.Scene = Scene;
  16570. })(BABYLON || (BABYLON = {}));
  16571. var BABYLON;
  16572. (function (BABYLON) {
  16573. var VertexBuffer = (function () {
  16574. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16575. if (engine instanceof BABYLON.Mesh) {
  16576. this._engine = engine.getScene().getEngine();
  16577. }
  16578. else {
  16579. this._engine = engine;
  16580. }
  16581. this._updatable = updatable;
  16582. this._data = data;
  16583. if (!postponeInternalCreation) {
  16584. this.create();
  16585. }
  16586. this._kind = kind;
  16587. if (stride) {
  16588. this._strideSize = stride;
  16589. return;
  16590. }
  16591. // Deduce stride from kind
  16592. switch (kind) {
  16593. case VertexBuffer.PositionKind:
  16594. this._strideSize = 3;
  16595. break;
  16596. case VertexBuffer.NormalKind:
  16597. this._strideSize = 3;
  16598. break;
  16599. case VertexBuffer.UVKind:
  16600. case VertexBuffer.UV2Kind:
  16601. case VertexBuffer.UV3Kind:
  16602. case VertexBuffer.UV4Kind:
  16603. case VertexBuffer.UV5Kind:
  16604. case VertexBuffer.UV6Kind:
  16605. this._strideSize = 2;
  16606. break;
  16607. case VertexBuffer.ColorKind:
  16608. this._strideSize = 4;
  16609. break;
  16610. case VertexBuffer.MatricesIndicesKind:
  16611. case VertexBuffer.MatricesIndicesExtraKind:
  16612. this._strideSize = 4;
  16613. break;
  16614. case VertexBuffer.MatricesWeightsKind:
  16615. case VertexBuffer.MatricesWeightsExtraKind:
  16616. this._strideSize = 4;
  16617. break;
  16618. }
  16619. }
  16620. // Properties
  16621. VertexBuffer.prototype.isUpdatable = function () {
  16622. return this._updatable;
  16623. };
  16624. VertexBuffer.prototype.getData = function () {
  16625. return this._data;
  16626. };
  16627. VertexBuffer.prototype.getBuffer = function () {
  16628. return this._buffer;
  16629. };
  16630. VertexBuffer.prototype.getStrideSize = function () {
  16631. return this._strideSize;
  16632. };
  16633. // Methods
  16634. VertexBuffer.prototype.create = function (data) {
  16635. if (!data && this._buffer) {
  16636. return; // nothing to do
  16637. }
  16638. data = data || this._data;
  16639. if (!this._buffer) {
  16640. if (this._updatable) {
  16641. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16642. }
  16643. else {
  16644. this._buffer = this._engine.createVertexBuffer(data);
  16645. }
  16646. }
  16647. if (this._updatable) {
  16648. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16649. this._data = data;
  16650. }
  16651. };
  16652. VertexBuffer.prototype.update = function (data) {
  16653. this.create(data);
  16654. };
  16655. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16656. if (!this._buffer) {
  16657. return;
  16658. }
  16659. if (this._updatable) {
  16660. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16661. this._data = null;
  16662. }
  16663. };
  16664. VertexBuffer.prototype.dispose = function () {
  16665. if (!this._buffer) {
  16666. return;
  16667. }
  16668. if (this._engine._releaseBuffer(this._buffer)) {
  16669. this._buffer = null;
  16670. }
  16671. };
  16672. Object.defineProperty(VertexBuffer, "PositionKind", {
  16673. get: function () {
  16674. return VertexBuffer._PositionKind;
  16675. },
  16676. enumerable: true,
  16677. configurable: true
  16678. });
  16679. Object.defineProperty(VertexBuffer, "NormalKind", {
  16680. get: function () {
  16681. return VertexBuffer._NormalKind;
  16682. },
  16683. enumerable: true,
  16684. configurable: true
  16685. });
  16686. Object.defineProperty(VertexBuffer, "UVKind", {
  16687. get: function () {
  16688. return VertexBuffer._UVKind;
  16689. },
  16690. enumerable: true,
  16691. configurable: true
  16692. });
  16693. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16694. get: function () {
  16695. return VertexBuffer._UV2Kind;
  16696. },
  16697. enumerable: true,
  16698. configurable: true
  16699. });
  16700. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16701. get: function () {
  16702. return VertexBuffer._UV3Kind;
  16703. },
  16704. enumerable: true,
  16705. configurable: true
  16706. });
  16707. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16708. get: function () {
  16709. return VertexBuffer._UV4Kind;
  16710. },
  16711. enumerable: true,
  16712. configurable: true
  16713. });
  16714. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16715. get: function () {
  16716. return VertexBuffer._UV5Kind;
  16717. },
  16718. enumerable: true,
  16719. configurable: true
  16720. });
  16721. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16722. get: function () {
  16723. return VertexBuffer._UV6Kind;
  16724. },
  16725. enumerable: true,
  16726. configurable: true
  16727. });
  16728. Object.defineProperty(VertexBuffer, "ColorKind", {
  16729. get: function () {
  16730. return VertexBuffer._ColorKind;
  16731. },
  16732. enumerable: true,
  16733. configurable: true
  16734. });
  16735. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16736. get: function () {
  16737. return VertexBuffer._MatricesIndicesKind;
  16738. },
  16739. enumerable: true,
  16740. configurable: true
  16741. });
  16742. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16743. get: function () {
  16744. return VertexBuffer._MatricesWeightsKind;
  16745. },
  16746. enumerable: true,
  16747. configurable: true
  16748. });
  16749. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16750. get: function () {
  16751. return VertexBuffer._MatricesIndicesExtraKind;
  16752. },
  16753. enumerable: true,
  16754. configurable: true
  16755. });
  16756. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16757. get: function () {
  16758. return VertexBuffer._MatricesWeightsExtraKind;
  16759. },
  16760. enumerable: true,
  16761. configurable: true
  16762. });
  16763. // Enums
  16764. VertexBuffer._PositionKind = "position";
  16765. VertexBuffer._NormalKind = "normal";
  16766. VertexBuffer._UVKind = "uv";
  16767. VertexBuffer._UV2Kind = "uv2";
  16768. VertexBuffer._UV3Kind = "uv3";
  16769. VertexBuffer._UV4Kind = "uv4";
  16770. VertexBuffer._UV5Kind = "uv5";
  16771. VertexBuffer._UV6Kind = "uv6";
  16772. VertexBuffer._ColorKind = "color";
  16773. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16774. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16775. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16776. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16777. return VertexBuffer;
  16778. })();
  16779. BABYLON.VertexBuffer = VertexBuffer;
  16780. })(BABYLON || (BABYLON = {}));
  16781. var BABYLON;
  16782. (function (BABYLON) {
  16783. /**
  16784. * Creates an instance based on a source mesh.
  16785. */
  16786. var InstancedMesh = (function (_super) {
  16787. __extends(InstancedMesh, _super);
  16788. function InstancedMesh(name, source) {
  16789. _super.call(this, name, source.getScene());
  16790. source.instances.push(this);
  16791. this._sourceMesh = source;
  16792. this.position.copyFrom(source.position);
  16793. this.rotation.copyFrom(source.rotation);
  16794. this.scaling.copyFrom(source.scaling);
  16795. if (source.rotationQuaternion) {
  16796. this.rotationQuaternion = source.rotationQuaternion.clone();
  16797. }
  16798. this.infiniteDistance = source.infiniteDistance;
  16799. this.setPivotMatrix(source.getPivotMatrix());
  16800. this.refreshBoundingInfo();
  16801. this._syncSubMeshes();
  16802. }
  16803. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16804. // Methods
  16805. get: function () {
  16806. return this._sourceMesh.receiveShadows;
  16807. },
  16808. enumerable: true,
  16809. configurable: true
  16810. });
  16811. Object.defineProperty(InstancedMesh.prototype, "material", {
  16812. get: function () {
  16813. return this._sourceMesh.material;
  16814. },
  16815. enumerable: true,
  16816. configurable: true
  16817. });
  16818. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16819. get: function () {
  16820. return this._sourceMesh.visibility;
  16821. },
  16822. enumerable: true,
  16823. configurable: true
  16824. });
  16825. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16826. get: function () {
  16827. return this._sourceMesh.skeleton;
  16828. },
  16829. enumerable: true,
  16830. configurable: true
  16831. });
  16832. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16833. get: function () {
  16834. return this._sourceMesh.renderingGroupId;
  16835. },
  16836. enumerable: true,
  16837. configurable: true
  16838. });
  16839. InstancedMesh.prototype.getTotalVertices = function () {
  16840. return this._sourceMesh.getTotalVertices();
  16841. };
  16842. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16843. get: function () {
  16844. return this._sourceMesh;
  16845. },
  16846. enumerable: true,
  16847. configurable: true
  16848. });
  16849. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16850. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16851. };
  16852. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16853. return this._sourceMesh.isVerticesDataPresent(kind);
  16854. };
  16855. InstancedMesh.prototype.getIndices = function () {
  16856. return this._sourceMesh.getIndices();
  16857. };
  16858. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16859. get: function () {
  16860. return this._sourceMesh._positions;
  16861. },
  16862. enumerable: true,
  16863. configurable: true
  16864. });
  16865. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16866. var meshBB = this._sourceMesh.getBoundingInfo();
  16867. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16868. this._updateBoundingInfo();
  16869. };
  16870. InstancedMesh.prototype._preActivate = function () {
  16871. if (this._currentLOD) {
  16872. this._currentLOD._preActivate();
  16873. }
  16874. };
  16875. InstancedMesh.prototype._activate = function (renderId) {
  16876. if (this._currentLOD) {
  16877. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16878. }
  16879. };
  16880. InstancedMesh.prototype.getLOD = function (camera) {
  16881. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16882. if (this._currentLOD === this.sourceMesh) {
  16883. return this;
  16884. }
  16885. return this._currentLOD;
  16886. };
  16887. InstancedMesh.prototype._syncSubMeshes = function () {
  16888. this.releaseSubMeshes();
  16889. if (this._sourceMesh.subMeshes) {
  16890. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16891. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16892. }
  16893. }
  16894. };
  16895. InstancedMesh.prototype._generatePointsArray = function () {
  16896. return this._sourceMesh._generatePointsArray();
  16897. };
  16898. // Clone
  16899. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16900. var result = this._sourceMesh.createInstance(name);
  16901. // Deep copy
  16902. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  16903. // Bounding info
  16904. this.refreshBoundingInfo();
  16905. // Parent
  16906. if (newParent) {
  16907. result.parent = newParent;
  16908. }
  16909. if (!doNotCloneChildren) {
  16910. // Children
  16911. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16912. var mesh = this.getScene().meshes[index];
  16913. if (mesh.parent === this) {
  16914. mesh.clone(mesh.name, result);
  16915. }
  16916. }
  16917. }
  16918. result.computeWorldMatrix(true);
  16919. return result;
  16920. };
  16921. // Dispoe
  16922. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16923. // Remove from mesh
  16924. var index = this._sourceMesh.instances.indexOf(this);
  16925. this._sourceMesh.instances.splice(index, 1);
  16926. _super.prototype.dispose.call(this, doNotRecurse);
  16927. };
  16928. return InstancedMesh;
  16929. })(BABYLON.AbstractMesh);
  16930. BABYLON.InstancedMesh = InstancedMesh;
  16931. })(BABYLON || (BABYLON = {}));
  16932. var BABYLON;
  16933. (function (BABYLON) {
  16934. var _InstancesBatch = (function () {
  16935. function _InstancesBatch() {
  16936. this.mustReturn = false;
  16937. this.visibleInstances = new Array();
  16938. this.renderSelf = new Array();
  16939. }
  16940. return _InstancesBatch;
  16941. })();
  16942. BABYLON._InstancesBatch = _InstancesBatch;
  16943. var Mesh = (function (_super) {
  16944. __extends(Mesh, _super);
  16945. /**
  16946. * @constructor
  16947. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16948. * @param {Scene} scene - The scene to add this mesh to.
  16949. * @param {Node} parent - The parent of this mesh, if it has one
  16950. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16951. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16952. * When false, achieved by calling a clone(), also passing False.
  16953. * This will make creation of children, recursive.
  16954. */
  16955. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16956. if (parent === void 0) { parent = null; }
  16957. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16958. _super.call(this, name, scene);
  16959. // Events
  16960. /**
  16961. * An event triggered before rendering the mesh
  16962. * @type {BABYLON.Observable}
  16963. */
  16964. this.onBeforeRenderObservable = new BABYLON.Observable();
  16965. /**
  16966. * An event triggered after rendering the mesh
  16967. * @type {BABYLON.Observable}
  16968. */
  16969. this.onAfterRenderObservable = new BABYLON.Observable();
  16970. /**
  16971. * An event triggered before drawing the mesh
  16972. * @type {BABYLON.Observable}
  16973. */
  16974. this.onBeforeDrawObservable = new BABYLON.Observable();
  16975. // Members
  16976. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16977. this.instances = new Array();
  16978. this._LODLevels = new Array();
  16979. this._visibleInstances = {};
  16980. this._renderIdForInstances = new Array();
  16981. this._batchCache = new _InstancesBatch();
  16982. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16983. this._sideOrientation = Mesh._DEFAULTSIDE;
  16984. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16985. if (source) {
  16986. // Geometry
  16987. if (source._geometry) {
  16988. source._geometry.applyToMesh(this);
  16989. }
  16990. // Deep copy
  16991. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16992. // Pivot
  16993. this.setPivotMatrix(source.getPivotMatrix());
  16994. this.id = name + "." + source.id;
  16995. // Material
  16996. this.material = source.material;
  16997. var index;
  16998. if (!doNotCloneChildren) {
  16999. // Children
  17000. for (index = 0; index < scene.meshes.length; index++) {
  17001. var mesh = scene.meshes[index];
  17002. if (mesh.parent === source) {
  17003. // doNotCloneChildren is always going to be False
  17004. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17005. }
  17006. }
  17007. }
  17008. // Physics clone
  17009. var physicsEngine = this.getScene().getPhysicsEngine();
  17010. if (clonePhysicsImpostor && physicsEngine) {
  17011. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17012. if (impostor) {
  17013. this.physicsImpostor = impostor.clone(this);
  17014. }
  17015. }
  17016. // Particles
  17017. for (index = 0; index < scene.particleSystems.length; index++) {
  17018. var system = scene.particleSystems[index];
  17019. if (system.emitter === source) {
  17020. system.clone(system.name, this);
  17021. }
  17022. }
  17023. this.computeWorldMatrix(true);
  17024. }
  17025. // Parent
  17026. if (parent !== null) {
  17027. this.parent = parent;
  17028. }
  17029. }
  17030. Object.defineProperty(Mesh, "FRONTSIDE", {
  17031. /**
  17032. * Mesh side orientation : usually the external or front surface
  17033. */
  17034. get: function () {
  17035. return Mesh._FRONTSIDE;
  17036. },
  17037. enumerable: true,
  17038. configurable: true
  17039. });
  17040. Object.defineProperty(Mesh, "BACKSIDE", {
  17041. /**
  17042. * Mesh side orientation : usually the internal or back surface
  17043. */
  17044. get: function () {
  17045. return Mesh._BACKSIDE;
  17046. },
  17047. enumerable: true,
  17048. configurable: true
  17049. });
  17050. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17051. /**
  17052. * Mesh side orientation : both internal and external or front and back surfaces
  17053. */
  17054. get: function () {
  17055. return Mesh._DOUBLESIDE;
  17056. },
  17057. enumerable: true,
  17058. configurable: true
  17059. });
  17060. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17061. /**
  17062. * Mesh side orientation : by default, `FRONTSIDE`
  17063. */
  17064. get: function () {
  17065. return Mesh._DEFAULTSIDE;
  17066. },
  17067. enumerable: true,
  17068. configurable: true
  17069. });
  17070. Object.defineProperty(Mesh, "NO_CAP", {
  17071. /**
  17072. * Mesh cap setting : no cap
  17073. */
  17074. get: function () {
  17075. return Mesh._NO_CAP;
  17076. },
  17077. enumerable: true,
  17078. configurable: true
  17079. });
  17080. Object.defineProperty(Mesh, "CAP_START", {
  17081. /**
  17082. * Mesh cap setting : one cap at the beginning of the mesh
  17083. */
  17084. get: function () {
  17085. return Mesh._CAP_START;
  17086. },
  17087. enumerable: true,
  17088. configurable: true
  17089. });
  17090. Object.defineProperty(Mesh, "CAP_END", {
  17091. /**
  17092. * Mesh cap setting : one cap at the end of the mesh
  17093. */
  17094. get: function () {
  17095. return Mesh._CAP_END;
  17096. },
  17097. enumerable: true,
  17098. configurable: true
  17099. });
  17100. Object.defineProperty(Mesh, "CAP_ALL", {
  17101. /**
  17102. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  17103. */
  17104. get: function () {
  17105. return Mesh._CAP_ALL;
  17106. },
  17107. enumerable: true,
  17108. configurable: true
  17109. });
  17110. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  17111. set: function (callback) {
  17112. if (this._onBeforeDrawObserver) {
  17113. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  17114. }
  17115. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  17116. },
  17117. enumerable: true,
  17118. configurable: true
  17119. });
  17120. // Methods
  17121. /**
  17122. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17123. */
  17124. Mesh.prototype.toString = function (fullDetails) {
  17125. var ret = _super.prototype.toString.call(this, fullDetails);
  17126. ret += ", n vertices: " + this.getTotalVertices();
  17127. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  17128. if (this.animations) {
  17129. for (var i = 0; i < this.animations.length; i++) {
  17130. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17131. }
  17132. }
  17133. if (fullDetails) {
  17134. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  17135. }
  17136. return ret;
  17137. };
  17138. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  17139. get: function () {
  17140. return this._LODLevels.length > 0;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. Mesh.prototype._sortLODLevels = function () {
  17146. this._LODLevels.sort(function (a, b) {
  17147. if (a.distance < b.distance) {
  17148. return 1;
  17149. }
  17150. if (a.distance > b.distance) {
  17151. return -1;
  17152. }
  17153. return 0;
  17154. });
  17155. };
  17156. /**
  17157. * Add a mesh as LOD level triggered at the given distance.
  17158. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17159. * @param {number} distance - the distance from the center of the object to show this level
  17160. * @param {Mesh} mesh - the mesh to be added as LOD level
  17161. * @return {Mesh} this mesh (for chaining)
  17162. */
  17163. Mesh.prototype.addLODLevel = function (distance, mesh) {
  17164. if (mesh && mesh._masterMesh) {
  17165. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  17166. return this;
  17167. }
  17168. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  17169. this._LODLevels.push(level);
  17170. if (mesh) {
  17171. mesh._masterMesh = this;
  17172. }
  17173. this._sortLODLevels();
  17174. return this;
  17175. };
  17176. /**
  17177. * Returns the LOD level mesh at the passed distance or null if not found.
  17178. * It is related to the method `addLODLevel(distance, mesh)`.
  17179. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17180. */
  17181. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  17182. for (var index = 0; index < this._LODLevels.length; index++) {
  17183. var level = this._LODLevels[index];
  17184. if (level.distance === distance) {
  17185. return level.mesh;
  17186. }
  17187. }
  17188. return null;
  17189. };
  17190. /**
  17191. * Remove a mesh from the LOD array
  17192. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17193. * @param {Mesh} mesh - the mesh to be removed.
  17194. * @return {Mesh} this mesh (for chaining)
  17195. */
  17196. Mesh.prototype.removeLODLevel = function (mesh) {
  17197. for (var index = 0; index < this._LODLevels.length; index++) {
  17198. if (this._LODLevels[index].mesh === mesh) {
  17199. this._LODLevels.splice(index, 1);
  17200. if (mesh) {
  17201. mesh._masterMesh = null;
  17202. }
  17203. }
  17204. }
  17205. this._sortLODLevels();
  17206. return this;
  17207. };
  17208. /**
  17209. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17210. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17211. */
  17212. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17213. if (!this._LODLevels || this._LODLevels.length === 0) {
  17214. return this;
  17215. }
  17216. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  17217. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  17218. if (this.onLODLevelSelection) {
  17219. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  17220. }
  17221. return this;
  17222. }
  17223. for (var index = 0; index < this._LODLevels.length; index++) {
  17224. var level = this._LODLevels[index];
  17225. if (level.distance < distanceToCamera) {
  17226. if (level.mesh) {
  17227. level.mesh._preActivate();
  17228. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17229. }
  17230. if (this.onLODLevelSelection) {
  17231. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  17232. }
  17233. return level.mesh;
  17234. }
  17235. }
  17236. if (this.onLODLevelSelection) {
  17237. this.onLODLevelSelection(distanceToCamera, this, this);
  17238. }
  17239. return this;
  17240. };
  17241. Object.defineProperty(Mesh.prototype, "geometry", {
  17242. /**
  17243. * Returns the mesh internal `Geometry` object.
  17244. */
  17245. get: function () {
  17246. return this._geometry;
  17247. },
  17248. enumerable: true,
  17249. configurable: true
  17250. });
  17251. /**
  17252. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17253. */
  17254. Mesh.prototype.getTotalVertices = function () {
  17255. if (!this._geometry) {
  17256. return 0;
  17257. }
  17258. return this._geometry.getTotalVertices();
  17259. };
  17260. /**
  17261. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17262. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17263. * Returns null if the mesh has no geometry or no vertex buffer.
  17264. * Possible `kind` values :
  17265. * - BABYLON.VertexBuffer.PositionKind
  17266. * - BABYLON.VertexBuffer.UVKind
  17267. * - BABYLON.VertexBuffer.UV2Kind
  17268. * - BABYLON.VertexBuffer.UV3Kind
  17269. * - BABYLON.VertexBuffer.UV4Kind
  17270. * - BABYLON.VertexBuffer.UV5Kind
  17271. * - BABYLON.VertexBuffer.UV6Kind
  17272. * - BABYLON.VertexBuffer.ColorKind
  17273. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17274. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17275. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17276. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17277. */
  17278. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17279. if (!this._geometry) {
  17280. return null;
  17281. }
  17282. return this._geometry.getVerticesData(kind, copyWhenShared);
  17283. };
  17284. /**
  17285. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  17286. * Returns `undefined` if the mesh has no geometry.
  17287. * Possible `kind` values :
  17288. * - BABYLON.VertexBuffer.PositionKind
  17289. * - BABYLON.VertexBuffer.UVKind
  17290. * - BABYLON.VertexBuffer.UV2Kind
  17291. * - BABYLON.VertexBuffer.UV3Kind
  17292. * - BABYLON.VertexBuffer.UV4Kind
  17293. * - BABYLON.VertexBuffer.UV5Kind
  17294. * - BABYLON.VertexBuffer.UV6Kind
  17295. * - BABYLON.VertexBuffer.ColorKind
  17296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17300. */
  17301. Mesh.prototype.getVertexBuffer = function (kind) {
  17302. if (!this._geometry) {
  17303. return undefined;
  17304. }
  17305. return this._geometry.getVertexBuffer(kind);
  17306. };
  17307. /**
  17308. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17309. * Possible `kind` values :
  17310. * - BABYLON.VertexBuffer.PositionKind
  17311. * - BABYLON.VertexBuffer.UVKind
  17312. * - BABYLON.VertexBuffer.UV2Kind
  17313. * - BABYLON.VertexBuffer.UV3Kind
  17314. * - BABYLON.VertexBuffer.UV4Kind
  17315. * - BABYLON.VertexBuffer.UV5Kind
  17316. * - BABYLON.VertexBuffer.UV6Kind
  17317. * - BABYLON.VertexBuffer.ColorKind
  17318. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17319. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17320. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17321. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17322. */
  17323. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17324. if (!this._geometry) {
  17325. if (this._delayInfo) {
  17326. return this._delayInfo.indexOf(kind) !== -1;
  17327. }
  17328. return false;
  17329. }
  17330. return this._geometry.isVerticesDataPresent(kind);
  17331. };
  17332. /**
  17333. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17334. * Possible `kind` values :
  17335. * - BABYLON.VertexBuffer.PositionKind
  17336. * - BABYLON.VertexBuffer.UVKind
  17337. * - BABYLON.VertexBuffer.UV2Kind
  17338. * - BABYLON.VertexBuffer.UV3Kind
  17339. * - BABYLON.VertexBuffer.UV4Kind
  17340. * - BABYLON.VertexBuffer.UV5Kind
  17341. * - BABYLON.VertexBuffer.UV6Kind
  17342. * - BABYLON.VertexBuffer.ColorKind
  17343. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17344. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17345. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17346. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17347. */
  17348. Mesh.prototype.getVerticesDataKinds = function () {
  17349. if (!this._geometry) {
  17350. var result = [];
  17351. if (this._delayInfo) {
  17352. for (var kind in this._delayInfo) {
  17353. result.push(kind);
  17354. }
  17355. }
  17356. return result;
  17357. }
  17358. return this._geometry.getVerticesDataKinds();
  17359. };
  17360. /**
  17361. * Returns a positive integer : the total number of indices in this mesh geometry.
  17362. * Returns zero if the mesh has no geometry.
  17363. */
  17364. Mesh.prototype.getTotalIndices = function () {
  17365. if (!this._geometry) {
  17366. return 0;
  17367. }
  17368. return this._geometry.getTotalIndices();
  17369. };
  17370. /**
  17371. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17372. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17373. * Returns an empty array if the mesh has no geometry.
  17374. */
  17375. Mesh.prototype.getIndices = function (copyWhenShared) {
  17376. if (!this._geometry) {
  17377. return [];
  17378. }
  17379. return this._geometry.getIndices(copyWhenShared);
  17380. };
  17381. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17382. get: function () {
  17383. return this._masterMesh !== null && this._masterMesh !== undefined;
  17384. },
  17385. enumerable: true,
  17386. configurable: true
  17387. });
  17388. /**
  17389. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17390. */
  17391. Mesh.prototype.isReady = function () {
  17392. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17393. return false;
  17394. }
  17395. return _super.prototype.isReady.call(this);
  17396. };
  17397. /**
  17398. * Boolean : true if the mesh has been disposed.
  17399. */
  17400. Mesh.prototype.isDisposed = function () {
  17401. return this._isDisposed;
  17402. };
  17403. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17404. get: function () {
  17405. return this._sideOrientation;
  17406. },
  17407. /**
  17408. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17409. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17410. */
  17411. set: function (sideO) {
  17412. this._sideOrientation = sideO;
  17413. },
  17414. enumerable: true,
  17415. configurable: true
  17416. });
  17417. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17418. /**
  17419. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17420. * This property is pertinent only for updatable parametric shapes.
  17421. */
  17422. get: function () {
  17423. return this._areNormalsFrozen;
  17424. },
  17425. enumerable: true,
  17426. configurable: true
  17427. });
  17428. /**
  17429. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17430. * It has no effect at all on other shapes.
  17431. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17432. */
  17433. Mesh.prototype.freezeNormals = function () {
  17434. this._areNormalsFrozen = true;
  17435. };
  17436. /**
  17437. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17438. * It has no effect at all on other shapes.
  17439. * It reactivates the mesh normals computation if it was previously frozen.
  17440. */
  17441. Mesh.prototype.unfreezeNormals = function () {
  17442. this._areNormalsFrozen = false;
  17443. };
  17444. // Methods
  17445. Mesh.prototype._preActivate = function () {
  17446. var sceneRenderId = this.getScene().getRenderId();
  17447. if (this._preActivateId === sceneRenderId) {
  17448. return;
  17449. }
  17450. this._preActivateId = sceneRenderId;
  17451. this._visibleInstances = null;
  17452. };
  17453. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17454. if (this._visibleInstances) {
  17455. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17456. }
  17457. };
  17458. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17459. if (!this._visibleInstances) {
  17460. this._visibleInstances = {};
  17461. this._visibleInstances.defaultRenderId = renderId;
  17462. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17463. }
  17464. if (!this._visibleInstances[renderId]) {
  17465. this._visibleInstances[renderId] = new Array();
  17466. }
  17467. this._visibleInstances[renderId].push(instance);
  17468. };
  17469. /**
  17470. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17471. * This means the mesh underlying bounding box and sphere are recomputed.
  17472. */
  17473. Mesh.prototype.refreshBoundingInfo = function () {
  17474. if (this._boundingInfo.isLocked) {
  17475. return;
  17476. }
  17477. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17478. if (data) {
  17479. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17480. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17481. }
  17482. if (this.subMeshes) {
  17483. for (var index = 0; index < this.subMeshes.length; index++) {
  17484. this.subMeshes[index].refreshBoundingInfo();
  17485. }
  17486. }
  17487. this._updateBoundingInfo();
  17488. };
  17489. Mesh.prototype._createGlobalSubMesh = function () {
  17490. var totalVertices = this.getTotalVertices();
  17491. if (!totalVertices || !this.getIndices()) {
  17492. return null;
  17493. }
  17494. this.releaseSubMeshes();
  17495. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17496. };
  17497. Mesh.prototype.subdivide = function (count) {
  17498. if (count < 1) {
  17499. return;
  17500. }
  17501. var totalIndices = this.getTotalIndices();
  17502. var subdivisionSize = (totalIndices / count) | 0;
  17503. var offset = 0;
  17504. // Ensure that subdivisionSize is a multiple of 3
  17505. while (subdivisionSize % 3 !== 0) {
  17506. subdivisionSize++;
  17507. }
  17508. this.releaseSubMeshes();
  17509. for (var index = 0; index < count; index++) {
  17510. if (offset >= totalIndices) {
  17511. break;
  17512. }
  17513. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17514. offset += subdivisionSize;
  17515. }
  17516. this.synchronizeInstances();
  17517. };
  17518. /**
  17519. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17520. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17521. * The `data` are either a numeric array either a Float32Array.
  17522. * The parameter `updatable` is passed as is to the underlying `Geometry` object constructor (if initianilly none) or updater.
  17523. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  17524. * Note that a new underlying `VertexBuffer` object is created each call.
  17525. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17526. *
  17527. * Possible `kind` values :
  17528. * - BABYLON.VertexBuffer.PositionKind
  17529. * - BABYLON.VertexBuffer.UVKind
  17530. * - BABYLON.VertexBuffer.UV2Kind
  17531. * - BABYLON.VertexBuffer.UV3Kind
  17532. * - BABYLON.VertexBuffer.UV4Kind
  17533. * - BABYLON.VertexBuffer.UV5Kind
  17534. * - BABYLON.VertexBuffer.UV6Kind
  17535. * - BABYLON.VertexBuffer.ColorKind
  17536. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17537. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17538. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17539. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17540. */
  17541. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17542. if (!this._geometry) {
  17543. var vertexData = new BABYLON.VertexData();
  17544. vertexData.set(data, kind);
  17545. var scene = this.getScene();
  17546. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17547. }
  17548. else {
  17549. this._geometry.setVerticesData(kind, data, updatable, stride);
  17550. }
  17551. };
  17552. /**
  17553. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17554. * If the mesh has no geometry, it is simply returned as it is.
  17555. * The `data` are either a numeric array either a Float32Array.
  17556. * No new underlying `VertexBuffer` object is created.
  17557. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17558. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17559. *
  17560. * Possible `kind` values :
  17561. * - BABYLON.VertexBuffer.PositionKind
  17562. * - BABYLON.VertexBuffer.UVKind
  17563. * - BABYLON.VertexBuffer.UV2Kind
  17564. * - BABYLON.VertexBuffer.UV3Kind
  17565. * - BABYLON.VertexBuffer.UV4Kind
  17566. * - BABYLON.VertexBuffer.UV5Kind
  17567. * - BABYLON.VertexBuffer.UV6Kind
  17568. * - BABYLON.VertexBuffer.ColorKind
  17569. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17570. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17571. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17572. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17573. */
  17574. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17575. if (!this._geometry) {
  17576. return;
  17577. }
  17578. if (!makeItUnique) {
  17579. this._geometry.updateVerticesData(kind, data, updateExtends);
  17580. }
  17581. else {
  17582. this.makeGeometryUnique();
  17583. this.updateVerticesData(kind, data, updateExtends, false);
  17584. }
  17585. };
  17586. /**
  17587. * Deprecated since BabylonJS v2.3
  17588. */
  17589. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17590. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17591. if (!this._geometry) {
  17592. return;
  17593. }
  17594. if (!makeItUnique) {
  17595. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17596. }
  17597. else {
  17598. this.makeGeometryUnique();
  17599. this.updateVerticesDataDirectly(kind, data, offset, false);
  17600. }
  17601. };
  17602. /**
  17603. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17604. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17605. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17606. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17607. */
  17608. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17609. if (computeNormals === void 0) { computeNormals = true; }
  17610. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17611. positionFunction(positions);
  17612. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17613. if (computeNormals) {
  17614. var indices = this.getIndices();
  17615. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17616. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17617. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17618. }
  17619. };
  17620. Mesh.prototype.makeGeometryUnique = function () {
  17621. if (!this._geometry) {
  17622. return;
  17623. }
  17624. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17625. geometry.applyToMesh(this);
  17626. };
  17627. /**
  17628. * Sets the mesh indices.
  17629. * Expects an array populated with integers or a Int32Array.
  17630. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17631. * This method creates a new index buffer each call.
  17632. */
  17633. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17634. if (!this._geometry) {
  17635. var vertexData = new BABYLON.VertexData();
  17636. vertexData.indices = indices;
  17637. var scene = this.getScene();
  17638. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17639. }
  17640. else {
  17641. this._geometry.setIndices(indices, totalVertices);
  17642. }
  17643. };
  17644. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17645. var engine = this.getScene().getEngine();
  17646. // Wireframe
  17647. var indexToBind;
  17648. if (this._unIndexed) {
  17649. indexToBind = null;
  17650. }
  17651. else {
  17652. switch (fillMode) {
  17653. case BABYLON.Material.PointFillMode:
  17654. indexToBind = null;
  17655. break;
  17656. case BABYLON.Material.WireFrameFillMode:
  17657. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17658. break;
  17659. default:
  17660. case BABYLON.Material.TriangleFillMode:
  17661. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17662. break;
  17663. }
  17664. }
  17665. // VBOs
  17666. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17667. };
  17668. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17669. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17670. return;
  17671. }
  17672. this.onBeforeDrawObservable.notifyObservers(this);
  17673. var engine = this.getScene().getEngine();
  17674. // Draw order
  17675. switch (fillMode) {
  17676. case BABYLON.Material.PointFillMode:
  17677. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17678. break;
  17679. case BABYLON.Material.WireFrameFillMode:
  17680. if (this._unIndexed) {
  17681. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17682. }
  17683. else {
  17684. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17685. }
  17686. break;
  17687. default:
  17688. if (this._unIndexed) {
  17689. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17690. }
  17691. else {
  17692. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17693. }
  17694. }
  17695. };
  17696. /**
  17697. * Registers for this mesh a javascript function called just before the rendering process.
  17698. * This function is passed the current mesh and doesn't return anything.
  17699. */
  17700. Mesh.prototype.registerBeforeRender = function (func) {
  17701. this.onBeforeRenderObservable.add(func);
  17702. };
  17703. /**
  17704. * Disposes a previously registered javascript function called before the rendering.
  17705. * This function is passed the current mesh and doesn't return anything.
  17706. */
  17707. Mesh.prototype.unregisterBeforeRender = function (func) {
  17708. this.onBeforeRenderObservable.removeCallback(func);
  17709. };
  17710. /**
  17711. * Registers for this mesh a javascript function called just after the rendering is complete.
  17712. * This function is passed the current mesh and doesn't return anything.
  17713. */
  17714. Mesh.prototype.registerAfterRender = function (func) {
  17715. this.onAfterRenderObservable.add(func);
  17716. };
  17717. /**
  17718. * Disposes a previously registered javascript function called after the rendering.
  17719. * This function is passed the current mesh and doesn't return anything.
  17720. */
  17721. Mesh.prototype.unregisterAfterRender = function (func) {
  17722. this.onAfterRenderObservable.removeCallback(func);
  17723. };
  17724. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17725. var scene = this.getScene();
  17726. this._batchCache.mustReturn = false;
  17727. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17728. this._batchCache.visibleInstances[subMeshId] = null;
  17729. if (this._visibleInstances) {
  17730. var currentRenderId = scene.getRenderId();
  17731. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17732. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17733. var selfRenderId = this._renderId;
  17734. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17735. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17736. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17737. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17738. }
  17739. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17740. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17741. this._batchCache.mustReturn = true;
  17742. return this._batchCache;
  17743. }
  17744. if (currentRenderId !== selfRenderId) {
  17745. this._batchCache.renderSelf[subMeshId] = false;
  17746. }
  17747. }
  17748. this._renderIdForInstances[subMeshId] = currentRenderId;
  17749. }
  17750. return this._batchCache;
  17751. };
  17752. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17753. var visibleInstances = batch.visibleInstances[subMesh._id];
  17754. var matricesCount = visibleInstances.length + 1;
  17755. var bufferSize = matricesCount * 16 * 4;
  17756. while (this._instancesBufferSize < bufferSize) {
  17757. this._instancesBufferSize *= 2;
  17758. }
  17759. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17760. if (this._worldMatricesInstancesBuffer) {
  17761. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17762. }
  17763. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17764. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17765. }
  17766. var offset = 0;
  17767. var instancesCount = 0;
  17768. var world = this.getWorldMatrix();
  17769. if (batch.renderSelf[subMesh._id]) {
  17770. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17771. offset += 16;
  17772. instancesCount++;
  17773. }
  17774. if (visibleInstances) {
  17775. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17776. var instance = visibleInstances[instanceIndex];
  17777. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17778. offset += 16;
  17779. instancesCount++;
  17780. }
  17781. }
  17782. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17783. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17784. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17785. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17786. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17787. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17788. this._draw(subMesh, fillMode, instancesCount);
  17789. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17790. };
  17791. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17792. var scene = this.getScene();
  17793. var engine = scene.getEngine();
  17794. if (hardwareInstancedRendering) {
  17795. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17796. }
  17797. else {
  17798. if (batch.renderSelf[subMesh._id]) {
  17799. // Draw
  17800. if (onBeforeDraw) {
  17801. onBeforeDraw(false, this.getWorldMatrix());
  17802. }
  17803. this._draw(subMesh, fillMode);
  17804. }
  17805. if (batch.visibleInstances[subMesh._id]) {
  17806. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17807. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17808. // World
  17809. var world = instance.getWorldMatrix();
  17810. if (onBeforeDraw) {
  17811. onBeforeDraw(true, world);
  17812. }
  17813. // Draw
  17814. this._draw(subMesh, fillMode);
  17815. }
  17816. }
  17817. }
  17818. };
  17819. /**
  17820. * Triggers the draw call for the mesh.
  17821. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  17822. */
  17823. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17824. var scene = this.getScene();
  17825. // Managing instances
  17826. var batch = this._getInstancesRenderList(subMesh._id);
  17827. if (batch.mustReturn) {
  17828. return;
  17829. }
  17830. // Checking geometry state
  17831. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17832. return;
  17833. }
  17834. var callbackIndex;
  17835. this.onBeforeRenderObservable.notifyObservers(this);
  17836. var engine = scene.getEngine();
  17837. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17838. // Material
  17839. var effectiveMaterial = subMesh.getMaterial();
  17840. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17841. return;
  17842. }
  17843. // Outline - step 1
  17844. var savedDepthWrite = engine.getDepthWrite();
  17845. if (this.renderOutline) {
  17846. engine.setDepthWrite(false);
  17847. scene.getOutlineRenderer().render(subMesh, batch);
  17848. engine.setDepthWrite(savedDepthWrite);
  17849. }
  17850. effectiveMaterial._preBind();
  17851. var effect = effectiveMaterial.getEffect();
  17852. // Bind
  17853. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17854. this._bind(subMesh, effect, fillMode);
  17855. var world = this.getWorldMatrix();
  17856. effectiveMaterial.bind(world, this);
  17857. // Alpha mode
  17858. if (enableAlphaMode) {
  17859. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17860. }
  17861. // Draw
  17862. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17863. if (isInstance) {
  17864. effectiveMaterial.bindOnlyWorldMatrix(world);
  17865. }
  17866. });
  17867. // Unbind
  17868. effectiveMaterial.unbind();
  17869. // Outline - step 2
  17870. if (this.renderOutline && savedDepthWrite) {
  17871. engine.setDepthWrite(true);
  17872. engine.setColorWrite(false);
  17873. scene.getOutlineRenderer().render(subMesh, batch);
  17874. engine.setColorWrite(true);
  17875. }
  17876. // Overlay
  17877. if (this.renderOverlay) {
  17878. var currentMode = engine.getAlphaMode();
  17879. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17880. scene.getOutlineRenderer().render(subMesh, batch, true);
  17881. engine.setAlphaMode(currentMode);
  17882. }
  17883. this.onAfterRenderObservable.notifyObservers(this);
  17884. };
  17885. /**
  17886. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17887. */
  17888. Mesh.prototype.getEmittedParticleSystems = function () {
  17889. var results = new Array();
  17890. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17891. var particleSystem = this.getScene().particleSystems[index];
  17892. if (particleSystem.emitter === this) {
  17893. results.push(particleSystem);
  17894. }
  17895. }
  17896. return results;
  17897. };
  17898. /**
  17899. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17900. */
  17901. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17902. var results = new Array();
  17903. var descendants = this.getDescendants();
  17904. descendants.push(this);
  17905. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17906. var particleSystem = this.getScene().particleSystems[index];
  17907. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17908. results.push(particleSystem);
  17909. }
  17910. }
  17911. return results;
  17912. };
  17913. Mesh.prototype._checkDelayState = function () {
  17914. var _this = this;
  17915. var that = this;
  17916. var scene = this.getScene();
  17917. if (this._geometry) {
  17918. this._geometry.load(scene);
  17919. }
  17920. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17921. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17922. scene._addPendingData(that);
  17923. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17924. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17925. if (data instanceof ArrayBuffer) {
  17926. _this._delayLoadingFunction(data, _this);
  17927. }
  17928. else {
  17929. _this._delayLoadingFunction(JSON.parse(data), _this);
  17930. }
  17931. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17932. scene._removePendingData(_this);
  17933. }, function () { }, scene.database, getBinaryData);
  17934. }
  17935. };
  17936. /**
  17937. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17938. */
  17939. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17940. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17941. return false;
  17942. }
  17943. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17944. return false;
  17945. }
  17946. this._checkDelayState();
  17947. return true;
  17948. };
  17949. /**
  17950. * Sets the mesh material by the material or multiMaterial `id` property.
  17951. * The material `id` is a string identifying the material or the multiMaterial.
  17952. * This method returns nothing.
  17953. */
  17954. Mesh.prototype.setMaterialByID = function (id) {
  17955. var materials = this.getScene().materials;
  17956. var index;
  17957. for (index = 0; index < materials.length; index++) {
  17958. if (materials[index].id === id) {
  17959. this.material = materials[index];
  17960. return;
  17961. }
  17962. }
  17963. // Multi
  17964. var multiMaterials = this.getScene().multiMaterials;
  17965. for (index = 0; index < multiMaterials.length; index++) {
  17966. if (multiMaterials[index].id === id) {
  17967. this.material = multiMaterials[index];
  17968. return;
  17969. }
  17970. }
  17971. };
  17972. /**
  17973. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  17974. */
  17975. Mesh.prototype.getAnimatables = function () {
  17976. var results = [];
  17977. if (this.material) {
  17978. results.push(this.material);
  17979. }
  17980. if (this.skeleton) {
  17981. results.push(this.skeleton);
  17982. }
  17983. return results;
  17984. };
  17985. /**
  17986. * Modifies the mesh geometry according to the passed transformation matrix.
  17987. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  17988. * The mesh normals are modified accordingly the same transformation.
  17989. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  17990. * Note that, under the hood, this method sets a new VertexBuffer each call.
  17991. */
  17992. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17993. // Position
  17994. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17995. return;
  17996. }
  17997. var submeshes = this.subMeshes.splice(0);
  17998. this._resetPointsArrayCache();
  17999. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18000. var temp = [];
  18001. var index;
  18002. for (index = 0; index < data.length; index += 3) {
  18003. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18004. }
  18005. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18006. // Normals
  18007. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18008. return;
  18009. }
  18010. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18011. temp = [];
  18012. for (index = 0; index < data.length; index += 3) {
  18013. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18014. }
  18015. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18016. // flip faces?
  18017. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18018. this.flipFaces();
  18019. }
  18020. // Restore submeshes
  18021. this.releaseSubMeshes();
  18022. this.subMeshes = submeshes;
  18023. };
  18024. /**
  18025. * Modifies the mesh geometry according to its own current World Matrix.
  18026. * The mesh World Matrix is then reset.
  18027. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18028. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18029. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18030. */
  18031. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18032. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18033. this.scaling.copyFromFloats(1, 1, 1);
  18034. this.position.copyFromFloats(0, 0, 0);
  18035. this.rotation.copyFromFloats(0, 0, 0);
  18036. //only if quaternion is already set
  18037. if (this.rotationQuaternion) {
  18038. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18039. }
  18040. this._worldMatrix = BABYLON.Matrix.Identity();
  18041. };
  18042. // Cache
  18043. Mesh.prototype._resetPointsArrayCache = function () {
  18044. this._positions = null;
  18045. };
  18046. Mesh.prototype._generatePointsArray = function () {
  18047. if (this._positions)
  18048. return true;
  18049. this._positions = [];
  18050. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18051. if (!data) {
  18052. return false;
  18053. }
  18054. for (var index = 0; index < data.length; index += 3) {
  18055. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18056. }
  18057. return true;
  18058. };
  18059. /**
  18060. * Returns a new `Mesh` object generated from the current mesh properties.
  18061. * This method must not get confused with createInstance().
  18062. * The parameter `name` is a string, the name given to the new mesh.
  18063. * The optional parameter `newParent` can be any `Node` object (default `null`).
  18064. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  18065. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  18066. */
  18067. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  18068. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18069. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  18070. };
  18071. /**
  18072. * Disposes the mesh.
  18073. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  18074. */
  18075. Mesh.prototype.dispose = function (doNotRecurse) {
  18076. if (this._geometry) {
  18077. this._geometry.releaseForMesh(this, true);
  18078. }
  18079. // Instances
  18080. if (this._worldMatricesInstancesBuffer) {
  18081. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  18082. this._worldMatricesInstancesBuffer = null;
  18083. }
  18084. while (this.instances.length) {
  18085. this.instances[0].dispose();
  18086. }
  18087. _super.prototype.dispose.call(this, doNotRecurse);
  18088. };
  18089. /**
  18090. * Modifies the mesh geometry according to a displacement map.
  18091. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  18092. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18093. * This method returns nothing.
  18094. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  18095. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18096. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  18097. */
  18098. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  18099. var _this = this;
  18100. var scene = this.getScene();
  18101. var onload = function (img) {
  18102. // Getting height map data
  18103. var canvas = document.createElement("canvas");
  18104. var context = canvas.getContext("2d");
  18105. var heightMapWidth = img.width;
  18106. var heightMapHeight = img.height;
  18107. canvas.width = heightMapWidth;
  18108. canvas.height = heightMapHeight;
  18109. context.drawImage(img, 0, 0);
  18110. // Create VertexData from map data
  18111. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18112. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  18113. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  18114. //execute success callback, if set
  18115. if (onSuccess) {
  18116. onSuccess(_this);
  18117. }
  18118. };
  18119. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18120. };
  18121. /**
  18122. * Modifies the mesh geometry according to a displacementMap buffer.
  18123. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  18124. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18125. * This method returns nothing.
  18126. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  18127. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  18128. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18129. */
  18130. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  18131. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  18132. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  18133. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18134. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  18135. return;
  18136. }
  18137. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18138. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18139. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18140. var position = BABYLON.Vector3.Zero();
  18141. var normal = BABYLON.Vector3.Zero();
  18142. var uv = BABYLON.Vector2.Zero();
  18143. for (var index = 0; index < positions.length; index += 3) {
  18144. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  18145. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  18146. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  18147. // Compute height
  18148. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  18149. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  18150. var pos = (u + v * heightMapWidth) * 4;
  18151. var r = buffer[pos] / 255.0;
  18152. var g = buffer[pos + 1] / 255.0;
  18153. var b = buffer[pos + 2] / 255.0;
  18154. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18155. normal.normalize();
  18156. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  18157. position = position.add(normal);
  18158. position.toArray(positions, index);
  18159. }
  18160. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  18161. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  18162. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18163. };
  18164. /**
  18165. * Modify the mesh to get a flat shading rendering.
  18166. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  18167. * This method returns nothing.
  18168. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  18169. */
  18170. Mesh.prototype.convertToFlatShadedMesh = function () {
  18171. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  18172. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18173. var kinds = this.getVerticesDataKinds();
  18174. var vbs = [];
  18175. var data = [];
  18176. var newdata = [];
  18177. var updatableNormals = false;
  18178. var kindIndex;
  18179. var kind;
  18180. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18181. kind = kinds[kindIndex];
  18182. var vertexBuffer = this.getVertexBuffer(kind);
  18183. if (kind === BABYLON.VertexBuffer.NormalKind) {
  18184. updatableNormals = vertexBuffer.isUpdatable();
  18185. kinds.splice(kindIndex, 1);
  18186. kindIndex--;
  18187. continue;
  18188. }
  18189. vbs[kind] = vertexBuffer;
  18190. data[kind] = vbs[kind].getData();
  18191. newdata[kind] = [];
  18192. }
  18193. // Save previous submeshes
  18194. var previousSubmeshes = this.subMeshes.slice(0);
  18195. var indices = this.getIndices();
  18196. var totalIndices = this.getTotalIndices();
  18197. // Generating unique vertices per face
  18198. var index;
  18199. for (index = 0; index < totalIndices; index++) {
  18200. var vertexIndex = indices[index];
  18201. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18202. kind = kinds[kindIndex];
  18203. var stride = vbs[kind].getStrideSize();
  18204. for (var offset = 0; offset < stride; offset++) {
  18205. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18206. }
  18207. }
  18208. }
  18209. // Updating faces & normal
  18210. var normals = [];
  18211. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  18212. for (index = 0; index < totalIndices; index += 3) {
  18213. indices[index] = index;
  18214. indices[index + 1] = index + 1;
  18215. indices[index + 2] = index + 2;
  18216. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  18217. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  18218. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  18219. var p1p2 = p1.subtract(p2);
  18220. var p3p2 = p3.subtract(p2);
  18221. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18222. // Store same normals for every vertex
  18223. for (var localIndex = 0; localIndex < 3; localIndex++) {
  18224. normals.push(normal.x);
  18225. normals.push(normal.y);
  18226. normals.push(normal.z);
  18227. }
  18228. }
  18229. this.setIndices(indices);
  18230. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  18231. // Updating vertex buffers
  18232. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18233. kind = kinds[kindIndex];
  18234. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18235. }
  18236. // Updating submeshes
  18237. this.releaseSubMeshes();
  18238. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18239. var previousOne = previousSubmeshes[submeshIndex];
  18240. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18241. }
  18242. this.synchronizeInstances();
  18243. };
  18244. /**
  18245. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  18246. * In other words, more vertices, no more indices and a single bigger VBO.
  18247. * This method returns nothing.
  18248. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  18249. *
  18250. */
  18251. Mesh.prototype.convertToUnIndexedMesh = function () {
  18252. /// <summary>Remove indices by unfolding faces into buffers</summary>
  18253. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18254. var kinds = this.getVerticesDataKinds();
  18255. var vbs = [];
  18256. var data = [];
  18257. var newdata = [];
  18258. var updatableNormals = false;
  18259. var kindIndex;
  18260. var kind;
  18261. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18262. kind = kinds[kindIndex];
  18263. var vertexBuffer = this.getVertexBuffer(kind);
  18264. vbs[kind] = vertexBuffer;
  18265. data[kind] = vbs[kind].getData();
  18266. newdata[kind] = [];
  18267. }
  18268. // Save previous submeshes
  18269. var previousSubmeshes = this.subMeshes.slice(0);
  18270. var indices = this.getIndices();
  18271. var totalIndices = this.getTotalIndices();
  18272. // Generating unique vertices per face
  18273. var index;
  18274. for (index = 0; index < totalIndices; index++) {
  18275. var vertexIndex = indices[index];
  18276. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18277. kind = kinds[kindIndex];
  18278. var stride = vbs[kind].getStrideSize();
  18279. for (var offset = 0; offset < stride; offset++) {
  18280. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18281. }
  18282. }
  18283. }
  18284. // Updating indices
  18285. for (index = 0; index < totalIndices; index += 3) {
  18286. indices[index] = index;
  18287. indices[index + 1] = index + 1;
  18288. indices[index + 2] = index + 2;
  18289. }
  18290. this.setIndices(indices);
  18291. // Updating vertex buffers
  18292. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18293. kind = kinds[kindIndex];
  18294. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18295. }
  18296. // Updating submeshes
  18297. this.releaseSubMeshes();
  18298. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18299. var previousOne = previousSubmeshes[submeshIndex];
  18300. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18301. }
  18302. this._unIndexed = true;
  18303. this.synchronizeInstances();
  18304. };
  18305. /**
  18306. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  18307. * This method returns nothing.
  18308. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  18309. */
  18310. Mesh.prototype.flipFaces = function (flipNormals) {
  18311. if (flipNormals === void 0) { flipNormals = false; }
  18312. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18313. var i;
  18314. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18315. for (i = 0; i < vertex_data.normals.length; i++) {
  18316. vertex_data.normals[i] *= -1;
  18317. }
  18318. }
  18319. var temp;
  18320. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18321. // reassign indices
  18322. temp = vertex_data.indices[i + 1];
  18323. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18324. vertex_data.indices[i + 2] = temp;
  18325. }
  18326. vertex_data.applyToMesh(this);
  18327. };
  18328. // Instances
  18329. /**
  18330. * Creates a new `InstancedMesh` object from the mesh model.
  18331. * An instance shares the same properties and the same material than its model.
  18332. * Only these properties of each instance can then be set individually :
  18333. * - position
  18334. * - rotation
  18335. * - rotationQuaternion
  18336. * - setPivotMatrix
  18337. * - scaling
  18338. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  18339. * Warning : this method is not supported for `Line` mesh and `LineSystem`
  18340. */
  18341. Mesh.prototype.createInstance = function (name) {
  18342. return new BABYLON.InstancedMesh(name, this);
  18343. };
  18344. /**
  18345. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  18346. * After this call, all the mesh instances have the same submeshes than the current mesh.
  18347. * This method returns nothing.
  18348. */
  18349. Mesh.prototype.synchronizeInstances = function () {
  18350. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18351. var instance = this.instances[instanceIndex];
  18352. instance._syncSubMeshes();
  18353. }
  18354. };
  18355. /**
  18356. * Simplify the mesh according to the given array of settings.
  18357. * Function will return immediately and will simplify async. It returns nothing.
  18358. * @param settings a collection of simplification settings.
  18359. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18360. * @param type the type of simplification to run.
  18361. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18362. */
  18363. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18364. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18365. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18366. this.getScene().simplificationQueue.addTask({
  18367. settings: settings,
  18368. parallelProcessing: parallelProcessing,
  18369. mesh: this,
  18370. simplificationType: simplificationType,
  18371. successCallback: successCallback
  18372. });
  18373. };
  18374. /**
  18375. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18376. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18377. * This should be used together with the simplification to avoid disappearing triangles.
  18378. * @param successCallback an optional success callback to be called after the optimization finished.
  18379. */
  18380. Mesh.prototype.optimizeIndices = function (successCallback) {
  18381. var _this = this;
  18382. var indices = this.getIndices();
  18383. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18384. var vectorPositions = [];
  18385. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18386. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18387. }
  18388. var dupes = [];
  18389. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18390. var realPos = vectorPositions.length - 1 - iteration;
  18391. var testedPosition = vectorPositions[realPos];
  18392. for (var j = 0; j < realPos; ++j) {
  18393. var againstPosition = vectorPositions[j];
  18394. if (testedPosition.equals(againstPosition)) {
  18395. dupes[realPos] = j;
  18396. break;
  18397. }
  18398. }
  18399. }, function () {
  18400. for (var i = 0; i < indices.length; ++i) {
  18401. indices[i] = dupes[indices[i]] || indices[i];
  18402. }
  18403. //indices are now reordered
  18404. var originalSubMeshes = _this.subMeshes.slice(0);
  18405. _this.setIndices(indices);
  18406. _this.subMeshes = originalSubMeshes;
  18407. if (successCallback) {
  18408. successCallback(_this);
  18409. }
  18410. });
  18411. };
  18412. // Statics
  18413. /**
  18414. * Returns a new `Mesh` object what is a deep copy of the passed mesh.
  18415. * The parameter `parsedMesh` is the mesh to be copied.
  18416. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18417. */
  18418. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18419. var mesh = new Mesh(parsedMesh.name, scene);
  18420. mesh.id = parsedMesh.id;
  18421. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18422. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18423. if (parsedMesh.rotationQuaternion) {
  18424. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18425. }
  18426. else if (parsedMesh.rotation) {
  18427. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18428. }
  18429. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18430. if (parsedMesh.localMatrix) {
  18431. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18432. }
  18433. else if (parsedMesh.pivotMatrix) {
  18434. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18435. }
  18436. mesh.setEnabled(parsedMesh.isEnabled);
  18437. mesh.isVisible = parsedMesh.isVisible;
  18438. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18439. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18440. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18441. if (parsedMesh.applyFog !== undefined) {
  18442. mesh.applyFog = parsedMesh.applyFog;
  18443. }
  18444. if (parsedMesh.pickable !== undefined) {
  18445. mesh.isPickable = parsedMesh.pickable;
  18446. }
  18447. if (parsedMesh.alphaIndex !== undefined) {
  18448. mesh.alphaIndex = parsedMesh.alphaIndex;
  18449. }
  18450. mesh.receiveShadows = parsedMesh.receiveShadows;
  18451. mesh.billboardMode = parsedMesh.billboardMode;
  18452. if (parsedMesh.visibility !== undefined) {
  18453. mesh.visibility = parsedMesh.visibility;
  18454. }
  18455. mesh.checkCollisions = parsedMesh.checkCollisions;
  18456. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18457. // freezeWorldMatrix
  18458. if (parsedMesh.freezeWorldMatrix) {
  18459. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18460. }
  18461. // Parent
  18462. if (parsedMesh.parentId) {
  18463. mesh._waitingParentId = parsedMesh.parentId;
  18464. }
  18465. // Actions
  18466. if (parsedMesh.actions !== undefined) {
  18467. mesh._waitingActions = parsedMesh.actions;
  18468. }
  18469. // Geometry
  18470. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18471. if (parsedMesh.delayLoadingFile) {
  18472. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18473. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18474. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18475. if (parsedMesh._binaryInfo) {
  18476. mesh._binaryInfo = parsedMesh._binaryInfo;
  18477. }
  18478. mesh._delayInfo = [];
  18479. if (parsedMesh.hasUVs) {
  18480. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18481. }
  18482. if (parsedMesh.hasUVs2) {
  18483. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18484. }
  18485. if (parsedMesh.hasUVs3) {
  18486. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18487. }
  18488. if (parsedMesh.hasUVs4) {
  18489. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18490. }
  18491. if (parsedMesh.hasUVs5) {
  18492. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18493. }
  18494. if (parsedMesh.hasUVs6) {
  18495. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18496. }
  18497. if (parsedMesh.hasColors) {
  18498. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18499. }
  18500. if (parsedMesh.hasMatricesIndices) {
  18501. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18502. }
  18503. if (parsedMesh.hasMatricesWeights) {
  18504. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18505. }
  18506. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18507. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18508. mesh._checkDelayState();
  18509. }
  18510. }
  18511. else {
  18512. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18513. }
  18514. // Material
  18515. if (parsedMesh.materialId) {
  18516. mesh.setMaterialByID(parsedMesh.materialId);
  18517. }
  18518. else {
  18519. mesh.material = null;
  18520. }
  18521. // Skeleton
  18522. if (parsedMesh.skeletonId > -1) {
  18523. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18524. if (parsedMesh.numBoneInfluencers) {
  18525. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18526. }
  18527. }
  18528. // Animations
  18529. if (parsedMesh.animations) {
  18530. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18531. var parsedAnimation = parsedMesh.animations[animationIndex];
  18532. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18533. }
  18534. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18535. }
  18536. if (parsedMesh.autoAnimate) {
  18537. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18538. }
  18539. // Layer Mask
  18540. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18541. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18542. }
  18543. else {
  18544. mesh.layerMask = 0x0FFFFFFF;
  18545. }
  18546. //(Deprecated) physics
  18547. if (parsedMesh.physicsImpostor) {
  18548. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18549. mass: parsedMesh.physicsMass,
  18550. friction: parsedMesh.physicsFriction,
  18551. restitution: parsedMesh.physicsRestitution
  18552. }, scene);
  18553. }
  18554. // Instances
  18555. if (parsedMesh.instances) {
  18556. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18557. var parsedInstance = parsedMesh.instances[index];
  18558. var instance = mesh.createInstance(parsedInstance.name);
  18559. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18560. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18561. if (parsedInstance.rotationQuaternion) {
  18562. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18563. }
  18564. else if (parsedInstance.rotation) {
  18565. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18566. }
  18567. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18568. instance.checkCollisions = mesh.checkCollisions;
  18569. if (parsedMesh.animations) {
  18570. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18571. parsedAnimation = parsedMesh.animations[animationIndex];
  18572. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18573. }
  18574. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18575. }
  18576. }
  18577. }
  18578. return mesh;
  18579. };
  18580. /**
  18581. * Creates a ribbon mesh.
  18582. * Please consider using the same method from the `MeshBuilder` class instead.
  18583. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18584. *
  18585. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18586. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18587. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18588. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18589. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  18590. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  18591. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  18592. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18593. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18594. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18595. */
  18596. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18597. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18598. pathArray: pathArray,
  18599. closeArray: closeArray,
  18600. closePath: closePath,
  18601. offset: offset,
  18602. updatable: updatable,
  18603. sideOrientation: sideOrientation,
  18604. instance: instance
  18605. }, scene);
  18606. };
  18607. /**
  18608. * Creates a plane polygonal mesh. By default, this is a disc.
  18609. * Please consider using the same method from the `MeshBuilder` class instead.
  18610. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18611. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  18612. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18613. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18615. */
  18616. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18617. var options = {
  18618. radius: radius,
  18619. tessellation: tessellation,
  18620. sideOrientation: sideOrientation,
  18621. updatable: updatable
  18622. };
  18623. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18624. };
  18625. /**
  18626. * Creates a box mesh.
  18627. * Please consider using the same method from the `MeshBuilder` class instead.
  18628. * The parameter `size` sets the size (float) of each box side (default 1).
  18629. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18630. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18632. */
  18633. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18634. var options = {
  18635. size: size,
  18636. sideOrientation: sideOrientation,
  18637. updatable: updatable
  18638. };
  18639. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18640. };
  18641. /**
  18642. * Creates a sphere mesh.
  18643. * Please consider using the same method from the `MeshBuilder` class instead.
  18644. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18645. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18647. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18649. */
  18650. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18651. var options = {
  18652. segments: segments,
  18653. diameterX: diameter,
  18654. diameterY: diameter,
  18655. diameterZ: diameter,
  18656. sideOrientation: sideOrientation,
  18657. updatable: updatable
  18658. };
  18659. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18660. };
  18661. /**
  18662. * Creates a cylinder or a cone mesh.
  18663. * Please consider using the same method from the `MeshBuilder` class instead.
  18664. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18665. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18666. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  18667. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18668. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18669. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18670. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18672. */
  18673. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18674. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18675. if (scene !== undefined) {
  18676. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18677. updatable = scene;
  18678. }
  18679. scene = subdivisions;
  18680. subdivisions = 1;
  18681. }
  18682. var options = {
  18683. height: height,
  18684. diameterTop: diameterTop,
  18685. diameterBottom: diameterBottom,
  18686. tessellation: tessellation,
  18687. subdivisions: subdivisions,
  18688. sideOrientation: sideOrientation,
  18689. updatable: updatable
  18690. };
  18691. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18692. };
  18693. // Torus (Code from SharpDX.org)
  18694. /**
  18695. * Creates a torus mesh.
  18696. * Please consider using the same method from the `MeshBuilder` class instead.
  18697. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18698. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18699. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18700. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18701. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18703. */
  18704. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18705. var options = {
  18706. diameter: diameter,
  18707. thickness: thickness,
  18708. tessellation: tessellation,
  18709. sideOrientation: sideOrientation,
  18710. updatable: updatable
  18711. };
  18712. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18713. };
  18714. /**
  18715. * Creates a torus knot mesh.
  18716. * Please consider using the same method from the `MeshBuilder` class instead.
  18717. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18718. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18719. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18720. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18721. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18722. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18724. */
  18725. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18726. var options = {
  18727. radius: radius,
  18728. tube: tube,
  18729. radialSegments: radialSegments,
  18730. tubularSegments: tubularSegments,
  18731. p: p,
  18732. q: q,
  18733. sideOrientation: sideOrientation,
  18734. updatable: updatable
  18735. };
  18736. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18737. };
  18738. /**
  18739. * Creates a line mesh.
  18740. * Please consider using the same method from the `MeshBuilder` class instead.
  18741. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18742. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18743. * The parameter `points` is an array successive Vector3.
  18744. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18745. * When updating an instance, remember that only point positions can change, not the number of points.
  18746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18747. */
  18748. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18749. var options = {
  18750. points: points,
  18751. updatable: updatable,
  18752. instance: instance
  18753. };
  18754. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18755. };
  18756. /**
  18757. * Creates a dashed line mesh.
  18758. * Please consider using the same method from the `MeshBuilder` class instead.
  18759. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18760. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18761. * The parameter `points` is an array successive Vector3.
  18762. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18763. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18764. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18765. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18766. * When updating an instance, remember that only point positions can change, not the number of points.
  18767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18768. */
  18769. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18770. var options = {
  18771. points: points,
  18772. dashSize: dashSize,
  18773. gapSize: gapSize,
  18774. dashNb: dashNb,
  18775. updatable: updatable
  18776. };
  18777. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18778. };
  18779. /**
  18780. * Creates an extruded shape mesh.
  18781. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18782. * Please consider using the same method from the `MeshBuilder` class instead.
  18783. *
  18784. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18785. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18786. * extruded along the Z axis.
  18787. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18788. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  18789. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18790. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18791. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18792. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18793. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18794. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18795. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18796. */
  18797. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18798. var options = {
  18799. shape: shape,
  18800. path: path,
  18801. scale: scale,
  18802. rotation: rotation,
  18803. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18804. sideOrientation: sideOrientation,
  18805. instance: instance,
  18806. updatable: updatable
  18807. };
  18808. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18809. };
  18810. /**
  18811. * Creates an custom extruded shape mesh.
  18812. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18813. * Please consider using the same method from the `MeshBuilder` class instead.
  18814. *
  18815. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18816. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18817. * extruded along the Z axis.
  18818. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18819. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18820. * and the distance of this point from the begining of the path :
  18821. * ```rotationFunction = function(i, distance) {
  18822. * // do things
  18823. * return rotationValue; }```
  18824. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18825. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18826. * and the distance of this point from the begining of the path :
  18827. * ````scaleFunction = function(i, distance) {
  18828. * // do things
  18829. * return scaleValue;}```
  18830. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18831. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18832. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18833. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18834. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18835. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18836. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18837. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18839. */
  18840. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18841. var options = {
  18842. shape: shape,
  18843. path: path,
  18844. scaleFunction: scaleFunction,
  18845. rotationFunction: rotationFunction,
  18846. ribbonCloseArray: ribbonCloseArray,
  18847. ribbonClosePath: ribbonClosePath,
  18848. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18849. sideOrientation: sideOrientation,
  18850. instance: instance,
  18851. updatable: updatable
  18852. };
  18853. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18854. };
  18855. /**
  18856. * Creates lathe mesh.
  18857. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18858. * Please consider using the same method from the `MeshBuilder` class instead.
  18859. *
  18860. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  18861. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18862. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18863. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18864. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18865. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18867. */
  18868. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18869. var options = {
  18870. shape: shape,
  18871. radius: radius,
  18872. tessellation: tessellation,
  18873. sideOrientation: sideOrientation,
  18874. updatable: updatable
  18875. };
  18876. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18877. };
  18878. /**
  18879. * Creates a plane mesh.
  18880. * Please consider using the same method from the `MeshBuilder` class instead.
  18881. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18882. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18883. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18885. */
  18886. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18887. var options = {
  18888. size: size,
  18889. width: size,
  18890. height: size,
  18891. sideOrientation: sideOrientation,
  18892. updatable: updatable
  18893. };
  18894. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18895. };
  18896. /**
  18897. * Creates a ground mesh.
  18898. * Please consider using the same method from the `MeshBuilder` class instead.
  18899. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18900. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18902. */
  18903. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18904. var options = {
  18905. width: width,
  18906. height: height,
  18907. subdivisions: subdivisions,
  18908. updatable: updatable
  18909. };
  18910. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18911. };
  18912. /**
  18913. * Creates a tiled ground mesh.
  18914. * Please consider using the same method from the `MeshBuilder` class instead.
  18915. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18916. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18917. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18918. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18919. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18920. * numbers of subdivisions on the ground width and height of each tile.
  18921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18922. */
  18923. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18924. var options = {
  18925. xmin: xmin,
  18926. zmin: zmin,
  18927. xmax: xmax,
  18928. zmax: zmax,
  18929. subdivisions: subdivisions,
  18930. precision: precision,
  18931. updatable: updatable
  18932. };
  18933. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18934. };
  18935. /**
  18936. * Creates a ground mesh from a height map.
  18937. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18938. * Please consider using the same method from the `MeshBuilder` class instead.
  18939. * The parameter `url` sets the URL of the height map image resource.
  18940. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18941. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18942. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18943. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18944. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  18945. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18946. * return; }```
  18947. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18948. */
  18949. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18950. var options = {
  18951. width: width,
  18952. height: height,
  18953. subdivisions: subdivisions,
  18954. minHeight: minHeight,
  18955. maxHeight: maxHeight,
  18956. updatable: updatable,
  18957. onReady: onReady
  18958. };
  18959. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18960. };
  18961. /**
  18962. * Creates a tube mesh.
  18963. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18964. *
  18965. * Please consider using the same method from the `MeshBuilder` class instead.
  18966. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18967. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18968. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18969. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18970. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  18971. * It must return a radius value (positive float) :
  18972. * ```var radiusFunction = function(i, distance) {
  18973. * // do things
  18974. * return radius; }```
  18975. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18976. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  18977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18980. */
  18981. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18982. var options = {
  18983. path: path,
  18984. radius: radius,
  18985. tessellation: tessellation,
  18986. radiusFunction: radiusFunction,
  18987. arc: 1,
  18988. cap: cap,
  18989. updatable: updatable,
  18990. sideOrientation: sideOrientation,
  18991. instance: instance
  18992. };
  18993. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18994. };
  18995. /**
  18996. * Creates a polyhedron mesh.
  18997. *
  18998. * Please consider using the same method from the `MeshBuilder` class instead.
  18999. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  19000. * to choose the wanted type.
  19001. * The parameter `size` (positive float, default 1) sets the polygon size.
  19002. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19003. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  19004. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  19005. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  19006. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19007. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  19008. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19009. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19010. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19011. */
  19012. Mesh.CreatePolyhedron = function (name, options, scene) {
  19013. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19014. };
  19015. /**
  19016. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19017. * Please consider using the same method from the `MeshBuilder` class instead.
  19018. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19019. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  19020. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19021. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  19022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19023. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19025. */
  19026. Mesh.CreateIcoSphere = function (name, options, scene) {
  19027. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19028. };
  19029. /**
  19030. * Creates a decal mesh.
  19031. * Please consider using the same method from the `MeshBuilder` class instead.
  19032. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  19033. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19034. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19035. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19036. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19037. */
  19038. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19039. var options = {
  19040. position: position,
  19041. normal: normal,
  19042. size: size,
  19043. angle: angle
  19044. };
  19045. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19046. };
  19047. // Skeletons
  19048. /**
  19049. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19050. */
  19051. Mesh.prototype.setPositionsForCPUSkinning = function () {
  19052. var source;
  19053. if (!this._sourcePositions) {
  19054. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19055. this._sourcePositions = new Float32Array(source);
  19056. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  19057. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  19058. }
  19059. }
  19060. return this._sourcePositions;
  19061. };
  19062. /**
  19063. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19064. */
  19065. Mesh.prototype.setNormalsForCPUSkinning = function () {
  19066. var source;
  19067. if (!this._sourceNormals) {
  19068. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19069. this._sourceNormals = new Float32Array(source);
  19070. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  19071. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  19072. }
  19073. }
  19074. return this._sourceNormals;
  19075. };
  19076. /**
  19077. * Update the vertex buffers by applying transformation from the bones
  19078. * @param {skeleton} skeleton to apply
  19079. */
  19080. Mesh.prototype.applySkeleton = function (skeleton) {
  19081. if (!this.geometry) {
  19082. return;
  19083. }
  19084. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  19085. return;
  19086. }
  19087. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  19088. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19089. return this;
  19090. }
  19091. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19092. return this;
  19093. }
  19094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19095. return this;
  19096. }
  19097. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19098. return this;
  19099. }
  19100. if (!this._sourcePositions) {
  19101. this.setPositionsForCPUSkinning();
  19102. }
  19103. if (!this._sourceNormals) {
  19104. this.setNormalsForCPUSkinning();
  19105. }
  19106. // positionsData checks for not being Float32Array will only pass at most once
  19107. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19108. if (!(positionsData instanceof Float32Array)) {
  19109. positionsData = new Float32Array(positionsData);
  19110. }
  19111. // normalsData checks for not being Float32Array will only pass at most once
  19112. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19113. if (!(normalsData instanceof Float32Array)) {
  19114. normalsData = new Float32Array(normalsData);
  19115. }
  19116. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19117. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19118. var needExtras = this.numBoneInfluencers > 4;
  19119. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  19120. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  19121. var skeletonMatrices = skeleton.getTransformMatrices(this);
  19122. var tempVector3 = BABYLON.Vector3.Zero();
  19123. var finalMatrix = new BABYLON.Matrix();
  19124. var tempMatrix = new BABYLON.Matrix();
  19125. var matWeightIdx = 0;
  19126. var inf;
  19127. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  19128. var weight;
  19129. for (inf = 0; inf < 4; inf++) {
  19130. weight = matricesWeightsData[matWeightIdx + inf];
  19131. if (weight > 0) {
  19132. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19133. finalMatrix.addToSelf(tempMatrix);
  19134. }
  19135. else
  19136. break;
  19137. }
  19138. if (needExtras) {
  19139. for (inf = 0; inf < 4; inf++) {
  19140. weight = matricesWeightsExtraData[matWeightIdx + inf];
  19141. if (weight > 0) {
  19142. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19143. finalMatrix.addToSelf(tempMatrix);
  19144. }
  19145. else
  19146. break;
  19147. }
  19148. }
  19149. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  19150. tempVector3.toArray(positionsData, index);
  19151. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  19152. tempVector3.toArray(normalsData, index);
  19153. finalMatrix.reset();
  19154. }
  19155. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  19156. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  19157. return this;
  19158. };
  19159. // Tools
  19160. /**
  19161. * Returns an object `{min: Vector3, max: Vector3}`
  19162. * This min and max `Vector3` are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  19163. */
  19164. Mesh.MinMax = function (meshes) {
  19165. var minVector = null;
  19166. var maxVector = null;
  19167. for (var i in meshes) {
  19168. var mesh = meshes[i];
  19169. var boundingBox = mesh.getBoundingInfo().boundingBox;
  19170. if (!minVector) {
  19171. minVector = boundingBox.minimumWorld;
  19172. maxVector = boundingBox.maximumWorld;
  19173. continue;
  19174. }
  19175. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  19176. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  19177. }
  19178. return {
  19179. min: minVector,
  19180. max: maxVector
  19181. };
  19182. };
  19183. /**
  19184. * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
  19185. */
  19186. Mesh.Center = function (meshesOrMinMaxVector) {
  19187. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  19188. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  19189. };
  19190. /**
  19191. * Merge the array of meshes into a single mesh for performance reasons.
  19192. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  19193. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  19194. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  19195. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  19196. */
  19197. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  19198. if (disposeSource === void 0) { disposeSource = true; }
  19199. var index;
  19200. if (!allow32BitsIndices) {
  19201. var totalVertices = 0;
  19202. // Counting vertices
  19203. for (index = 0; index < meshes.length; index++) {
  19204. if (meshes[index]) {
  19205. totalVertices += meshes[index].getTotalVertices();
  19206. if (totalVertices > 65536) {
  19207. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  19208. return null;
  19209. }
  19210. }
  19211. }
  19212. }
  19213. // Merge
  19214. var vertexData;
  19215. var otherVertexData;
  19216. var source;
  19217. for (index = 0; index < meshes.length; index++) {
  19218. if (meshes[index]) {
  19219. meshes[index].computeWorldMatrix(true);
  19220. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  19221. otherVertexData.transform(meshes[index].getWorldMatrix());
  19222. if (vertexData) {
  19223. vertexData.merge(otherVertexData);
  19224. }
  19225. else {
  19226. vertexData = otherVertexData;
  19227. source = meshes[index];
  19228. }
  19229. }
  19230. }
  19231. if (!meshSubclass) {
  19232. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  19233. }
  19234. vertexData.applyToMesh(meshSubclass);
  19235. // Setting properties
  19236. meshSubclass.material = source.material;
  19237. meshSubclass.checkCollisions = source.checkCollisions;
  19238. // Cleaning
  19239. if (disposeSource) {
  19240. for (index = 0; index < meshes.length; index++) {
  19241. if (meshes[index]) {
  19242. meshes[index].dispose();
  19243. }
  19244. }
  19245. }
  19246. return meshSubclass;
  19247. };
  19248. // Consts
  19249. Mesh._FRONTSIDE = 0;
  19250. Mesh._BACKSIDE = 1;
  19251. Mesh._DOUBLESIDE = 2;
  19252. Mesh._DEFAULTSIDE = 0;
  19253. Mesh._NO_CAP = 0;
  19254. Mesh._CAP_START = 1;
  19255. Mesh._CAP_END = 2;
  19256. Mesh._CAP_ALL = 3;
  19257. return Mesh;
  19258. })(BABYLON.AbstractMesh);
  19259. BABYLON.Mesh = Mesh;
  19260. })(BABYLON || (BABYLON = {}));
  19261. var BABYLON;
  19262. (function (BABYLON) {
  19263. var SubMesh = (function () {
  19264. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  19265. if (createBoundingBox === void 0) { createBoundingBox = true; }
  19266. this.materialIndex = materialIndex;
  19267. this.verticesStart = verticesStart;
  19268. this.verticesCount = verticesCount;
  19269. this.indexStart = indexStart;
  19270. this.indexCount = indexCount;
  19271. this._renderId = 0;
  19272. this._mesh = mesh;
  19273. this._renderingMesh = renderingMesh || mesh;
  19274. mesh.subMeshes.push(this);
  19275. this._trianglePlanes = [];
  19276. this._id = mesh.subMeshes.length - 1;
  19277. if (createBoundingBox) {
  19278. this.refreshBoundingInfo();
  19279. mesh.computeWorldMatrix(true);
  19280. }
  19281. }
  19282. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  19283. get: function () {
  19284. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  19285. },
  19286. enumerable: true,
  19287. configurable: true
  19288. });
  19289. SubMesh.prototype.getBoundingInfo = function () {
  19290. if (this.IsGlobal) {
  19291. return this._mesh.getBoundingInfo();
  19292. }
  19293. return this._boundingInfo;
  19294. };
  19295. SubMesh.prototype.getMesh = function () {
  19296. return this._mesh;
  19297. };
  19298. SubMesh.prototype.getRenderingMesh = function () {
  19299. return this._renderingMesh;
  19300. };
  19301. SubMesh.prototype.getMaterial = function () {
  19302. var rootMaterial = this._renderingMesh.material;
  19303. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  19304. var multiMaterial = rootMaterial;
  19305. return multiMaterial.getSubMaterial(this.materialIndex);
  19306. }
  19307. if (!rootMaterial) {
  19308. return this._mesh.getScene().defaultMaterial;
  19309. }
  19310. return rootMaterial;
  19311. };
  19312. // Methods
  19313. SubMesh.prototype.refreshBoundingInfo = function () {
  19314. this._lastColliderWorldVertices = null;
  19315. if (this.IsGlobal) {
  19316. return;
  19317. }
  19318. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19319. if (!data) {
  19320. this._boundingInfo = this._mesh._boundingInfo;
  19321. return;
  19322. }
  19323. var indices = this._renderingMesh.getIndices();
  19324. var extend;
  19325. //is this the only submesh?
  19326. if (this.indexStart === 0 && this.indexCount === indices.length) {
  19327. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  19328. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  19329. }
  19330. else {
  19331. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19332. }
  19333. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19334. };
  19335. SubMesh.prototype._checkCollision = function (collider) {
  19336. return this.getBoundingInfo()._checkCollision(collider);
  19337. };
  19338. SubMesh.prototype.updateBoundingInfo = function (world) {
  19339. if (!this.getBoundingInfo()) {
  19340. this.refreshBoundingInfo();
  19341. }
  19342. this.getBoundingInfo().update(world);
  19343. };
  19344. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19345. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19346. };
  19347. SubMesh.prototype.render = function (enableAlphaMode) {
  19348. this._renderingMesh.render(this, enableAlphaMode);
  19349. };
  19350. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19351. if (!this._linesIndexBuffer) {
  19352. var linesIndices = [];
  19353. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19354. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19355. }
  19356. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19357. this.linesIndexCount = linesIndices.length;
  19358. }
  19359. return this._linesIndexBuffer;
  19360. };
  19361. SubMesh.prototype.canIntersects = function (ray) {
  19362. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19363. };
  19364. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19365. var intersectInfo = null;
  19366. // LineMesh first as it's also a Mesh...
  19367. if (this._mesh instanceof BABYLON.LinesMesh) {
  19368. var lineMesh = this._mesh;
  19369. // Line test
  19370. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19371. var p0 = positions[indices[index]];
  19372. var p1 = positions[indices[index + 1]];
  19373. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19374. if (length < 0) {
  19375. continue;
  19376. }
  19377. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19378. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19379. if (fastCheck) {
  19380. break;
  19381. }
  19382. }
  19383. }
  19384. }
  19385. else {
  19386. // Triangles test
  19387. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19388. var p0 = positions[indices[index]];
  19389. var p1 = positions[indices[index + 1]];
  19390. var p2 = positions[indices[index + 2]];
  19391. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19392. if (currentIntersectInfo) {
  19393. if (currentIntersectInfo.distance < 0) {
  19394. continue;
  19395. }
  19396. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19397. intersectInfo = currentIntersectInfo;
  19398. intersectInfo.faceId = index / 3;
  19399. if (fastCheck) {
  19400. break;
  19401. }
  19402. }
  19403. }
  19404. }
  19405. }
  19406. return intersectInfo;
  19407. };
  19408. // Clone
  19409. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19410. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19411. if (!this.IsGlobal) {
  19412. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19413. }
  19414. return result;
  19415. };
  19416. // Dispose
  19417. SubMesh.prototype.dispose = function () {
  19418. if (this._linesIndexBuffer) {
  19419. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19420. this._linesIndexBuffer = null;
  19421. }
  19422. // Remove from mesh
  19423. var index = this._mesh.subMeshes.indexOf(this);
  19424. this._mesh.subMeshes.splice(index, 1);
  19425. };
  19426. // Statics
  19427. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19428. var minVertexIndex = Number.MAX_VALUE;
  19429. var maxVertexIndex = -Number.MAX_VALUE;
  19430. renderingMesh = renderingMesh || mesh;
  19431. var indices = renderingMesh.getIndices();
  19432. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19433. var vertexIndex = indices[index];
  19434. if (vertexIndex < minVertexIndex)
  19435. minVertexIndex = vertexIndex;
  19436. if (vertexIndex > maxVertexIndex)
  19437. maxVertexIndex = vertexIndex;
  19438. }
  19439. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19440. };
  19441. return SubMesh;
  19442. })();
  19443. BABYLON.SubMesh = SubMesh;
  19444. })(BABYLON || (BABYLON = {}));
  19445. var BABYLON;
  19446. (function (BABYLON) {
  19447. var MeshBuilder = (function () {
  19448. function MeshBuilder() {
  19449. }
  19450. /**
  19451. * Creates a box mesh.
  19452. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19453. * The parameter `size` sets the size (float) of each box side (default 1).
  19454. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19455. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 `Color3` elements) and `faceUV` (an array of 6 `Vector4` elements).
  19456. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19457. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19458. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19460. */
  19461. MeshBuilder.CreateBox = function (name, options, scene) {
  19462. var box = new BABYLON.Mesh(name, scene);
  19463. var vertexData = BABYLON.VertexData.CreateBox(options);
  19464. vertexData.applyToMesh(box, options.updatable);
  19465. return box;
  19466. };
  19467. /**
  19468. * Creates a sphere mesh.
  19469. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19470. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19471. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  19472. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19473. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  19474. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  19475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19476. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19478. */
  19479. MeshBuilder.CreateSphere = function (name, options, scene) {
  19480. var sphere = new BABYLON.Mesh(name, scene);
  19481. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19482. vertexData.applyToMesh(sphere, options.updatable);
  19483. return sphere;
  19484. };
  19485. /**
  19486. * Creates a plane polygonal mesh. By default, this is a disc.
  19487. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19488. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19489. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  19490. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  19491. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19492. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19494. */
  19495. MeshBuilder.CreateDisc = function (name, options, scene) {
  19496. var disc = new BABYLON.Mesh(name, scene);
  19497. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19498. vertexData.applyToMesh(disc, options.updatable);
  19499. return disc;
  19500. };
  19501. /**
  19502. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19503. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19504. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19505. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  19506. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19507. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  19508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19511. */
  19512. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19513. var sphere = new BABYLON.Mesh(name, scene);
  19514. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19515. vertexData.applyToMesh(sphere, options.updatable);
  19516. return sphere;
  19517. };
  19518. ;
  19519. /**
  19520. * Creates a ribbon mesh.
  19521. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19522. *
  19523. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19524. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19525. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19526. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19527. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  19528. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  19529. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  19530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19533. */
  19534. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19535. var pathArray = options.pathArray;
  19536. var closeArray = options.closeArray;
  19537. var closePath = options.closePath;
  19538. var offset = options.offset;
  19539. var sideOrientation = options.sideOrientation;
  19540. var instance = options.instance;
  19541. var updatable = options.updatable;
  19542. if (instance) {
  19543. // positionFunction : ribbon case
  19544. // only pathArray and sideOrientation parameters are taken into account for positions update
  19545. var positionFunction = function (positions) {
  19546. var minlg = pathArray[0].length;
  19547. var i = 0;
  19548. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19549. for (var si = 1; si <= ns; si++) {
  19550. for (var p = 0; p < pathArray.length; p++) {
  19551. var path = pathArray[p];
  19552. var l = path.length;
  19553. minlg = (minlg < l) ? minlg : l;
  19554. var j = 0;
  19555. while (j < minlg) {
  19556. positions[i] = path[j].x;
  19557. positions[i + 1] = path[j].y;
  19558. positions[i + 2] = path[j].z;
  19559. j++;
  19560. i += 3;
  19561. }
  19562. if (instance._closePath) {
  19563. positions[i] = path[0].x;
  19564. positions[i + 1] = path[0].y;
  19565. positions[i + 2] = path[0].z;
  19566. i += 3;
  19567. }
  19568. }
  19569. }
  19570. };
  19571. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19572. positionFunction(positions);
  19573. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19574. if (!(instance.areNormalsFrozen)) {
  19575. var indices = instance.getIndices();
  19576. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19577. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19578. if (instance._closePath) {
  19579. var indexFirst = 0;
  19580. var indexLast = 0;
  19581. for (var p = 0; p < pathArray.length; p++) {
  19582. indexFirst = instance._idx[p] * 3;
  19583. if (p + 1 < pathArray.length) {
  19584. indexLast = (instance._idx[p + 1] - 1) * 3;
  19585. }
  19586. else {
  19587. indexLast = normals.length - 3;
  19588. }
  19589. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19590. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19591. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19592. normals[indexLast] = normals[indexFirst];
  19593. normals[indexLast + 1] = normals[indexFirst + 1];
  19594. normals[indexLast + 2] = normals[indexFirst + 2];
  19595. }
  19596. }
  19597. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19598. }
  19599. return instance;
  19600. }
  19601. else {
  19602. var ribbon = new BABYLON.Mesh(name, scene);
  19603. ribbon.sideOrientation = sideOrientation;
  19604. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19605. if (closePath) {
  19606. ribbon._idx = vertexData._idx;
  19607. }
  19608. ribbon._closePath = closePath;
  19609. ribbon._closeArray = closeArray;
  19610. vertexData.applyToMesh(ribbon, updatable);
  19611. return ribbon;
  19612. }
  19613. };
  19614. /**
  19615. * Creates a cylinder or a cone mesh.
  19616. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19617. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19618. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19619. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  19620. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19621. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19622. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19623. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19624. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19625. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n `Color3` elements) and `faceUV` (an array of n `Vector4` elements).
  19626. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  19627. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19628. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  19629. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  19630. * If `enclose` is false, a ring surface is one element.
  19631. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19632. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  19633. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19634. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19635. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19636. */
  19637. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19638. var cylinder = new BABYLON.Mesh(name, scene);
  19639. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19640. vertexData.applyToMesh(cylinder, options.updatable);
  19641. return cylinder;
  19642. };
  19643. /**
  19644. * Creates a torus mesh.
  19645. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19646. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19647. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19648. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19650. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19652. */
  19653. MeshBuilder.CreateTorus = function (name, options, scene) {
  19654. var torus = new BABYLON.Mesh(name, scene);
  19655. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19656. vertexData.applyToMesh(torus, options.updatable);
  19657. return torus;
  19658. };
  19659. /**
  19660. * Creates a torus knot mesh.
  19661. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19662. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19663. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19664. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19665. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19666. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19667. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19669. */
  19670. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19671. var torusKnot = new BABYLON.Mesh(name, scene);
  19672. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19673. vertexData.applyToMesh(torusKnot, options.updatable);
  19674. return torusKnot;
  19675. };
  19676. /**
  19677. * Creates a line system mesh.
  19678. * A line system is a pool of many lines gathered in a single mesh.
  19679. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19680. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  19681. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19682. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19683. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  19684. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19685. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19687. */
  19688. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19689. var instance = options.instance;
  19690. var lines = options.lines;
  19691. if (instance) {
  19692. var positionFunction = function (positions) {
  19693. var i = 0;
  19694. for (var l = 0; l < lines.length; l++) {
  19695. var points = lines[l];
  19696. for (var p = 0; p < points.length; p++) {
  19697. positions[i] = points[p].x;
  19698. positions[i + 1] = points[p].y;
  19699. positions[i + 2] = points[p].z;
  19700. i += 3;
  19701. }
  19702. }
  19703. };
  19704. instance.updateMeshPositions(positionFunction, false);
  19705. return instance;
  19706. }
  19707. // line system creation
  19708. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19709. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19710. vertexData.applyToMesh(lineSystem, options.updatable);
  19711. return lineSystem;
  19712. };
  19713. /**
  19714. * Creates a line mesh.
  19715. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19716. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19717. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19718. * The parameter `points` is an array successive Vector3.
  19719. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19720. * When updating an instance, remember that only point positions can change, not the number of points.
  19721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19722. */
  19723. MeshBuilder.CreateLines = function (name, options, scene) {
  19724. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19725. return lines;
  19726. };
  19727. /**
  19728. * Creates a dashed line mesh.
  19729. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19730. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19731. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19732. * The parameter `points` is an array successive Vector3.
  19733. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19734. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19735. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19736. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19737. * When updating an instance, remember that only point positions can change, not the number of points.
  19738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19739. */
  19740. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19741. var points = options.points;
  19742. var instance = options.instance;
  19743. var gapSize = options.gapSize;
  19744. var dashNb = options.dashNb;
  19745. var dashSize = options.dashSize;
  19746. if (instance) {
  19747. var positionFunction = function (positions) {
  19748. var curvect = BABYLON.Vector3.Zero();
  19749. var nbSeg = positions.length / 6;
  19750. var lg = 0;
  19751. var nb = 0;
  19752. var shft = 0;
  19753. var dashshft = 0;
  19754. var curshft = 0;
  19755. var p = 0;
  19756. var i = 0;
  19757. var j = 0;
  19758. for (i = 0; i < points.length - 1; i++) {
  19759. points[i + 1].subtractToRef(points[i], curvect);
  19760. lg += curvect.length();
  19761. }
  19762. shft = lg / nbSeg;
  19763. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19764. for (i = 0; i < points.length - 1; i++) {
  19765. points[i + 1].subtractToRef(points[i], curvect);
  19766. nb = Math.floor(curvect.length() / shft);
  19767. curvect.normalize();
  19768. j = 0;
  19769. while (j < nb && p < positions.length) {
  19770. curshft = shft * j;
  19771. positions[p] = points[i].x + curshft * curvect.x;
  19772. positions[p + 1] = points[i].y + curshft * curvect.y;
  19773. positions[p + 2] = points[i].z + curshft * curvect.z;
  19774. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19775. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19776. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19777. p += 6;
  19778. j++;
  19779. }
  19780. }
  19781. while (p < positions.length) {
  19782. positions[p] = points[i].x;
  19783. positions[p + 1] = points[i].y;
  19784. positions[p + 2] = points[i].z;
  19785. p += 3;
  19786. }
  19787. };
  19788. instance.updateMeshPositions(positionFunction, false);
  19789. return instance;
  19790. }
  19791. // dashed lines creation
  19792. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19793. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19794. vertexData.applyToMesh(dashedLines, options.updatable);
  19795. dashedLines.dashSize = dashSize;
  19796. dashedLines.gapSize = gapSize;
  19797. return dashedLines;
  19798. };
  19799. /**
  19800. * Creates an extruded shape mesh.
  19801. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19802. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19803. *
  19804. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19805. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19806. * extruded along the Z axis.
  19807. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19808. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  19809. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19810. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19811. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19812. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19813. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19815. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19816. */
  19817. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19818. var path = options.path;
  19819. var shape = options.shape;
  19820. var scale = options.scale || 1;
  19821. var rotation = options.rotation || 0;
  19822. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19823. var updatable = options.updatable;
  19824. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19825. var instance = options.instance;
  19826. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19827. };
  19828. /**
  19829. * Creates an custom extruded shape mesh.
  19830. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19831. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19832. *
  19833. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19834. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19835. * extruded along the Z axis.
  19836. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19837. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19838. * and the distance of this point from the begining of the path :
  19839. * ```rotationFunction = function(i, distance) {
  19840. * // do things
  19841. * return rotationValue; }```
  19842. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19843. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19844. * and the distance of this point from the begining of the path :
  19845. * ````scaleFunction = function(i, distance) {
  19846. * // do things
  19847. * return scaleValue;}```
  19848. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19849. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19850. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19851. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19852. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19853. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19854. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19855. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19856. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19857. */
  19858. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19859. var path = options.path;
  19860. var shape = options.shape;
  19861. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19862. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19863. var ribbonCloseArray = options.ribbonCloseArray || false;
  19864. var ribbonClosePath = options.ribbonClosePath || false;
  19865. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19866. var updatable = options.updatable;
  19867. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19868. var instance = options.instance;
  19869. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19870. };
  19871. /**
  19872. * Creates lathe mesh.
  19873. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19874. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19875. *
  19876. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  19877. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19878. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19879. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19880. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  19881. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19882. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19883. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19884. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19885. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19886. */
  19887. MeshBuilder.CreateLathe = function (name, options, scene) {
  19888. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19889. var closed = (options.closed === undefined) ? true : options.closed;
  19890. var shape = options.shape;
  19891. var radius = options.radius || 1;
  19892. var tessellation = options.tessellation || 64;
  19893. var updatable = options.updatable;
  19894. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19895. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19896. var pi2 = Math.PI * 2;
  19897. var paths = new Array();
  19898. var i = 0;
  19899. var p = 0;
  19900. var step = pi2 / tessellation * arc;
  19901. var rotated;
  19902. var path = new Array();
  19903. ;
  19904. for (i = 0; i <= tessellation; i++) {
  19905. var path = [];
  19906. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19907. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19908. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19909. }
  19910. for (p = 0; p < shape.length; p++) {
  19911. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19912. path.push(rotated);
  19913. }
  19914. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19915. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  19916. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19917. }
  19918. paths.push(path);
  19919. }
  19920. // lathe ribbon
  19921. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19922. return lathe;
  19923. };
  19924. /**
  19925. * Creates a plane mesh.
  19926. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19927. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19928. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19929. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19931. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19933. */
  19934. MeshBuilder.CreatePlane = function (name, options, scene) {
  19935. var plane = new BABYLON.Mesh(name, scene);
  19936. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19937. vertexData.applyToMesh(plane, options.updatable);
  19938. if (options.sourcePlane) {
  19939. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19940. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19941. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19942. plane.rotate(vectorProduct, product);
  19943. }
  19944. return plane;
  19945. };
  19946. /**
  19947. * Creates a ground mesh.
  19948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19949. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19950. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19952. */
  19953. MeshBuilder.CreateGround = function (name, options, scene) {
  19954. var ground = new BABYLON.GroundMesh(name, scene);
  19955. ground._setReady(false);
  19956. ground._subdivisions = options.subdivisions || 1;
  19957. ground._width = options.width || 1;
  19958. ground._height = options.height || 1;
  19959. ground._maxX = ground._width / 2;
  19960. ground._maxZ = ground._height / 2;
  19961. ground._minX = -ground._maxX;
  19962. ground._minZ = -ground._maxZ;
  19963. var vertexData = BABYLON.VertexData.CreateGround(options);
  19964. vertexData.applyToMesh(ground, options.updatable);
  19965. ground._setReady(true);
  19966. return ground;
  19967. };
  19968. /**
  19969. * Creates a tiled ground mesh.
  19970. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19971. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19972. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19973. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19974. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19975. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19976. * numbers of subdivisions on the ground width and height of each tile.
  19977. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19978. */
  19979. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19980. var tiledGround = new BABYLON.Mesh(name, scene);
  19981. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19982. vertexData.applyToMesh(tiledGround, options.updatable);
  19983. return tiledGround;
  19984. };
  19985. /**
  19986. * Creates a ground mesh from a height map.
  19987. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19988. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19989. * The parameter `url` sets the URL of the height map image resource.
  19990. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19991. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19992. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19993. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19994. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  19995. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19996. * return; }```
  19997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19998. */
  19999. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20000. var width = options.width || 10;
  20001. var height = options.height || 10;
  20002. var subdivisions = options.subdivisions || 1;
  20003. var minHeight = options.minHeight;
  20004. var maxHeight = options.maxHeight || 10;
  20005. var updatable = options.updatable;
  20006. var onReady = options.onReady;
  20007. var ground = new BABYLON.GroundMesh(name, scene);
  20008. ground._subdivisions = subdivisions;
  20009. ground._width = width;
  20010. ground._height = height;
  20011. ground._maxX = ground._width / 2;
  20012. ground._maxZ = ground._height / 2;
  20013. ground._minX = -ground._maxX;
  20014. ground._minZ = -ground._maxZ;
  20015. ground._setReady(false);
  20016. var onload = function (img) {
  20017. // Getting height map data
  20018. var canvas = document.createElement("canvas");
  20019. var context = canvas.getContext("2d");
  20020. var bufferWidth = img.width;
  20021. var bufferHeight = img.height;
  20022. canvas.width = bufferWidth;
  20023. canvas.height = bufferHeight;
  20024. context.drawImage(img, 0, 0);
  20025. // Create VertexData from map data
  20026. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20027. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  20028. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  20029. width: width, height: height,
  20030. subdivisions: subdivisions,
  20031. minHeight: minHeight, maxHeight: maxHeight,
  20032. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  20033. });
  20034. vertexData.applyToMesh(ground, updatable);
  20035. ground._setReady(true);
  20036. //execute ready callback, if set
  20037. if (onReady) {
  20038. onReady(ground);
  20039. }
  20040. };
  20041. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20042. return ground;
  20043. };
  20044. /**
  20045. * Creates a tube mesh.
  20046. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  20047. *
  20048. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  20049. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  20050. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20051. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20052. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20053. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  20054. * It must return a radius value (positive float) :
  20055. * ```var radiusFunction = function(i, distance) {
  20056. * // do things
  20057. * return radius; }```
  20058. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  20059. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  20060. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  20061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20064. */
  20065. MeshBuilder.CreateTube = function (name, options, scene) {
  20066. var path = options.path;
  20067. var radius = options.radius || 1;
  20068. var tessellation = options.tessellation || 64;
  20069. var radiusFunction = options.radiusFunction;
  20070. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20071. var updatable = options.updatable;
  20072. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20073. var instance = options.instance;
  20074. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  20075. // tube geometry
  20076. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  20077. var tangents = path3D.getTangents();
  20078. var normals = path3D.getNormals();
  20079. var distances = path3D.getDistances();
  20080. var pi2 = Math.PI * 2;
  20081. var step = pi2 / tessellation * arc;
  20082. var returnRadius = function () { return radius; };
  20083. var radiusFunctionFinal = radiusFunction || returnRadius;
  20084. var circlePath;
  20085. var rad;
  20086. var normal;
  20087. var rotated;
  20088. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20089. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20090. for (var i = 0; i < path.length; i++) {
  20091. rad = radiusFunctionFinal(i, distances[i]); // current radius
  20092. circlePath = Array(); // current circle array
  20093. normal = normals[i]; // current normal
  20094. for (var t = 0; t < tessellation; t++) {
  20095. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  20096. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  20097. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  20098. rotated.scaleInPlace(rad).addInPlace(path[i]);
  20099. circlePath[t] = rotated;
  20100. }
  20101. circlePaths[index] = circlePath;
  20102. index++;
  20103. }
  20104. // cap
  20105. var capPath = function (nbPoints, pathIndex) {
  20106. var pointCap = Array();
  20107. for (var i = 0; i < nbPoints; i++) {
  20108. pointCap.push(path[pathIndex]);
  20109. }
  20110. return pointCap;
  20111. };
  20112. switch (cap) {
  20113. case BABYLON.Mesh.NO_CAP:
  20114. break;
  20115. case BABYLON.Mesh.CAP_START:
  20116. circlePaths[0] = capPath(tessellation, 0);
  20117. circlePaths[1] = circlePaths[2].slice(0);
  20118. break;
  20119. case BABYLON.Mesh.CAP_END:
  20120. circlePaths[index] = circlePaths[index - 1].slice(0);
  20121. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20122. break;
  20123. case BABYLON.Mesh.CAP_ALL:
  20124. circlePaths[0] = capPath(tessellation, 0);
  20125. circlePaths[1] = circlePaths[2].slice(0);
  20126. circlePaths[index] = circlePaths[index - 1].slice(0);
  20127. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20128. break;
  20129. default:
  20130. break;
  20131. }
  20132. return circlePaths;
  20133. };
  20134. var path3D;
  20135. var pathArray;
  20136. if (instance) {
  20137. var arc = options.arc || instance.arc;
  20138. path3D = (instance.path3D).update(path);
  20139. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  20140. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  20141. instance.path3D = path3D;
  20142. instance.pathArray = pathArray;
  20143. instance.arc = arc;
  20144. return instance;
  20145. }
  20146. // tube creation
  20147. path3D = new BABYLON.Path3D(path);
  20148. var newPathArray = new Array();
  20149. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20150. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  20151. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  20152. tube.pathArray = pathArray;
  20153. tube.path3D = path3D;
  20154. tube.tessellation = tessellation;
  20155. tube.cap = cap;
  20156. tube.arc = options.arc;
  20157. return tube;
  20158. };
  20159. /**
  20160. * Creates a polyhedron mesh.
  20161. *
  20162. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  20163. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  20164. * to choose the wanted type.
  20165. * The parameter `size` (positive float, default 1) sets the polygon size.
  20166. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20167. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  20168. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  20169. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  20170. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20171. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  20172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20175. */
  20176. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  20177. var polyhedron = new BABYLON.Mesh(name, scene);
  20178. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  20179. vertexData.applyToMesh(polyhedron, options.updatable);
  20180. return polyhedron;
  20181. };
  20182. /**
  20183. * Creates a decal mesh.
  20184. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  20185. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  20186. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20187. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20188. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  20189. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20190. */
  20191. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  20192. var indices = sourceMesh.getIndices();
  20193. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20194. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20195. var position = options.position || BABYLON.Vector3.Zero();
  20196. var normal = options.normal || BABYLON.Vector3.Up();
  20197. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  20198. var angle = options.angle || 0;
  20199. // Getting correct rotation
  20200. if (!normal) {
  20201. var target = new BABYLON.Vector3(0, 0, 1);
  20202. var camera = sourceMesh.getScene().activeCamera;
  20203. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  20204. normal = camera.globalPosition.subtract(cameraWorldTarget);
  20205. }
  20206. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  20207. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  20208. var pitch = Math.atan2(normal.y, len);
  20209. // Matrix
  20210. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  20211. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  20212. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  20213. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  20214. var vertexData = new BABYLON.VertexData();
  20215. vertexData.indices = [];
  20216. vertexData.positions = [];
  20217. vertexData.normals = [];
  20218. vertexData.uvs = [];
  20219. var currentVertexDataIndex = 0;
  20220. var extractDecalVector3 = function (indexId) {
  20221. var vertexId = indices[indexId];
  20222. var result = new BABYLON.PositionNormalVertex();
  20223. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  20224. // Send vector to decal local world
  20225. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  20226. // Get normal
  20227. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  20228. return result;
  20229. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  20230. var clip = function (vertices, axis) {
  20231. if (vertices.length === 0) {
  20232. return vertices;
  20233. }
  20234. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  20235. var clipVertices = function (v0, v1) {
  20236. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  20237. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  20238. };
  20239. var result = new Array();
  20240. for (var index = 0; index < vertices.length; index += 3) {
  20241. var v1Out;
  20242. var v2Out;
  20243. var v3Out;
  20244. var total = 0;
  20245. var nV1, nV2, nV3, nV4;
  20246. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  20247. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  20248. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  20249. v1Out = d1 > 0;
  20250. v2Out = d2 > 0;
  20251. v3Out = d3 > 0;
  20252. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  20253. switch (total) {
  20254. case 0:
  20255. result.push(vertices[index]);
  20256. result.push(vertices[index + 1]);
  20257. result.push(vertices[index + 2]);
  20258. break;
  20259. case 1:
  20260. if (v1Out) {
  20261. nV1 = vertices[index + 1];
  20262. nV2 = vertices[index + 2];
  20263. nV3 = clipVertices(vertices[index], nV1);
  20264. nV4 = clipVertices(vertices[index], nV2);
  20265. }
  20266. if (v2Out) {
  20267. nV1 = vertices[index];
  20268. nV2 = vertices[index + 2];
  20269. nV3 = clipVertices(vertices[index + 1], nV1);
  20270. nV4 = clipVertices(vertices[index + 1], nV2);
  20271. result.push(nV3);
  20272. result.push(nV2.clone());
  20273. result.push(nV1.clone());
  20274. result.push(nV2.clone());
  20275. result.push(nV3.clone());
  20276. result.push(nV4);
  20277. break;
  20278. }
  20279. if (v3Out) {
  20280. nV1 = vertices[index];
  20281. nV2 = vertices[index + 1];
  20282. nV3 = clipVertices(vertices[index + 2], nV1);
  20283. nV4 = clipVertices(vertices[index + 2], nV2);
  20284. }
  20285. result.push(nV1.clone());
  20286. result.push(nV2.clone());
  20287. result.push(nV3);
  20288. result.push(nV4);
  20289. result.push(nV3.clone());
  20290. result.push(nV2.clone());
  20291. break;
  20292. case 2:
  20293. if (!v1Out) {
  20294. nV1 = vertices[index].clone();
  20295. nV2 = clipVertices(nV1, vertices[index + 1]);
  20296. nV3 = clipVertices(nV1, vertices[index + 2]);
  20297. result.push(nV1);
  20298. result.push(nV2);
  20299. result.push(nV3);
  20300. }
  20301. if (!v2Out) {
  20302. nV1 = vertices[index + 1].clone();
  20303. nV2 = clipVertices(nV1, vertices[index + 2]);
  20304. nV3 = clipVertices(nV1, vertices[index]);
  20305. result.push(nV1);
  20306. result.push(nV2);
  20307. result.push(nV3);
  20308. }
  20309. if (!v3Out) {
  20310. nV1 = vertices[index + 2].clone();
  20311. nV2 = clipVertices(nV1, vertices[index]);
  20312. nV3 = clipVertices(nV1, vertices[index + 1]);
  20313. result.push(nV1);
  20314. result.push(nV2);
  20315. result.push(nV3);
  20316. }
  20317. break;
  20318. case 3:
  20319. break;
  20320. }
  20321. }
  20322. return result;
  20323. };
  20324. for (var index = 0; index < indices.length; index += 3) {
  20325. var faceVertices = new Array();
  20326. faceVertices.push(extractDecalVector3(index));
  20327. faceVertices.push(extractDecalVector3(index + 1));
  20328. faceVertices.push(extractDecalVector3(index + 2));
  20329. // Clip
  20330. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20331. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20332. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20333. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20334. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20335. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20336. if (faceVertices.length === 0) {
  20337. continue;
  20338. }
  20339. // Add UVs and get back to world
  20340. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20341. var vertex = faceVertices[vIndex];
  20342. //TODO check for Int32Array
  20343. vertexData.indices.push(currentVertexDataIndex);
  20344. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20345. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20346. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20347. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20348. currentVertexDataIndex++;
  20349. }
  20350. }
  20351. // Return mesh
  20352. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20353. vertexData.applyToMesh(decal);
  20354. decal.position = position.clone();
  20355. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20356. return decal;
  20357. };
  20358. // Privates
  20359. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20360. // extrusion geometry
  20361. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20362. var tangents = path3D.getTangents();
  20363. var normals = path3D.getNormals();
  20364. var binormals = path3D.getBinormals();
  20365. var distances = path3D.getDistances();
  20366. var angle = 0;
  20367. var returnScale = function () { return scale; };
  20368. var returnRotation = function () { return rotation; };
  20369. var rotate = custom ? rotateFunction : returnRotation;
  20370. var scl = custom ? scaleFunction : returnScale;
  20371. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20372. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20373. for (var i = 0; i < curve.length; i++) {
  20374. var shapePath = new Array();
  20375. var angleStep = rotate(i, distances[i]);
  20376. var scaleRatio = scl(i, distances[i]);
  20377. for (var p = 0; p < shape.length; p++) {
  20378. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20379. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20380. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20381. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20382. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20383. shapePath[p] = rotated;
  20384. }
  20385. shapePaths[index] = shapePath;
  20386. angle += angleStep;
  20387. index++;
  20388. }
  20389. // cap
  20390. var capPath = function (shapePath) {
  20391. var pointCap = Array();
  20392. var barycenter = BABYLON.Vector3.Zero();
  20393. var i;
  20394. for (i = 0; i < shapePath.length; i++) {
  20395. barycenter.addInPlace(shapePath[i]);
  20396. }
  20397. barycenter.scaleInPlace(1 / shapePath.length);
  20398. for (i = 0; i < shapePath.length; i++) {
  20399. pointCap.push(barycenter);
  20400. }
  20401. return pointCap;
  20402. };
  20403. switch (cap) {
  20404. case BABYLON.Mesh.NO_CAP:
  20405. break;
  20406. case BABYLON.Mesh.CAP_START:
  20407. shapePaths[0] = capPath(shapePaths[2]);
  20408. shapePaths[1] = shapePaths[2].slice(0);
  20409. break;
  20410. case BABYLON.Mesh.CAP_END:
  20411. shapePaths[index] = shapePaths[index - 1];
  20412. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20413. break;
  20414. case BABYLON.Mesh.CAP_ALL:
  20415. shapePaths[0] = capPath(shapePaths[2]);
  20416. shapePaths[1] = shapePaths[2].slice(0);
  20417. shapePaths[index] = shapePaths[index - 1];
  20418. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20419. break;
  20420. default:
  20421. break;
  20422. }
  20423. return shapePaths;
  20424. };
  20425. var path3D;
  20426. var pathArray;
  20427. if (instance) {
  20428. path3D = (instance.path3D).update(curve);
  20429. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20430. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20431. return instance;
  20432. }
  20433. // extruded shape creation
  20434. path3D = new BABYLON.Path3D(curve);
  20435. var newShapePaths = new Array();
  20436. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20437. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20438. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20439. extrudedGeneric.pathArray = pathArray;
  20440. extrudedGeneric.path3D = path3D;
  20441. extrudedGeneric.cap = cap;
  20442. return extrudedGeneric;
  20443. };
  20444. return MeshBuilder;
  20445. })();
  20446. BABYLON.MeshBuilder = MeshBuilder;
  20447. })(BABYLON || (BABYLON = {}));
  20448. var BABYLON;
  20449. (function (BABYLON) {
  20450. var BaseTexture = (function () {
  20451. function BaseTexture(scene) {
  20452. this.hasAlpha = false;
  20453. this.getAlphaFromRGB = false;
  20454. this.level = 1;
  20455. this.coordinatesIndex = 0;
  20456. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20457. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20458. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20459. this.anisotropicFilteringLevel = 4;
  20460. this.isCube = false;
  20461. this.isRenderTarget = false;
  20462. this.animations = new Array();
  20463. /**
  20464. * An event triggered when the texture is disposed.
  20465. * @type {BABYLON.Observable}
  20466. */
  20467. this.onDisposeObservable = new BABYLON.Observable();
  20468. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20469. this._scene = scene;
  20470. this._scene.textures.push(this);
  20471. }
  20472. BaseTexture.prototype.toString = function () {
  20473. return this.name;
  20474. };
  20475. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20476. set: function (callback) {
  20477. if (this._onDisposeObserver) {
  20478. this.onDisposeObservable.remove(this._onDisposeObserver);
  20479. }
  20480. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20481. },
  20482. enumerable: true,
  20483. configurable: true
  20484. });
  20485. BaseTexture.prototype.getScene = function () {
  20486. return this._scene;
  20487. };
  20488. BaseTexture.prototype.getTextureMatrix = function () {
  20489. return null;
  20490. };
  20491. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20492. return null;
  20493. };
  20494. BaseTexture.prototype.getInternalTexture = function () {
  20495. return this._texture;
  20496. };
  20497. BaseTexture.prototype.isReady = function () {
  20498. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20499. return true;
  20500. }
  20501. if (this._texture) {
  20502. return this._texture.isReady;
  20503. }
  20504. return false;
  20505. };
  20506. BaseTexture.prototype.getSize = function () {
  20507. if (this._texture._width) {
  20508. return { width: this._texture._width, height: this._texture._height };
  20509. }
  20510. if (this._texture._size) {
  20511. return { width: this._texture._size, height: this._texture._size };
  20512. }
  20513. return { width: 0, height: 0 };
  20514. };
  20515. BaseTexture.prototype.getBaseSize = function () {
  20516. if (!this.isReady() || !this._texture)
  20517. return { width: 0, height: 0 };
  20518. if (this._texture._size) {
  20519. return { width: this._texture._size, height: this._texture._size };
  20520. }
  20521. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20522. };
  20523. BaseTexture.prototype.scale = function (ratio) {
  20524. };
  20525. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20526. get: function () {
  20527. return false;
  20528. },
  20529. enumerable: true,
  20530. configurable: true
  20531. });
  20532. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20533. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20534. for (var index = 0; index < texturesCache.length; index++) {
  20535. var texturesCacheEntry = texturesCache[index];
  20536. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20537. texturesCache.splice(index, 1);
  20538. return;
  20539. }
  20540. }
  20541. };
  20542. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20543. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20544. for (var index = 0; index < texturesCache.length; index++) {
  20545. var texturesCacheEntry = texturesCache[index];
  20546. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20547. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20548. texturesCacheEntry.references++;
  20549. return texturesCacheEntry;
  20550. }
  20551. }
  20552. }
  20553. return null;
  20554. };
  20555. BaseTexture.prototype.delayLoad = function () {
  20556. };
  20557. BaseTexture.prototype.clone = function () {
  20558. return null;
  20559. };
  20560. BaseTexture.prototype.releaseInternalTexture = function () {
  20561. if (this._texture) {
  20562. this._scene.getEngine().releaseInternalTexture(this._texture);
  20563. delete this._texture;
  20564. }
  20565. };
  20566. BaseTexture.prototype.dispose = function () {
  20567. // Animations
  20568. this.getScene().stopAnimation(this);
  20569. // Remove from scene
  20570. var index = this._scene.textures.indexOf(this);
  20571. if (index >= 0) {
  20572. this._scene.textures.splice(index, 1);
  20573. }
  20574. if (this._texture === undefined) {
  20575. return;
  20576. }
  20577. // Release
  20578. this.releaseInternalTexture();
  20579. // Callback
  20580. this.onDisposeObservable.notifyObservers(this);
  20581. this.onDisposeObservable.clear();
  20582. };
  20583. BaseTexture.prototype.serialize = function () {
  20584. if (!this.name) {
  20585. return null;
  20586. }
  20587. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20588. // Animations
  20589. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20590. return serializationObject;
  20591. };
  20592. __decorate([
  20593. BABYLON.serialize()
  20594. ], BaseTexture.prototype, "name", void 0);
  20595. __decorate([
  20596. BABYLON.serialize()
  20597. ], BaseTexture.prototype, "hasAlpha", void 0);
  20598. __decorate([
  20599. BABYLON.serialize()
  20600. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20601. __decorate([
  20602. BABYLON.serialize()
  20603. ], BaseTexture.prototype, "level", void 0);
  20604. __decorate([
  20605. BABYLON.serialize()
  20606. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20607. __decorate([
  20608. BABYLON.serialize()
  20609. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20610. __decorate([
  20611. BABYLON.serialize()
  20612. ], BaseTexture.prototype, "wrapU", void 0);
  20613. __decorate([
  20614. BABYLON.serialize()
  20615. ], BaseTexture.prototype, "wrapV", void 0);
  20616. __decorate([
  20617. BABYLON.serialize()
  20618. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20619. __decorate([
  20620. BABYLON.serialize()
  20621. ], BaseTexture.prototype, "isCube", void 0);
  20622. __decorate([
  20623. BABYLON.serialize()
  20624. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20625. return BaseTexture;
  20626. })();
  20627. BABYLON.BaseTexture = BaseTexture;
  20628. })(BABYLON || (BABYLON = {}));
  20629. var BABYLON;
  20630. (function (BABYLON) {
  20631. var Texture = (function (_super) {
  20632. __extends(Texture, _super);
  20633. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20634. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20635. if (onLoad === void 0) { onLoad = null; }
  20636. if (onError === void 0) { onError = null; }
  20637. if (buffer === void 0) { buffer = null; }
  20638. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20639. _super.call(this, scene);
  20640. this.uOffset = 0;
  20641. this.vOffset = 0;
  20642. this.uScale = 1.0;
  20643. this.vScale = 1.0;
  20644. this.uAng = 0;
  20645. this.vAng = 0;
  20646. this.wAng = 0;
  20647. this.name = url;
  20648. this.url = url;
  20649. this._noMipmap = noMipmap;
  20650. this._invertY = invertY;
  20651. this._samplingMode = samplingMode;
  20652. this._buffer = buffer;
  20653. this._deleteBuffer = deleteBuffer;
  20654. if (!url) {
  20655. return;
  20656. }
  20657. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20658. if (!this._texture) {
  20659. if (!scene.useDelayedTextureLoading) {
  20660. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20661. if (deleteBuffer) {
  20662. delete this._buffer;
  20663. }
  20664. }
  20665. else {
  20666. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20667. this._delayedOnLoad = onLoad;
  20668. this._delayedOnError = onError;
  20669. }
  20670. }
  20671. else {
  20672. BABYLON.Tools.SetImmediate(function () {
  20673. if (onLoad) {
  20674. onLoad();
  20675. }
  20676. });
  20677. }
  20678. }
  20679. Object.defineProperty(Texture.prototype, "noMipmap", {
  20680. get: function () {
  20681. return this._noMipmap;
  20682. },
  20683. enumerable: true,
  20684. configurable: true
  20685. });
  20686. Texture.prototype.delayLoad = function () {
  20687. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20688. return;
  20689. }
  20690. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20691. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20692. if (!this._texture) {
  20693. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20694. if (this._deleteBuffer) {
  20695. delete this._buffer;
  20696. }
  20697. }
  20698. };
  20699. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20700. if (!this._texture) {
  20701. return;
  20702. }
  20703. this._samplingMode = samplingMode;
  20704. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20705. };
  20706. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20707. x *= this.uScale;
  20708. y *= this.vScale;
  20709. x -= 0.5 * this.uScale;
  20710. y -= 0.5 * this.vScale;
  20711. z -= 0.5;
  20712. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20713. t.x += 0.5 * this.uScale + this.uOffset;
  20714. t.y += 0.5 * this.vScale + this.vOffset;
  20715. t.z += 0.5;
  20716. };
  20717. Texture.prototype.getTextureMatrix = function () {
  20718. if (this.uOffset === this._cachedUOffset &&
  20719. this.vOffset === this._cachedVOffset &&
  20720. this.uScale === this._cachedUScale &&
  20721. this.vScale === this._cachedVScale &&
  20722. this.uAng === this._cachedUAng &&
  20723. this.vAng === this._cachedVAng &&
  20724. this.wAng === this._cachedWAng) {
  20725. return this._cachedTextureMatrix;
  20726. }
  20727. this._cachedUOffset = this.uOffset;
  20728. this._cachedVOffset = this.vOffset;
  20729. this._cachedUScale = this.uScale;
  20730. this._cachedVScale = this.vScale;
  20731. this._cachedUAng = this.uAng;
  20732. this._cachedVAng = this.vAng;
  20733. this._cachedWAng = this.wAng;
  20734. if (!this._cachedTextureMatrix) {
  20735. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20736. this._rowGenerationMatrix = new BABYLON.Matrix();
  20737. this._t0 = BABYLON.Vector3.Zero();
  20738. this._t1 = BABYLON.Vector3.Zero();
  20739. this._t2 = BABYLON.Vector3.Zero();
  20740. }
  20741. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20742. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20743. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20744. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20745. this._t1.subtractInPlace(this._t0);
  20746. this._t2.subtractInPlace(this._t0);
  20747. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20748. this._cachedTextureMatrix.m[0] = this._t1.x;
  20749. this._cachedTextureMatrix.m[1] = this._t1.y;
  20750. this._cachedTextureMatrix.m[2] = this._t1.z;
  20751. this._cachedTextureMatrix.m[4] = this._t2.x;
  20752. this._cachedTextureMatrix.m[5] = this._t2.y;
  20753. this._cachedTextureMatrix.m[6] = this._t2.z;
  20754. this._cachedTextureMatrix.m[8] = this._t0.x;
  20755. this._cachedTextureMatrix.m[9] = this._t0.y;
  20756. this._cachedTextureMatrix.m[10] = this._t0.z;
  20757. return this._cachedTextureMatrix;
  20758. };
  20759. Texture.prototype.getReflectionTextureMatrix = function () {
  20760. if (this.uOffset === this._cachedUOffset &&
  20761. this.vOffset === this._cachedVOffset &&
  20762. this.uScale === this._cachedUScale &&
  20763. this.vScale === this._cachedVScale &&
  20764. this.coordinatesMode === this._cachedCoordinatesMode) {
  20765. return this._cachedTextureMatrix;
  20766. }
  20767. if (!this._cachedTextureMatrix) {
  20768. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20769. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20770. }
  20771. this._cachedCoordinatesMode = this.coordinatesMode;
  20772. switch (this.coordinatesMode) {
  20773. case Texture.PLANAR_MODE:
  20774. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20775. this._cachedTextureMatrix[0] = this.uScale;
  20776. this._cachedTextureMatrix[5] = this.vScale;
  20777. this._cachedTextureMatrix[12] = this.uOffset;
  20778. this._cachedTextureMatrix[13] = this.vOffset;
  20779. break;
  20780. case Texture.PROJECTION_MODE:
  20781. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20782. this._projectionModeMatrix.m[0] = 0.5;
  20783. this._projectionModeMatrix.m[5] = -0.5;
  20784. this._projectionModeMatrix.m[10] = 0.0;
  20785. this._projectionModeMatrix.m[12] = 0.5;
  20786. this._projectionModeMatrix.m[13] = 0.5;
  20787. this._projectionModeMatrix.m[14] = 1.0;
  20788. this._projectionModeMatrix.m[15] = 1.0;
  20789. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20790. break;
  20791. default:
  20792. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20793. break;
  20794. }
  20795. return this._cachedTextureMatrix;
  20796. };
  20797. Texture.prototype.clone = function () {
  20798. var _this = this;
  20799. return BABYLON.SerializationHelper.Clone(function () {
  20800. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20801. }, this);
  20802. };
  20803. // Statics
  20804. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20805. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20806. if (onLoad === void 0) { onLoad = null; }
  20807. if (onError === void 0) { onError = null; }
  20808. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20809. };
  20810. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20811. if (parsedTexture.isCube) {
  20812. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20813. }
  20814. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20815. return null;
  20816. }
  20817. var texture = BABYLON.SerializationHelper.Parse(function () {
  20818. if (parsedTexture.mirrorPlane) {
  20819. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20820. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20821. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20822. return mirrorTexture;
  20823. }
  20824. else if (parsedTexture.isRenderTarget) {
  20825. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20826. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20827. return renderTargetTexture;
  20828. }
  20829. else {
  20830. var texture;
  20831. if (parsedTexture.base64String) {
  20832. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20833. }
  20834. else {
  20835. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20836. }
  20837. return texture;
  20838. }
  20839. }, parsedTexture, scene);
  20840. // Animations
  20841. if (parsedTexture.animations) {
  20842. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20843. var parsedAnimation = parsedTexture.animations[animationIndex];
  20844. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20845. }
  20846. }
  20847. return texture;
  20848. };
  20849. // Constants
  20850. Texture.NEAREST_SAMPLINGMODE = 1;
  20851. Texture.BILINEAR_SAMPLINGMODE = 2;
  20852. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20853. Texture.EXPLICIT_MODE = 0;
  20854. Texture.SPHERICAL_MODE = 1;
  20855. Texture.PLANAR_MODE = 2;
  20856. Texture.CUBIC_MODE = 3;
  20857. Texture.PROJECTION_MODE = 4;
  20858. Texture.SKYBOX_MODE = 5;
  20859. Texture.INVCUBIC_MODE = 6;
  20860. Texture.EQUIRECTANGULAR_MODE = 7;
  20861. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20862. Texture.CLAMP_ADDRESSMODE = 0;
  20863. Texture.WRAP_ADDRESSMODE = 1;
  20864. Texture.MIRROR_ADDRESSMODE = 2;
  20865. __decorate([
  20866. BABYLON.serialize()
  20867. ], Texture.prototype, "url", void 0);
  20868. __decorate([
  20869. BABYLON.serialize()
  20870. ], Texture.prototype, "uOffset", void 0);
  20871. __decorate([
  20872. BABYLON.serialize()
  20873. ], Texture.prototype, "vOffset", void 0);
  20874. __decorate([
  20875. BABYLON.serialize()
  20876. ], Texture.prototype, "uScale", void 0);
  20877. __decorate([
  20878. BABYLON.serialize()
  20879. ], Texture.prototype, "vScale", void 0);
  20880. __decorate([
  20881. BABYLON.serialize()
  20882. ], Texture.prototype, "uAng", void 0);
  20883. __decorate([
  20884. BABYLON.serialize()
  20885. ], Texture.prototype, "vAng", void 0);
  20886. __decorate([
  20887. BABYLON.serialize()
  20888. ], Texture.prototype, "wAng", void 0);
  20889. return Texture;
  20890. })(BABYLON.BaseTexture);
  20891. BABYLON.Texture = Texture;
  20892. })(BABYLON || (BABYLON = {}));
  20893. var BABYLON;
  20894. (function (BABYLON) {
  20895. var CubeTexture = (function (_super) {
  20896. __extends(CubeTexture, _super);
  20897. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20898. _super.call(this, scene);
  20899. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20900. this.name = rootUrl;
  20901. this.url = rootUrl;
  20902. this._noMipmap = noMipmap;
  20903. this.hasAlpha = false;
  20904. if (!rootUrl && !files) {
  20905. return;
  20906. }
  20907. this._texture = this._getFromCache(rootUrl, noMipmap);
  20908. if (!files) {
  20909. if (!extensions) {
  20910. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20911. }
  20912. files = [];
  20913. for (var index = 0; index < extensions.length; index++) {
  20914. files.push(rootUrl + extensions[index]);
  20915. }
  20916. this._extensions = extensions;
  20917. }
  20918. this._files = files;
  20919. if (!this._texture) {
  20920. if (!scene.useDelayedTextureLoading) {
  20921. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20922. }
  20923. else {
  20924. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20925. }
  20926. }
  20927. this.isCube = true;
  20928. this._textureMatrix = BABYLON.Matrix.Identity();
  20929. }
  20930. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20931. return new CubeTexture("", scene, null, noMipmap, files);
  20932. };
  20933. // Methods
  20934. CubeTexture.prototype.delayLoad = function () {
  20935. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20936. return;
  20937. }
  20938. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20939. this._texture = this._getFromCache(this.url, this._noMipmap);
  20940. if (!this._texture) {
  20941. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20942. }
  20943. };
  20944. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20945. return this._textureMatrix;
  20946. };
  20947. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20948. var texture = BABYLON.SerializationHelper.Parse(function () {
  20949. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20950. }, parsedTexture, scene);
  20951. // Animations
  20952. if (parsedTexture.animations) {
  20953. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20954. var parsedAnimation = parsedTexture.animations[animationIndex];
  20955. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20956. }
  20957. }
  20958. return texture;
  20959. };
  20960. CubeTexture.prototype.clone = function () {
  20961. var _this = this;
  20962. return BABYLON.SerializationHelper.Clone(function () {
  20963. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20964. }, this);
  20965. };
  20966. return CubeTexture;
  20967. })(BABYLON.BaseTexture);
  20968. BABYLON.CubeTexture = CubeTexture;
  20969. })(BABYLON || (BABYLON = {}));
  20970. var BABYLON;
  20971. (function (BABYLON) {
  20972. var RenderTargetTexture = (function (_super) {
  20973. __extends(RenderTargetTexture, _super);
  20974. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20975. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20976. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20977. if (isCube === void 0) { isCube = false; }
  20978. _super.call(this, null, scene, !generateMipMaps);
  20979. this.isCube = isCube;
  20980. this.renderList = new Array();
  20981. this.renderParticles = true;
  20982. this.renderSprites = false;
  20983. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20984. // Events
  20985. /**
  20986. * An event triggered when the texture is unbind.
  20987. * @type {BABYLON.Observable}
  20988. */
  20989. this.onAfterUnbindObservable = new BABYLON.Observable();
  20990. /**
  20991. * An event triggered before rendering the texture
  20992. * @type {BABYLON.Observable}
  20993. */
  20994. this.onBeforeRenderObservable = new BABYLON.Observable();
  20995. /**
  20996. * An event triggered after rendering the texture
  20997. * @type {BABYLON.Observable}
  20998. */
  20999. this.onAfterRenderObservable = new BABYLON.Observable();
  21000. /**
  21001. * An event triggered after the texture clear
  21002. * @type {BABYLON.Observable}
  21003. */
  21004. this.onClearObservable = new BABYLON.Observable();
  21005. this._currentRefreshId = -1;
  21006. this._refreshRate = 1;
  21007. this.name = name;
  21008. this.isRenderTarget = true;
  21009. this._size = size;
  21010. this._generateMipMaps = generateMipMaps;
  21011. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  21012. if (isCube) {
  21013. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21014. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  21015. this._textureMatrix = BABYLON.Matrix.Identity();
  21016. }
  21017. else {
  21018. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  21019. }
  21020. // Rendering groups
  21021. this._renderingManager = new BABYLON.RenderingManager(scene);
  21022. }
  21023. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  21024. get: function () {
  21025. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  21026. },
  21027. enumerable: true,
  21028. configurable: true
  21029. });
  21030. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  21031. get: function () {
  21032. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  21033. },
  21034. enumerable: true,
  21035. configurable: true
  21036. });
  21037. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  21038. get: function () {
  21039. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  21040. },
  21041. enumerable: true,
  21042. configurable: true
  21043. });
  21044. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  21045. set: function (callback) {
  21046. if (this._onAfterUnbindObserver) {
  21047. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  21048. }
  21049. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  21050. },
  21051. enumerable: true,
  21052. configurable: true
  21053. });
  21054. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  21055. set: function (callback) {
  21056. if (this._onBeforeRenderObserver) {
  21057. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21058. }
  21059. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21060. },
  21061. enumerable: true,
  21062. configurable: true
  21063. });
  21064. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  21065. set: function (callback) {
  21066. if (this._onAfterRenderObserver) {
  21067. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21068. }
  21069. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21070. },
  21071. enumerable: true,
  21072. configurable: true
  21073. });
  21074. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  21075. set: function (callback) {
  21076. if (this._onClearObserver) {
  21077. this.onClearObservable.remove(this._onClearObserver);
  21078. }
  21079. this._onClearObserver = this.onClearObservable.add(callback);
  21080. },
  21081. enumerable: true,
  21082. configurable: true
  21083. });
  21084. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  21085. this._currentRefreshId = -1;
  21086. };
  21087. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  21088. get: function () {
  21089. return this._refreshRate;
  21090. },
  21091. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21092. set: function (value) {
  21093. this._refreshRate = value;
  21094. this.resetRefreshCounter();
  21095. },
  21096. enumerable: true,
  21097. configurable: true
  21098. });
  21099. RenderTargetTexture.prototype._shouldRender = function () {
  21100. if (this._currentRefreshId === -1) {
  21101. this._currentRefreshId = 1;
  21102. return true;
  21103. }
  21104. if (this.refreshRate === this._currentRefreshId) {
  21105. this._currentRefreshId = 1;
  21106. return true;
  21107. }
  21108. this._currentRefreshId++;
  21109. return false;
  21110. };
  21111. RenderTargetTexture.prototype.isReady = function () {
  21112. if (!this.getScene().renderTargetsEnabled) {
  21113. return false;
  21114. }
  21115. return _super.prototype.isReady.call(this);
  21116. };
  21117. RenderTargetTexture.prototype.getRenderSize = function () {
  21118. return this._size;
  21119. };
  21120. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  21121. get: function () {
  21122. return true;
  21123. },
  21124. enumerable: true,
  21125. configurable: true
  21126. });
  21127. RenderTargetTexture.prototype.scale = function (ratio) {
  21128. var newSize = this._size * ratio;
  21129. this.resize(newSize, this._generateMipMaps);
  21130. };
  21131. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  21132. if (this.isCube) {
  21133. return this._textureMatrix;
  21134. }
  21135. return _super.prototype.getReflectionTextureMatrix.call(this);
  21136. };
  21137. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  21138. this.releaseInternalTexture();
  21139. if (this.isCube) {
  21140. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  21141. }
  21142. else {
  21143. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21144. }
  21145. };
  21146. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  21147. var scene = this.getScene();
  21148. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21149. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  21150. }
  21151. if (this._waitingRenderList) {
  21152. this.renderList = [];
  21153. for (var index = 0; index < this._waitingRenderList.length; index++) {
  21154. var id = this._waitingRenderList[index];
  21155. this.renderList.push(scene.getMeshByID(id));
  21156. }
  21157. delete this._waitingRenderList;
  21158. }
  21159. if (this.renderList && this.renderList.length === 0) {
  21160. return;
  21161. }
  21162. // Prepare renderingManager
  21163. this._renderingManager.reset();
  21164. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  21165. var sceneRenderId = scene.getRenderId();
  21166. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  21167. var mesh = currentRenderList[meshIndex];
  21168. if (mesh) {
  21169. if (!mesh.isReady()) {
  21170. // Reset _currentRefreshId
  21171. this.resetRefreshCounter();
  21172. continue;
  21173. }
  21174. mesh._preActivateForIntermediateRendering(sceneRenderId);
  21175. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  21176. mesh._activate(sceneRenderId);
  21177. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  21178. var subMesh = mesh.subMeshes[subIndex];
  21179. scene._activeIndices += subMesh.indexCount;
  21180. this._renderingManager.dispatch(subMesh);
  21181. }
  21182. }
  21183. }
  21184. }
  21185. if (this.isCube) {
  21186. for (var face = 0; face < 6; face++) {
  21187. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  21188. scene.incrementRenderId();
  21189. scene.resetCachedMaterial();
  21190. }
  21191. }
  21192. else {
  21193. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  21194. }
  21195. this.onAfterUnbindObservable.notifyObservers(this);
  21196. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21197. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  21198. }
  21199. scene.resetCachedMaterial();
  21200. };
  21201. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  21202. var scene = this.getScene();
  21203. var engine = scene.getEngine();
  21204. // Bind
  21205. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  21206. if (this.isCube) {
  21207. engine.bindFramebuffer(this._texture, faceIndex);
  21208. }
  21209. else {
  21210. engine.bindFramebuffer(this._texture);
  21211. }
  21212. }
  21213. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  21214. // Clear
  21215. if (this.onClearObservable.hasObservers()) {
  21216. this.onClearObservable.notifyObservers(engine);
  21217. }
  21218. else {
  21219. engine.clear(scene.clearColor, true, true);
  21220. }
  21221. if (!this._doNotChangeAspectRatio) {
  21222. scene.updateTransformMatrix(true);
  21223. }
  21224. // Render
  21225. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  21226. if (useCameraPostProcess) {
  21227. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  21228. }
  21229. if (!this._doNotChangeAspectRatio) {
  21230. scene.updateTransformMatrix(true);
  21231. }
  21232. this.onAfterRenderObservable.notifyObservers(faceIndex);
  21233. // Dump ?
  21234. if (dumpForDebug) {
  21235. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  21236. }
  21237. // Unbind
  21238. if (!this.isCube || faceIndex === 5) {
  21239. if (this.isCube) {
  21240. if (faceIndex === 5) {
  21241. engine.generateMipMapsForCubemap(this._texture);
  21242. }
  21243. }
  21244. engine.unBindFramebuffer(this._texture, this.isCube);
  21245. }
  21246. };
  21247. RenderTargetTexture.prototype.clone = function () {
  21248. var textureSize = this.getSize();
  21249. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21250. // Base texture
  21251. newTexture.hasAlpha = this.hasAlpha;
  21252. newTexture.level = this.level;
  21253. // RenderTarget Texture
  21254. newTexture.coordinatesMode = this.coordinatesMode;
  21255. newTexture.renderList = this.renderList.slice(0);
  21256. return newTexture;
  21257. };
  21258. RenderTargetTexture.prototype.serialize = function () {
  21259. if (!this.name) {
  21260. return null;
  21261. }
  21262. var serializationObject = _super.prototype.serialize.call(this);
  21263. serializationObject.renderTargetSize = this.getRenderSize();
  21264. serializationObject.renderList = [];
  21265. for (var index = 0; index < this.renderList.length; index++) {
  21266. serializationObject.renderList.push(this.renderList[index].id);
  21267. }
  21268. return serializationObject;
  21269. };
  21270. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  21271. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  21272. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  21273. return RenderTargetTexture;
  21274. })(BABYLON.Texture);
  21275. BABYLON.RenderTargetTexture = RenderTargetTexture;
  21276. })(BABYLON || (BABYLON = {}));
  21277. var BABYLON;
  21278. (function (BABYLON) {
  21279. var ProceduralTexture = (function (_super) {
  21280. __extends(ProceduralTexture, _super);
  21281. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  21282. if (generateMipMaps === void 0) { generateMipMaps = true; }
  21283. if (isCube === void 0) { isCube = false; }
  21284. _super.call(this, null, scene, !generateMipMaps);
  21285. this.isCube = isCube;
  21286. this.isEnabled = true;
  21287. this._currentRefreshId = -1;
  21288. this._refreshRate = 1;
  21289. this._vertexDeclaration = [2];
  21290. this._vertexStrideSize = 2 * 4;
  21291. this._uniforms = new Array();
  21292. this._samplers = new Array();
  21293. this._textures = new Array();
  21294. this._floats = new Array();
  21295. this._floatsArrays = {};
  21296. this._colors3 = new Array();
  21297. this._colors4 = new Array();
  21298. this._vectors2 = new Array();
  21299. this._vectors3 = new Array();
  21300. this._matrices = new Array();
  21301. this._fallbackTextureUsed = false;
  21302. scene._proceduralTextures.push(this);
  21303. this.name = name;
  21304. this.isRenderTarget = true;
  21305. this._size = size;
  21306. this._generateMipMaps = generateMipMaps;
  21307. this.setFragment(fragment);
  21308. this._fallbackTexture = fallbackTexture;
  21309. if (isCube) {
  21310. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21311. this.setFloat("face", 0);
  21312. }
  21313. else {
  21314. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  21315. }
  21316. // VBO
  21317. var vertices = [];
  21318. vertices.push(1, 1);
  21319. vertices.push(-1, 1);
  21320. vertices.push(-1, -1);
  21321. vertices.push(1, -1);
  21322. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21323. // Indices
  21324. var indices = [];
  21325. indices.push(0);
  21326. indices.push(1);
  21327. indices.push(2);
  21328. indices.push(0);
  21329. indices.push(2);
  21330. indices.push(3);
  21331. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21332. }
  21333. ProceduralTexture.prototype.reset = function () {
  21334. if (this._effect === undefined) {
  21335. return;
  21336. }
  21337. var engine = this.getScene().getEngine();
  21338. engine._releaseEffect(this._effect);
  21339. };
  21340. ProceduralTexture.prototype.isReady = function () {
  21341. var _this = this;
  21342. var engine = this.getScene().getEngine();
  21343. var shaders;
  21344. if (!this._fragment) {
  21345. return false;
  21346. }
  21347. if (this._fallbackTextureUsed) {
  21348. return true;
  21349. }
  21350. if (this._fragment.fragmentElement !== undefined) {
  21351. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  21352. }
  21353. else {
  21354. shaders = { vertex: "procedural", fragment: this._fragment };
  21355. }
  21356. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  21357. _this.releaseInternalTexture();
  21358. if (_this._fallbackTexture) {
  21359. _this._texture = _this._fallbackTexture._texture;
  21360. _this._texture.references++;
  21361. }
  21362. _this._fallbackTextureUsed = true;
  21363. });
  21364. return this._effect.isReady();
  21365. };
  21366. ProceduralTexture.prototype.resetRefreshCounter = function () {
  21367. this._currentRefreshId = -1;
  21368. };
  21369. ProceduralTexture.prototype.setFragment = function (fragment) {
  21370. this._fragment = fragment;
  21371. };
  21372. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  21373. get: function () {
  21374. return this._refreshRate;
  21375. },
  21376. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21377. set: function (value) {
  21378. this._refreshRate = value;
  21379. this.resetRefreshCounter();
  21380. },
  21381. enumerable: true,
  21382. configurable: true
  21383. });
  21384. ProceduralTexture.prototype._shouldRender = function () {
  21385. if (!this.isEnabled || !this.isReady() || !this._texture) {
  21386. return false;
  21387. }
  21388. if (this._fallbackTextureUsed) {
  21389. return false;
  21390. }
  21391. if (this._currentRefreshId === -1) {
  21392. this._currentRefreshId = 1;
  21393. return true;
  21394. }
  21395. if (this.refreshRate === this._currentRefreshId) {
  21396. this._currentRefreshId = 1;
  21397. return true;
  21398. }
  21399. this._currentRefreshId++;
  21400. return false;
  21401. };
  21402. ProceduralTexture.prototype.getRenderSize = function () {
  21403. return this._size;
  21404. };
  21405. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  21406. if (this._fallbackTextureUsed) {
  21407. return;
  21408. }
  21409. this.releaseInternalTexture();
  21410. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21411. };
  21412. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21413. if (this._uniforms.indexOf(uniformName) === -1) {
  21414. this._uniforms.push(uniformName);
  21415. }
  21416. };
  21417. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21418. if (this._samplers.indexOf(name) === -1) {
  21419. this._samplers.push(name);
  21420. }
  21421. this._textures[name] = texture;
  21422. return this;
  21423. };
  21424. ProceduralTexture.prototype.setFloat = function (name, value) {
  21425. this._checkUniform(name);
  21426. this._floats[name] = value;
  21427. return this;
  21428. };
  21429. ProceduralTexture.prototype.setFloats = function (name, value) {
  21430. this._checkUniform(name);
  21431. this._floatsArrays[name] = value;
  21432. return this;
  21433. };
  21434. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21435. this._checkUniform(name);
  21436. this._colors3[name] = value;
  21437. return this;
  21438. };
  21439. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21440. this._checkUniform(name);
  21441. this._colors4[name] = value;
  21442. return this;
  21443. };
  21444. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21445. this._checkUniform(name);
  21446. this._vectors2[name] = value;
  21447. return this;
  21448. };
  21449. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21450. this._checkUniform(name);
  21451. this._vectors3[name] = value;
  21452. return this;
  21453. };
  21454. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21455. this._checkUniform(name);
  21456. this._matrices[name] = value;
  21457. return this;
  21458. };
  21459. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21460. var scene = this.getScene();
  21461. var engine = scene.getEngine();
  21462. // Render
  21463. engine.enableEffect(this._effect);
  21464. engine.setState(false);
  21465. // Texture
  21466. for (var name in this._textures) {
  21467. this._effect.setTexture(name, this._textures[name]);
  21468. }
  21469. // Float
  21470. for (name in this._floats) {
  21471. this._effect.setFloat(name, this._floats[name]);
  21472. }
  21473. // Floats
  21474. for (name in this._floatsArrays) {
  21475. this._effect.setArray(name, this._floatsArrays[name]);
  21476. }
  21477. // Color3
  21478. for (name in this._colors3) {
  21479. this._effect.setColor3(name, this._colors3[name]);
  21480. }
  21481. // Color4
  21482. for (name in this._colors4) {
  21483. var color = this._colors4[name];
  21484. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21485. }
  21486. // Vector2
  21487. for (name in this._vectors2) {
  21488. this._effect.setVector2(name, this._vectors2[name]);
  21489. }
  21490. // Vector3
  21491. for (name in this._vectors3) {
  21492. this._effect.setVector3(name, this._vectors3[name]);
  21493. }
  21494. // Matrix
  21495. for (name in this._matrices) {
  21496. this._effect.setMatrix(name, this._matrices[name]);
  21497. }
  21498. // VBOs
  21499. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21500. if (this.isCube) {
  21501. for (var face = 0; face < 6; face++) {
  21502. engine.bindFramebuffer(this._texture, face);
  21503. this._effect.setFloat("face", face);
  21504. // Clear
  21505. engine.clear(scene.clearColor, true, true);
  21506. // Draw order
  21507. engine.draw(true, 0, 6);
  21508. // Mipmaps
  21509. if (face === 5) {
  21510. engine.generateMipMapsForCubemap(this._texture);
  21511. }
  21512. }
  21513. }
  21514. else {
  21515. engine.bindFramebuffer(this._texture);
  21516. // Clear
  21517. engine.clear(scene.clearColor, true, true);
  21518. // Draw order
  21519. engine.draw(true, 0, 6);
  21520. }
  21521. // Unbind
  21522. engine.unBindFramebuffer(this._texture, this.isCube);
  21523. if (this.onGenerated) {
  21524. this.onGenerated();
  21525. }
  21526. };
  21527. ProceduralTexture.prototype.clone = function () {
  21528. var textureSize = this.getSize();
  21529. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21530. // Base texture
  21531. newTexture.hasAlpha = this.hasAlpha;
  21532. newTexture.level = this.level;
  21533. // RenderTarget Texture
  21534. newTexture.coordinatesMode = this.coordinatesMode;
  21535. return newTexture;
  21536. };
  21537. ProceduralTexture.prototype.dispose = function () {
  21538. var index = this.getScene()._proceduralTextures.indexOf(this);
  21539. if (index >= 0) {
  21540. this.getScene()._proceduralTextures.splice(index, 1);
  21541. }
  21542. _super.prototype.dispose.call(this);
  21543. };
  21544. return ProceduralTexture;
  21545. })(BABYLON.Texture);
  21546. BABYLON.ProceduralTexture = ProceduralTexture;
  21547. })(BABYLON || (BABYLON = {}));
  21548. var BABYLON;
  21549. (function (BABYLON) {
  21550. var MirrorTexture = (function (_super) {
  21551. __extends(MirrorTexture, _super);
  21552. function MirrorTexture(name, size, scene, generateMipMaps) {
  21553. var _this = this;
  21554. _super.call(this, name, size, scene, generateMipMaps, true);
  21555. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21556. this._transformMatrix = BABYLON.Matrix.Zero();
  21557. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21558. this.onBeforeRenderObservable.add(function () {
  21559. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21560. _this._savedViewMatrix = scene.getViewMatrix();
  21561. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21562. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21563. scene.clipPlane = _this.mirrorPlane;
  21564. scene.getEngine().cullBackFaces = false;
  21565. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21566. });
  21567. this.onAfterRenderObservable.add(function () {
  21568. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21569. scene.getEngine().cullBackFaces = true;
  21570. scene._mirroredCameraPosition = null;
  21571. delete scene.clipPlane;
  21572. });
  21573. }
  21574. MirrorTexture.prototype.clone = function () {
  21575. var textureSize = this.getSize();
  21576. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21577. // Base texture
  21578. newTexture.hasAlpha = this.hasAlpha;
  21579. newTexture.level = this.level;
  21580. // Mirror Texture
  21581. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21582. newTexture.renderList = this.renderList.slice(0);
  21583. return newTexture;
  21584. };
  21585. MirrorTexture.prototype.serialize = function () {
  21586. if (!this.name) {
  21587. return null;
  21588. }
  21589. var serializationObject = _super.prototype.serialize.call(this);
  21590. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21591. return serializationObject;
  21592. };
  21593. return MirrorTexture;
  21594. })(BABYLON.RenderTargetTexture);
  21595. BABYLON.MirrorTexture = MirrorTexture;
  21596. })(BABYLON || (BABYLON = {}));
  21597. var BABYLON;
  21598. (function (BABYLON) {
  21599. /**
  21600. * Creates a refraction texture used by refraction channel of the standard material.
  21601. * @param name the texture name
  21602. * @param size size of the underlying texture
  21603. * @param scene root scene
  21604. */
  21605. var RefractionTexture = (function (_super) {
  21606. __extends(RefractionTexture, _super);
  21607. function RefractionTexture(name, size, scene, generateMipMaps) {
  21608. var _this = this;
  21609. _super.call(this, name, size, scene, generateMipMaps, true);
  21610. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21611. this.depth = 2.0;
  21612. this.onBeforeRenderObservable.add(function () {
  21613. scene.clipPlane = _this.refractionPlane;
  21614. });
  21615. this.onAfterRenderObservable.add(function () {
  21616. delete scene.clipPlane;
  21617. });
  21618. }
  21619. RefractionTexture.prototype.clone = function () {
  21620. var textureSize = this.getSize();
  21621. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21622. // Base texture
  21623. newTexture.hasAlpha = this.hasAlpha;
  21624. newTexture.level = this.level;
  21625. // Refraction Texture
  21626. newTexture.refractionPlane = this.refractionPlane.clone();
  21627. newTexture.renderList = this.renderList.slice(0);
  21628. newTexture.depth = this.depth;
  21629. return newTexture;
  21630. };
  21631. RefractionTexture.prototype.serialize = function () {
  21632. if (!this.name) {
  21633. return null;
  21634. }
  21635. var serializationObject = _super.prototype.serialize.call(this);
  21636. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21637. serializationObject.depth = this.depth;
  21638. return serializationObject;
  21639. };
  21640. return RefractionTexture;
  21641. })(BABYLON.RenderTargetTexture);
  21642. BABYLON.RefractionTexture = RefractionTexture;
  21643. })(BABYLON || (BABYLON = {}));
  21644. var BABYLON;
  21645. (function (BABYLON) {
  21646. var DynamicTexture = (function (_super) {
  21647. __extends(DynamicTexture, _super);
  21648. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21650. _super.call(this, null, scene, !generateMipMaps);
  21651. this.name = name;
  21652. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21653. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21654. this._generateMipMaps = generateMipMaps;
  21655. if (options.getContext) {
  21656. this._canvas = options;
  21657. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21658. }
  21659. else {
  21660. this._canvas = document.createElement("canvas");
  21661. if (options.width) {
  21662. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21663. }
  21664. else {
  21665. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21666. }
  21667. }
  21668. var textureSize = this.getSize();
  21669. this._canvas.width = textureSize.width;
  21670. this._canvas.height = textureSize.height;
  21671. this._context = this._canvas.getContext("2d");
  21672. }
  21673. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21674. get: function () {
  21675. return true;
  21676. },
  21677. enumerable: true,
  21678. configurable: true
  21679. });
  21680. DynamicTexture.prototype.scale = function (ratio) {
  21681. var textureSize = this.getSize();
  21682. textureSize.width *= ratio;
  21683. textureSize.height *= ratio;
  21684. this._canvas.width = textureSize.width;
  21685. this._canvas.height = textureSize.height;
  21686. this.releaseInternalTexture();
  21687. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21688. };
  21689. DynamicTexture.prototype.getContext = function () {
  21690. return this._context;
  21691. };
  21692. DynamicTexture.prototype.clear = function () {
  21693. var size = this.getSize();
  21694. this._context.fillRect(0, 0, size.width, size.height);
  21695. };
  21696. DynamicTexture.prototype.update = function (invertY) {
  21697. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21698. };
  21699. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21700. if (update === void 0) { update = true; }
  21701. var size = this.getSize();
  21702. if (clearColor) {
  21703. this._context.fillStyle = clearColor;
  21704. this._context.fillRect(0, 0, size.width, size.height);
  21705. }
  21706. this._context.font = font;
  21707. if (x === null) {
  21708. var textSize = this._context.measureText(text);
  21709. x = (size.width - textSize.width) / 2;
  21710. }
  21711. this._context.fillStyle = color;
  21712. this._context.fillText(text, x, y);
  21713. if (update) {
  21714. this.update(invertY);
  21715. }
  21716. };
  21717. DynamicTexture.prototype.clone = function () {
  21718. var textureSize = this.getSize();
  21719. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21720. // Base texture
  21721. newTexture.hasAlpha = this.hasAlpha;
  21722. newTexture.level = this.level;
  21723. // Dynamic Texture
  21724. newTexture.wrapU = this.wrapU;
  21725. newTexture.wrapV = this.wrapV;
  21726. return newTexture;
  21727. };
  21728. return DynamicTexture;
  21729. })(BABYLON.Texture);
  21730. BABYLON.DynamicTexture = DynamicTexture;
  21731. })(BABYLON || (BABYLON = {}));
  21732. var BABYLON;
  21733. (function (BABYLON) {
  21734. var VideoTexture = (function (_super) {
  21735. __extends(VideoTexture, _super);
  21736. /**
  21737. * Creates a video texture.
  21738. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21739. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21740. * @param {BABYLON.Scene} scene is obviously the current scene.
  21741. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21742. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21743. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21744. */
  21745. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21746. var _this = this;
  21747. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21748. if (invertY === void 0) { invertY = false; }
  21749. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21750. _super.call(this, null, scene, !generateMipMaps, invertY);
  21751. this._autoLaunch = true;
  21752. var urls;
  21753. this.name = name;
  21754. if (urlsOrVideo instanceof HTMLVideoElement) {
  21755. this.video = urlsOrVideo;
  21756. }
  21757. else {
  21758. urls = urlsOrVideo;
  21759. this.video = document.createElement("video");
  21760. this.video.autoplay = false;
  21761. this.video.loop = true;
  21762. }
  21763. this._generateMipMaps = generateMipMaps;
  21764. this._samplingMode = samplingMode;
  21765. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21766. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21767. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21768. }
  21769. else {
  21770. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21771. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21772. this._generateMipMaps = false;
  21773. }
  21774. if (urls) {
  21775. this.video.addEventListener("canplaythrough", function () {
  21776. _this._createTexture();
  21777. });
  21778. urls.forEach(function (url) {
  21779. var source = document.createElement("source");
  21780. source.src = url;
  21781. _this.video.appendChild(source);
  21782. });
  21783. }
  21784. else {
  21785. this._createTexture();
  21786. }
  21787. this._lastUpdate = BABYLON.Tools.Now;
  21788. }
  21789. VideoTexture.prototype._createTexture = function () {
  21790. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21791. this._texture.isReady = true;
  21792. };
  21793. VideoTexture.prototype.update = function () {
  21794. if (this._autoLaunch) {
  21795. this._autoLaunch = false;
  21796. this.video.play();
  21797. }
  21798. var now = BABYLON.Tools.Now;
  21799. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21800. return false;
  21801. }
  21802. this._lastUpdate = now;
  21803. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21804. return true;
  21805. };
  21806. return VideoTexture;
  21807. })(BABYLON.Texture);
  21808. BABYLON.VideoTexture = VideoTexture;
  21809. })(BABYLON || (BABYLON = {}));
  21810. var BABYLON;
  21811. (function (BABYLON) {
  21812. var CustomProceduralTexture = (function (_super) {
  21813. __extends(CustomProceduralTexture, _super);
  21814. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21815. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21816. this._animate = true;
  21817. this._time = 0;
  21818. this._texturePath = texturePath;
  21819. //Try to load json
  21820. this.loadJson(texturePath);
  21821. this.refreshRate = 1;
  21822. }
  21823. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21824. var _this = this;
  21825. var that = this;
  21826. function noConfigFile() {
  21827. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21828. try {
  21829. that.setFragment(that._texturePath);
  21830. }
  21831. catch (ex) {
  21832. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21833. }
  21834. }
  21835. var configFileUrl = jsonUrl + "/config.json";
  21836. var xhr = new XMLHttpRequest();
  21837. xhr.open("GET", configFileUrl, true);
  21838. xhr.addEventListener("load", function () {
  21839. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21840. try {
  21841. _this._config = JSON.parse(xhr.response);
  21842. _this.updateShaderUniforms();
  21843. _this.updateTextures();
  21844. _this.setFragment(_this._texturePath + "/custom");
  21845. _this._animate = _this._config.animate;
  21846. _this.refreshRate = _this._config.refreshrate;
  21847. }
  21848. catch (ex) {
  21849. noConfigFile();
  21850. }
  21851. }
  21852. else {
  21853. noConfigFile();
  21854. }
  21855. }, false);
  21856. xhr.addEventListener("error", function () {
  21857. noConfigFile();
  21858. }, false);
  21859. try {
  21860. xhr.send();
  21861. }
  21862. catch (ex) {
  21863. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21864. }
  21865. };
  21866. CustomProceduralTexture.prototype.isReady = function () {
  21867. if (!_super.prototype.isReady.call(this)) {
  21868. return false;
  21869. }
  21870. for (var name in this._textures) {
  21871. var texture = this._textures[name];
  21872. if (!texture.isReady()) {
  21873. return false;
  21874. }
  21875. }
  21876. return true;
  21877. };
  21878. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21879. if (this._animate) {
  21880. this._time += this.getScene().getAnimationRatio() * 0.03;
  21881. this.updateShaderUniforms();
  21882. }
  21883. _super.prototype.render.call(this, useCameraPostProcess);
  21884. };
  21885. CustomProceduralTexture.prototype.updateTextures = function () {
  21886. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21887. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21888. }
  21889. };
  21890. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21891. if (this._config) {
  21892. for (var j = 0; j < this._config.uniforms.length; j++) {
  21893. var uniform = this._config.uniforms[j];
  21894. switch (uniform.type) {
  21895. case "float":
  21896. this.setFloat(uniform.name, uniform.value);
  21897. break;
  21898. case "color3":
  21899. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21900. break;
  21901. case "color4":
  21902. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21903. break;
  21904. case "vector2":
  21905. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21906. break;
  21907. case "vector3":
  21908. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21909. break;
  21910. }
  21911. }
  21912. }
  21913. this.setFloat("time", this._time);
  21914. };
  21915. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21916. get: function () {
  21917. return this._animate;
  21918. },
  21919. set: function (value) {
  21920. this._animate = value;
  21921. },
  21922. enumerable: true,
  21923. configurable: true
  21924. });
  21925. return CustomProceduralTexture;
  21926. })(BABYLON.ProceduralTexture);
  21927. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21928. })(BABYLON || (BABYLON = {}));
  21929. var BABYLON;
  21930. (function (BABYLON) {
  21931. var EffectFallbacks = (function () {
  21932. function EffectFallbacks() {
  21933. this._defines = {};
  21934. this._currentRank = 32;
  21935. this._maxRank = -1;
  21936. }
  21937. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21938. if (!this._defines[rank]) {
  21939. if (rank < this._currentRank) {
  21940. this._currentRank = rank;
  21941. }
  21942. if (rank > this._maxRank) {
  21943. this._maxRank = rank;
  21944. }
  21945. this._defines[rank] = new Array();
  21946. }
  21947. this._defines[rank].push(define);
  21948. };
  21949. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21950. this._meshRank = rank;
  21951. this._mesh = mesh;
  21952. if (rank > this._maxRank) {
  21953. this._maxRank = rank;
  21954. }
  21955. };
  21956. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21957. get: function () {
  21958. return this._currentRank <= this._maxRank;
  21959. },
  21960. enumerable: true,
  21961. configurable: true
  21962. });
  21963. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21964. var currentFallbacks = this._defines[this._currentRank];
  21965. for (var index = 0; index < currentFallbacks.length; index++) {
  21966. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21967. }
  21968. if (this._mesh && this._currentRank === this._meshRank) {
  21969. this._mesh.computeBonesUsingShaders = false;
  21970. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21971. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21972. }
  21973. this._currentRank++;
  21974. return currentDefines;
  21975. };
  21976. return EffectFallbacks;
  21977. })();
  21978. BABYLON.EffectFallbacks = EffectFallbacks;
  21979. var Effect = (function () {
  21980. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21981. var _this = this;
  21982. this._isReady = false;
  21983. this._compilationError = "";
  21984. this._valueCache = [];
  21985. this._engine = engine;
  21986. this.name = baseName;
  21987. this.defines = defines;
  21988. this._uniformsNames = uniformsNames.concat(samplers);
  21989. this._samplers = samplers;
  21990. this._attributesNames = attributesNames;
  21991. this.onError = onError;
  21992. this.onCompiled = onCompiled;
  21993. this._indexParameters = indexParameters;
  21994. var vertexSource;
  21995. var fragmentSource;
  21996. if (baseName.vertexElement) {
  21997. vertexSource = document.getElementById(baseName.vertexElement);
  21998. if (!vertexSource) {
  21999. vertexSource = baseName.vertexElement;
  22000. }
  22001. }
  22002. else {
  22003. vertexSource = baseName.vertex || baseName;
  22004. }
  22005. if (baseName.fragmentElement) {
  22006. fragmentSource = document.getElementById(baseName.fragmentElement);
  22007. if (!fragmentSource) {
  22008. fragmentSource = baseName.fragmentElement;
  22009. }
  22010. }
  22011. else {
  22012. fragmentSource = baseName.fragment || baseName;
  22013. }
  22014. this._loadVertexShader(vertexSource, function (vertexCode) {
  22015. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22016. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22017. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22018. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  22019. });
  22020. });
  22021. });
  22022. });
  22023. }
  22024. // Properties
  22025. Effect.prototype.isReady = function () {
  22026. return this._isReady;
  22027. };
  22028. Effect.prototype.getProgram = function () {
  22029. return this._program;
  22030. };
  22031. Effect.prototype.getAttributesNames = function () {
  22032. return this._attributesNames;
  22033. };
  22034. Effect.prototype.getAttributeLocation = function (index) {
  22035. return this._attributes[index];
  22036. };
  22037. Effect.prototype.getAttributeLocationByName = function (name) {
  22038. var index = this._attributesNames.indexOf(name);
  22039. return this._attributes[index];
  22040. };
  22041. Effect.prototype.getAttributesCount = function () {
  22042. return this._attributes.length;
  22043. };
  22044. Effect.prototype.getUniformIndex = function (uniformName) {
  22045. return this._uniformsNames.indexOf(uniformName);
  22046. };
  22047. Effect.prototype.getUniform = function (uniformName) {
  22048. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22049. };
  22050. Effect.prototype.getSamplers = function () {
  22051. return this._samplers;
  22052. };
  22053. Effect.prototype.getCompilationError = function () {
  22054. return this._compilationError;
  22055. };
  22056. // Methods
  22057. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22058. // DOM element ?
  22059. if (vertex instanceof HTMLElement) {
  22060. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22061. callback(vertexCode);
  22062. return;
  22063. }
  22064. // Is in local store ?
  22065. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22066. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22067. return;
  22068. }
  22069. var vertexShaderUrl;
  22070. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22071. vertexShaderUrl = vertex;
  22072. }
  22073. else {
  22074. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22075. }
  22076. // Vertex shader
  22077. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22078. };
  22079. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22080. // DOM element ?
  22081. if (fragment instanceof HTMLElement) {
  22082. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22083. callback(fragmentCode);
  22084. return;
  22085. }
  22086. // Is in local store ?
  22087. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22088. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22089. return;
  22090. }
  22091. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22092. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22093. return;
  22094. }
  22095. var fragmentShaderUrl;
  22096. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22097. fragmentShaderUrl = fragment;
  22098. }
  22099. else {
  22100. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22101. }
  22102. // Fragment shader
  22103. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22104. };
  22105. Effect.prototype._dumpShadersName = function () {
  22106. if (this.name.vertexElement) {
  22107. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  22108. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  22109. }
  22110. else if (this.name.vertex) {
  22111. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  22112. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  22113. }
  22114. else {
  22115. BABYLON.Tools.Error("Vertex shader:" + this.name);
  22116. BABYLON.Tools.Error("Fragment shader:" + this.name);
  22117. }
  22118. };
  22119. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22120. var _this = this;
  22121. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22122. var match = regex.exec(sourceCode);
  22123. var returnValue = new String(sourceCode);
  22124. while (match != null) {
  22125. var includeFile = match[1];
  22126. if (Effect.IncludesShadersStore[includeFile]) {
  22127. // Substitution
  22128. var includeContent = Effect.IncludesShadersStore[includeFile];
  22129. if (match[2]) {
  22130. var splits = match[3].split(",");
  22131. for (var index = 0; index < splits.length; index += 2) {
  22132. var source = new RegExp(splits[index], "g");
  22133. var dest = splits[index + 1];
  22134. includeContent = includeContent.replace(source, dest);
  22135. }
  22136. }
  22137. if (match[4]) {
  22138. var indexString = match[5];
  22139. if (indexString.indexOf("..") !== -1) {
  22140. var indexSplits = indexString.split("..");
  22141. var minIndex = parseInt(indexSplits[0]);
  22142. var maxIndex = parseInt(indexSplits[1]);
  22143. var sourceIncludeContent = includeContent.slice(0);
  22144. includeContent = "";
  22145. if (isNaN(maxIndex)) {
  22146. maxIndex = this._indexParameters[indexSplits[1]];
  22147. }
  22148. for (var i = minIndex; i <= maxIndex; i++) {
  22149. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22150. }
  22151. }
  22152. else {
  22153. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22154. }
  22155. }
  22156. // Replace
  22157. returnValue = returnValue.replace(match[0], includeContent);
  22158. }
  22159. else {
  22160. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22161. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22162. Effect.IncludesShadersStore[includeFile] = fileContent;
  22163. _this._processIncludes(returnValue, callback);
  22164. });
  22165. return;
  22166. }
  22167. match = regex.exec(sourceCode);
  22168. }
  22169. callback(returnValue);
  22170. };
  22171. Effect.prototype._processPrecision = function (source) {
  22172. if (source.indexOf("precision highp float") === -1) {
  22173. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22174. source = "precision mediump float;\n" + source;
  22175. }
  22176. else {
  22177. source = "precision highp float;\n" + source;
  22178. }
  22179. }
  22180. else {
  22181. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22182. source = source.replace("precision highp float", "precision mediump float");
  22183. }
  22184. }
  22185. return source;
  22186. };
  22187. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22188. try {
  22189. var engine = this._engine;
  22190. // Precision
  22191. vertexSourceCode = this._processPrecision(vertexSourceCode);
  22192. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  22193. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22194. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22195. this._attributes = engine.getAttributes(this._program, attributesNames);
  22196. for (var index = 0; index < this._samplers.length; index++) {
  22197. var sampler = this.getUniform(this._samplers[index]);
  22198. if (sampler == null) {
  22199. this._samplers.splice(index, 1);
  22200. index--;
  22201. }
  22202. }
  22203. engine.bindSamplers(this);
  22204. this._isReady = true;
  22205. if (this.onCompiled) {
  22206. this.onCompiled(this);
  22207. }
  22208. }
  22209. catch (e) {
  22210. // Is it a problem with precision?
  22211. if (e.message.indexOf("highp") !== -1) {
  22212. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  22213. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  22214. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22215. return;
  22216. }
  22217. // Let's go through fallbacks then
  22218. if (fallbacks && fallbacks.isMoreFallbacks) {
  22219. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  22220. this._dumpShadersName();
  22221. defines = fallbacks.reduce(defines);
  22222. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22223. }
  22224. else {
  22225. BABYLON.Tools.Error("Unable to compile effect: ");
  22226. this._dumpShadersName();
  22227. BABYLON.Tools.Error("Defines: " + defines);
  22228. BABYLON.Tools.Error("Error: " + e.message);
  22229. this._compilationError = e.message;
  22230. if (this.onError) {
  22231. this.onError(this, this._compilationError);
  22232. }
  22233. }
  22234. }
  22235. };
  22236. Object.defineProperty(Effect.prototype, "isSupported", {
  22237. get: function () {
  22238. return this._compilationError === "";
  22239. },
  22240. enumerable: true,
  22241. configurable: true
  22242. });
  22243. Effect.prototype._bindTexture = function (channel, texture) {
  22244. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22245. };
  22246. Effect.prototype.setTexture = function (channel, texture) {
  22247. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  22248. };
  22249. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22250. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22251. };
  22252. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22253. if (!this._valueCache[uniformName]) {
  22254. this._valueCache[uniformName] = new BABYLON.Matrix();
  22255. }
  22256. for (var index = 0; index < 16; index++) {
  22257. this._valueCache[uniformName].m[index] = matrix.m[index];
  22258. }
  22259. };
  22260. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22261. if (!this._valueCache[uniformName]) {
  22262. this._valueCache[uniformName] = [x, y];
  22263. return;
  22264. }
  22265. this._valueCache[uniformName][0] = x;
  22266. this._valueCache[uniformName][1] = y;
  22267. };
  22268. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22269. if (!this._valueCache[uniformName]) {
  22270. this._valueCache[uniformName] = [x, y, z];
  22271. return;
  22272. }
  22273. this._valueCache[uniformName][0] = x;
  22274. this._valueCache[uniformName][1] = y;
  22275. this._valueCache[uniformName][2] = z;
  22276. };
  22277. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22278. if (!this._valueCache[uniformName]) {
  22279. this._valueCache[uniformName] = [x, y, z, w];
  22280. return;
  22281. }
  22282. this._valueCache[uniformName][0] = x;
  22283. this._valueCache[uniformName][1] = y;
  22284. this._valueCache[uniformName][2] = z;
  22285. this._valueCache[uniformName][3] = w;
  22286. };
  22287. Effect.prototype.setArray = function (uniformName, array) {
  22288. this._engine.setArray(this.getUniform(uniformName), array);
  22289. return this;
  22290. };
  22291. Effect.prototype.setArray2 = function (uniformName, array) {
  22292. this._engine.setArray2(this.getUniform(uniformName), array);
  22293. return this;
  22294. };
  22295. Effect.prototype.setArray3 = function (uniformName, array) {
  22296. this._engine.setArray3(this.getUniform(uniformName), array);
  22297. return this;
  22298. };
  22299. Effect.prototype.setArray4 = function (uniformName, array) {
  22300. this._engine.setArray4(this.getUniform(uniformName), array);
  22301. return this;
  22302. };
  22303. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22304. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22305. return this;
  22306. };
  22307. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22308. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  22309. // return this;
  22310. // this._cacheMatrix(uniformName, matrix);
  22311. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22312. return this;
  22313. };
  22314. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22315. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22316. return this;
  22317. };
  22318. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  22319. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  22320. return this;
  22321. };
  22322. Effect.prototype.setFloat = function (uniformName, value) {
  22323. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  22324. return this;
  22325. this._valueCache[uniformName] = value;
  22326. this._engine.setFloat(this.getUniform(uniformName), value);
  22327. return this;
  22328. };
  22329. Effect.prototype.setBool = function (uniformName, bool) {
  22330. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  22331. return this;
  22332. this._valueCache[uniformName] = bool;
  22333. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22334. return this;
  22335. };
  22336. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22337. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  22338. return this;
  22339. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  22340. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22341. return this;
  22342. };
  22343. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22344. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  22345. return this;
  22346. this._cacheFloat2(uniformName, x, y);
  22347. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22348. return this;
  22349. };
  22350. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22351. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  22352. return this;
  22353. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  22354. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22355. return this;
  22356. };
  22357. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22358. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  22359. return this;
  22360. this._cacheFloat3(uniformName, x, y, z);
  22361. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22362. return this;
  22363. };
  22364. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22365. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  22366. return this;
  22367. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  22368. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22369. return this;
  22370. };
  22371. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22372. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  22373. return this;
  22374. this._cacheFloat4(uniformName, x, y, z, w);
  22375. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22376. return this;
  22377. };
  22378. Effect.prototype.setColor3 = function (uniformName, color3) {
  22379. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  22380. return this;
  22381. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  22382. this._engine.setColor3(this.getUniform(uniformName), color3);
  22383. return this;
  22384. };
  22385. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22386. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
  22387. return this;
  22388. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  22389. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22390. return this;
  22391. };
  22392. // Statics
  22393. Effect.ShadersStore = {};
  22394. Effect.IncludesShadersStore = {};
  22395. return Effect;
  22396. })();
  22397. BABYLON.Effect = Effect;
  22398. })(BABYLON || (BABYLON = {}));
  22399. var BABYLON;
  22400. (function (BABYLON) {
  22401. var MaterialHelper = (function () {
  22402. function MaterialHelper() {
  22403. }
  22404. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  22405. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22406. var lightIndex = 0;
  22407. var needNormals = false;
  22408. var needRebuild = false;
  22409. for (var index = 0; index < scene.lights.length; index++) {
  22410. var light = scene.lights[index];
  22411. if (!light.isEnabled()) {
  22412. continue;
  22413. }
  22414. // Excluded check
  22415. if (light._excludedMeshesIds.length > 0) {
  22416. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  22417. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  22418. if (excludedMesh) {
  22419. light.excludedMeshes.push(excludedMesh);
  22420. }
  22421. }
  22422. light._excludedMeshesIds = [];
  22423. }
  22424. // Included check
  22425. if (light._includedOnlyMeshesIds.length > 0) {
  22426. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  22427. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22428. if (includedOnlyMesh) {
  22429. light.includedOnlyMeshes.push(includedOnlyMesh);
  22430. }
  22431. }
  22432. light._includedOnlyMeshesIds = [];
  22433. }
  22434. if (!light.canAffectMesh(mesh)) {
  22435. continue;
  22436. }
  22437. needNormals = true;
  22438. if (defines["LIGHT" + lightIndex] === undefined) {
  22439. needRebuild = true;
  22440. }
  22441. defines["LIGHT" + lightIndex] = true;
  22442. var type;
  22443. if (light instanceof BABYLON.SpotLight) {
  22444. type = "SPOTLIGHT" + lightIndex;
  22445. }
  22446. else if (light instanceof BABYLON.HemisphericLight) {
  22447. type = "HEMILIGHT" + lightIndex;
  22448. }
  22449. else if (light instanceof BABYLON.PointLight) {
  22450. type = "POINTLIGHT" + lightIndex;
  22451. }
  22452. else {
  22453. type = "DIRLIGHT" + lightIndex;
  22454. }
  22455. if (defines[type] === undefined) {
  22456. needRebuild = true;
  22457. }
  22458. defines[type] = true;
  22459. // Specular
  22460. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22461. defines["SPECULARTERM"] = true;
  22462. }
  22463. // Shadows
  22464. if (scene.shadowsEnabled) {
  22465. var shadowGenerator = light.getShadowGenerator();
  22466. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22467. if (defines["SHADOW" + lightIndex] === undefined) {
  22468. needRebuild = true;
  22469. }
  22470. defines["SHADOW" + lightIndex] = true;
  22471. defines["SHADOWS"] = true;
  22472. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22473. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  22474. needRebuild = true;
  22475. }
  22476. defines["SHADOWVSM" + lightIndex] = true;
  22477. }
  22478. if (shadowGenerator.usePoissonSampling) {
  22479. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  22480. needRebuild = true;
  22481. }
  22482. defines["SHADOWPCF" + lightIndex] = true;
  22483. }
  22484. }
  22485. }
  22486. lightIndex++;
  22487. if (lightIndex === maxSimultaneousLights)
  22488. break;
  22489. }
  22490. if (needRebuild) {
  22491. defines.rebuild();
  22492. }
  22493. return needNormals;
  22494. };
  22495. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  22496. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22497. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22498. if (!defines["LIGHT" + lightIndex]) {
  22499. break;
  22500. }
  22501. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22502. samplersList.push("shadowSampler" + lightIndex);
  22503. }
  22504. };
  22505. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22506. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22507. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22508. if (!defines["LIGHT" + lightIndex]) {
  22509. break;
  22510. }
  22511. if (lightIndex > 0) {
  22512. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22513. }
  22514. if (defines["SHADOW" + lightIndex]) {
  22515. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22516. }
  22517. if (defines["SHADOWPCF" + lightIndex]) {
  22518. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22519. }
  22520. if (defines["SHADOWVSM" + lightIndex]) {
  22521. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22522. }
  22523. }
  22524. };
  22525. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22526. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22527. fallbacks.addCPUSkinningFallback(0, mesh);
  22528. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22529. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22530. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22531. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22532. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22533. }
  22534. }
  22535. };
  22536. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22537. if (defines["INSTANCES"]) {
  22538. attribs.push("world0");
  22539. attribs.push("world1");
  22540. attribs.push("world2");
  22541. attribs.push("world3");
  22542. }
  22543. };
  22544. // Bindings
  22545. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22546. var shadowGenerator = light.getShadowGenerator();
  22547. if (mesh.receiveShadows && shadowGenerator) {
  22548. if (!light.needCube()) {
  22549. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22550. }
  22551. else {
  22552. if (!depthValuesAlreadySet) {
  22553. depthValuesAlreadySet = true;
  22554. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22555. }
  22556. }
  22557. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22558. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22559. }
  22560. return depthValuesAlreadySet;
  22561. };
  22562. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22563. if (light instanceof BABYLON.PointLight) {
  22564. // Point Light
  22565. light.transferToEffect(effect, "vLightData" + lightIndex);
  22566. }
  22567. else if (light instanceof BABYLON.DirectionalLight) {
  22568. // Directional Light
  22569. light.transferToEffect(effect, "vLightData" + lightIndex);
  22570. }
  22571. else if (light instanceof BABYLON.SpotLight) {
  22572. // Spot Light
  22573. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22574. }
  22575. else if (light instanceof BABYLON.HemisphericLight) {
  22576. // Hemispheric Light
  22577. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22578. }
  22579. };
  22580. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22581. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22582. var lightIndex = 0;
  22583. var depthValuesAlreadySet = false;
  22584. for (var index = 0; index < scene.lights.length; index++) {
  22585. var light = scene.lights[index];
  22586. if (!light.isEnabled()) {
  22587. continue;
  22588. }
  22589. if (!light.canAffectMesh(mesh)) {
  22590. continue;
  22591. }
  22592. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22593. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22594. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22595. if (defines["SPECULARTERM"]) {
  22596. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22597. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22598. }
  22599. // Shadows
  22600. if (scene.shadowsEnabled) {
  22601. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22602. }
  22603. lightIndex++;
  22604. if (lightIndex === maxSimultaneousLights)
  22605. break;
  22606. }
  22607. };
  22608. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22609. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22610. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22611. effect.setColor3("vFogColor", scene.fogColor);
  22612. }
  22613. };
  22614. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22615. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22616. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22617. }
  22618. };
  22619. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22620. if (defines["LOGARITHMICDEPTH"]) {
  22621. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22622. }
  22623. };
  22624. MaterialHelper.BindClipPlane = function (effect, scene) {
  22625. if (scene.clipPlane) {
  22626. var clipPlane = scene.clipPlane;
  22627. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22628. }
  22629. };
  22630. return MaterialHelper;
  22631. })();
  22632. BABYLON.MaterialHelper = MaterialHelper;
  22633. })(BABYLON || (BABYLON = {}));
  22634. var BABYLON;
  22635. (function (BABYLON) {
  22636. var FresnelParameters = (function () {
  22637. function FresnelParameters() {
  22638. this.isEnabled = true;
  22639. this.leftColor = BABYLON.Color3.White();
  22640. this.rightColor = BABYLON.Color3.Black();
  22641. this.bias = 0;
  22642. this.power = 1;
  22643. }
  22644. FresnelParameters.prototype.clone = function () {
  22645. var newFresnelParameters = new FresnelParameters();
  22646. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22647. return new FresnelParameters;
  22648. };
  22649. FresnelParameters.prototype.serialize = function () {
  22650. var serializationObject = {};
  22651. serializationObject.isEnabled = this.isEnabled;
  22652. serializationObject.leftColor = this.leftColor;
  22653. serializationObject.rightColor = this.rightColor;
  22654. serializationObject.bias = this.bias;
  22655. serializationObject.power = this.power;
  22656. return serializationObject;
  22657. };
  22658. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22659. var fresnelParameters = new FresnelParameters();
  22660. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22661. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22662. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22663. fresnelParameters.bias = parsedFresnelParameters.bias;
  22664. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22665. return fresnelParameters;
  22666. };
  22667. return FresnelParameters;
  22668. })();
  22669. BABYLON.FresnelParameters = FresnelParameters;
  22670. })(BABYLON || (BABYLON = {}));
  22671. var BABYLON;
  22672. (function (BABYLON) {
  22673. var MaterialDefines = (function () {
  22674. function MaterialDefines() {
  22675. }
  22676. MaterialDefines.prototype.rebuild = function () {
  22677. if (this._keys) {
  22678. delete this._keys;
  22679. }
  22680. this._keys = Object.keys(this);
  22681. };
  22682. MaterialDefines.prototype.isEqual = function (other) {
  22683. if (this._keys.length !== other._keys.length) {
  22684. return false;
  22685. }
  22686. for (var index = 0; index < this._keys.length; index++) {
  22687. var prop = this._keys[index];
  22688. if (this[prop] !== other[prop]) {
  22689. return false;
  22690. }
  22691. }
  22692. return true;
  22693. };
  22694. MaterialDefines.prototype.cloneTo = function (other) {
  22695. if (this._keys.length !== other._keys.length) {
  22696. other._keys = this._keys.slice(0);
  22697. }
  22698. for (var index = 0; index < this._keys.length; index++) {
  22699. var prop = this._keys[index];
  22700. other[prop] = this[prop];
  22701. }
  22702. };
  22703. MaterialDefines.prototype.reset = function () {
  22704. for (var index = 0; index < this._keys.length; index++) {
  22705. var prop = this._keys[index];
  22706. if (typeof (this[prop]) === "number") {
  22707. this[prop] = 0;
  22708. }
  22709. else {
  22710. this[prop] = false;
  22711. }
  22712. }
  22713. };
  22714. MaterialDefines.prototype.toString = function () {
  22715. var result = "";
  22716. for (var index = 0; index < this._keys.length; index++) {
  22717. var prop = this._keys[index];
  22718. if (typeof (this[prop]) === "number") {
  22719. result += "#define " + prop + " " + this[prop] + "\n";
  22720. }
  22721. else if (this[prop]) {
  22722. result += "#define " + prop + "\n";
  22723. }
  22724. }
  22725. return result;
  22726. };
  22727. return MaterialDefines;
  22728. })();
  22729. BABYLON.MaterialDefines = MaterialDefines;
  22730. var Material = (function () {
  22731. function Material(name, scene, doNotAdd) {
  22732. this.name = name;
  22733. this.checkReadyOnEveryCall = false;
  22734. this.checkReadyOnlyOnce = false;
  22735. this.state = "";
  22736. this.alpha = 1.0;
  22737. this.backFaceCulling = true;
  22738. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22739. /**
  22740. * An event triggered when the material is disposed.
  22741. * @type {BABYLON.Observable}
  22742. */
  22743. this.onDisposeObservable = new BABYLON.Observable();
  22744. /**
  22745. * An event triggered when the material is compiled.
  22746. * @type {BABYLON.Observable}
  22747. */
  22748. this.onBindObservable = new BABYLON.Observable();
  22749. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22750. this.disableDepthWrite = false;
  22751. this.fogEnabled = true;
  22752. this.pointSize = 1.0;
  22753. this.zOffset = 0;
  22754. this._wasPreviouslyReady = false;
  22755. this._fillMode = Material.TriangleFillMode;
  22756. this.id = name;
  22757. this._scene = scene;
  22758. if (!doNotAdd) {
  22759. scene.materials.push(this);
  22760. }
  22761. }
  22762. Object.defineProperty(Material, "TriangleFillMode", {
  22763. get: function () {
  22764. return Material._TriangleFillMode;
  22765. },
  22766. enumerable: true,
  22767. configurable: true
  22768. });
  22769. Object.defineProperty(Material, "WireFrameFillMode", {
  22770. get: function () {
  22771. return Material._WireFrameFillMode;
  22772. },
  22773. enumerable: true,
  22774. configurable: true
  22775. });
  22776. Object.defineProperty(Material, "PointFillMode", {
  22777. get: function () {
  22778. return Material._PointFillMode;
  22779. },
  22780. enumerable: true,
  22781. configurable: true
  22782. });
  22783. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22784. get: function () {
  22785. return Material._ClockWiseSideOrientation;
  22786. },
  22787. enumerable: true,
  22788. configurable: true
  22789. });
  22790. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22791. get: function () {
  22792. return Material._CounterClockWiseSideOrientation;
  22793. },
  22794. enumerable: true,
  22795. configurable: true
  22796. });
  22797. Object.defineProperty(Material.prototype, "onDispose", {
  22798. set: function (callback) {
  22799. if (this._onDisposeObserver) {
  22800. this.onDisposeObservable.remove(this._onDisposeObserver);
  22801. }
  22802. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22803. },
  22804. enumerable: true,
  22805. configurable: true
  22806. });
  22807. Object.defineProperty(Material.prototype, "onBind", {
  22808. set: function (callback) {
  22809. if (this._onBindObserver) {
  22810. this.onBindObservable.remove(this._onBindObserver);
  22811. }
  22812. this._onBindObserver = this.onBindObservable.add(callback);
  22813. },
  22814. enumerable: true,
  22815. configurable: true
  22816. });
  22817. Object.defineProperty(Material.prototype, "wireframe", {
  22818. get: function () {
  22819. return this._fillMode === Material.WireFrameFillMode;
  22820. },
  22821. set: function (value) {
  22822. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22823. },
  22824. enumerable: true,
  22825. configurable: true
  22826. });
  22827. Object.defineProperty(Material.prototype, "pointsCloud", {
  22828. get: function () {
  22829. return this._fillMode === Material.PointFillMode;
  22830. },
  22831. set: function (value) {
  22832. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22833. },
  22834. enumerable: true,
  22835. configurable: true
  22836. });
  22837. Object.defineProperty(Material.prototype, "fillMode", {
  22838. get: function () {
  22839. return this._fillMode;
  22840. },
  22841. set: function (value) {
  22842. this._fillMode = value;
  22843. },
  22844. enumerable: true,
  22845. configurable: true
  22846. });
  22847. /**
  22848. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22849. * subclasses should override adding information pertainent to themselves
  22850. */
  22851. Material.prototype.toString = function (fullDetails) {
  22852. var ret = "Name: " + this.name;
  22853. if (fullDetails) {
  22854. }
  22855. return ret;
  22856. };
  22857. Object.defineProperty(Material.prototype, "isFrozen", {
  22858. get: function () {
  22859. return this.checkReadyOnlyOnce;
  22860. },
  22861. enumerable: true,
  22862. configurable: true
  22863. });
  22864. Material.prototype.freeze = function () {
  22865. this.checkReadyOnlyOnce = true;
  22866. };
  22867. Material.prototype.unfreeze = function () {
  22868. this.checkReadyOnlyOnce = false;
  22869. };
  22870. Material.prototype.isReady = function (mesh, useInstances) {
  22871. return true;
  22872. };
  22873. Material.prototype.getEffect = function () {
  22874. return this._effect;
  22875. };
  22876. Material.prototype.getScene = function () {
  22877. return this._scene;
  22878. };
  22879. Material.prototype.needAlphaBlending = function () {
  22880. return (this.alpha < 1.0);
  22881. };
  22882. Material.prototype.needAlphaTesting = function () {
  22883. return false;
  22884. };
  22885. Material.prototype.getAlphaTestTexture = function () {
  22886. return null;
  22887. };
  22888. Material.prototype.markDirty = function () {
  22889. this._wasPreviouslyReady = false;
  22890. };
  22891. Material.prototype._preBind = function () {
  22892. var engine = this._scene.getEngine();
  22893. engine.enableEffect(this._effect);
  22894. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22895. };
  22896. Material.prototype.bind = function (world, mesh) {
  22897. this._scene._cachedMaterial = this;
  22898. this.onBindObservable.notifyObservers(mesh);
  22899. if (this.disableDepthWrite) {
  22900. var engine = this._scene.getEngine();
  22901. this._cachedDepthWriteState = engine.getDepthWrite();
  22902. engine.setDepthWrite(false);
  22903. }
  22904. };
  22905. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22906. };
  22907. Material.prototype.unbind = function () {
  22908. if (this.disableDepthWrite) {
  22909. var engine = this._scene.getEngine();
  22910. engine.setDepthWrite(this._cachedDepthWriteState);
  22911. }
  22912. };
  22913. Material.prototype.clone = function (name) {
  22914. return null;
  22915. };
  22916. Material.prototype.getBindedMeshes = function () {
  22917. var result = new Array();
  22918. for (var index = 0; index < this._scene.meshes.length; index++) {
  22919. var mesh = this._scene.meshes[index];
  22920. if (mesh.material === this) {
  22921. result.push(mesh);
  22922. }
  22923. }
  22924. return result;
  22925. };
  22926. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22927. // Animations
  22928. this.getScene().stopAnimation(this);
  22929. // Remove from scene
  22930. var index = this._scene.materials.indexOf(this);
  22931. if (index >= 0) {
  22932. this._scene.materials.splice(index, 1);
  22933. }
  22934. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22935. if (forceDisposeEffect && this._effect) {
  22936. this._scene.getEngine()._releaseEffect(this._effect);
  22937. this._effect = null;
  22938. }
  22939. // Remove from meshes
  22940. for (index = 0; index < this._scene.meshes.length; index++) {
  22941. var mesh = this._scene.meshes[index];
  22942. if (mesh.material === this) {
  22943. mesh.material = null;
  22944. }
  22945. }
  22946. // Callback
  22947. this.onDisposeObservable.notifyObservers(this);
  22948. this.onDisposeObservable.clear();
  22949. this.onBindObservable.clear();
  22950. };
  22951. Material.prototype.serialize = function () {
  22952. return BABYLON.SerializationHelper.Serialize(this);
  22953. };
  22954. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22955. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22956. multiMaterial.id = parsedMultiMaterial.id;
  22957. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22958. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22959. var subMatId = parsedMultiMaterial.materials[matIndex];
  22960. if (subMatId) {
  22961. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22962. }
  22963. else {
  22964. multiMaterial.subMaterials.push(null);
  22965. }
  22966. }
  22967. return multiMaterial;
  22968. };
  22969. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22970. if (!parsedMaterial.customType) {
  22971. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22972. }
  22973. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22974. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22975. ;
  22976. };
  22977. Material._TriangleFillMode = 0;
  22978. Material._WireFrameFillMode = 1;
  22979. Material._PointFillMode = 2;
  22980. Material._ClockWiseSideOrientation = 0;
  22981. Material._CounterClockWiseSideOrientation = 1;
  22982. __decorate([
  22983. BABYLON.serialize()
  22984. ], Material.prototype, "id", void 0);
  22985. __decorate([
  22986. BABYLON.serialize()
  22987. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22988. __decorate([
  22989. BABYLON.serialize()
  22990. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22991. __decorate([
  22992. BABYLON.serialize()
  22993. ], Material.prototype, "state", void 0);
  22994. __decorate([
  22995. BABYLON.serialize()
  22996. ], Material.prototype, "alpha", void 0);
  22997. __decorate([
  22998. BABYLON.serialize()
  22999. ], Material.prototype, "backFaceCulling", void 0);
  23000. __decorate([
  23001. BABYLON.serialize()
  23002. ], Material.prototype, "sideOrientation", void 0);
  23003. __decorate([
  23004. BABYLON.serialize()
  23005. ], Material.prototype, "alphaMode", void 0);
  23006. __decorate([
  23007. BABYLON.serialize()
  23008. ], Material.prototype, "disableDepthWrite", void 0);
  23009. __decorate([
  23010. BABYLON.serialize()
  23011. ], Material.prototype, "fogEnabled", void 0);
  23012. __decorate([
  23013. BABYLON.serialize()
  23014. ], Material.prototype, "pointSize", void 0);
  23015. __decorate([
  23016. BABYLON.serialize()
  23017. ], Material.prototype, "zOffset", void 0);
  23018. __decorate([
  23019. BABYLON.serialize()
  23020. ], Material.prototype, "wireframe", null);
  23021. __decorate([
  23022. BABYLON.serialize()
  23023. ], Material.prototype, "pointsCloud", null);
  23024. __decorate([
  23025. BABYLON.serialize()
  23026. ], Material.prototype, "fillMode", null);
  23027. return Material;
  23028. })();
  23029. BABYLON.Material = Material;
  23030. })(BABYLON || (BABYLON = {}));
  23031. var BABYLON;
  23032. (function (BABYLON) {
  23033. var StandardMaterialDefines = (function (_super) {
  23034. __extends(StandardMaterialDefines, _super);
  23035. function StandardMaterialDefines() {
  23036. _super.call(this);
  23037. this.DIFFUSE = false;
  23038. this.AMBIENT = false;
  23039. this.OPACITY = false;
  23040. this.OPACITYRGB = false;
  23041. this.REFLECTION = false;
  23042. this.EMISSIVE = false;
  23043. this.SPECULAR = false;
  23044. this.BUMP = false;
  23045. this.PARALLAX = false;
  23046. this.PARALLAXOCCLUSION = false;
  23047. this.SPECULAROVERALPHA = false;
  23048. this.CLIPPLANE = false;
  23049. this.ALPHATEST = false;
  23050. this.ALPHAFROMDIFFUSE = false;
  23051. this.POINTSIZE = false;
  23052. this.FOG = false;
  23053. this.SPECULARTERM = false;
  23054. this.DIFFUSEFRESNEL = false;
  23055. this.OPACITYFRESNEL = false;
  23056. this.REFLECTIONFRESNEL = false;
  23057. this.REFRACTIONFRESNEL = false;
  23058. this.EMISSIVEFRESNEL = false;
  23059. this.FRESNEL = false;
  23060. this.NORMAL = false;
  23061. this.UV1 = false;
  23062. this.UV2 = false;
  23063. this.VERTEXCOLOR = false;
  23064. this.VERTEXALPHA = false;
  23065. this.NUM_BONE_INFLUENCERS = 0;
  23066. this.BonesPerMesh = 0;
  23067. this.INSTANCES = false;
  23068. this.GLOSSINESS = false;
  23069. this.ROUGHNESS = false;
  23070. this.EMISSIVEASILLUMINATION = false;
  23071. this.LINKEMISSIVEWITHDIFFUSE = false;
  23072. this.REFLECTIONFRESNELFROMSPECULAR = false;
  23073. this.LIGHTMAP = false;
  23074. this.USELIGHTMAPASSHADOWMAP = false;
  23075. this.REFLECTIONMAP_3D = false;
  23076. this.REFLECTIONMAP_SPHERICAL = false;
  23077. this.REFLECTIONMAP_PLANAR = false;
  23078. this.REFLECTIONMAP_CUBIC = false;
  23079. this.REFLECTIONMAP_PROJECTION = false;
  23080. this.REFLECTIONMAP_SKYBOX = false;
  23081. this.REFLECTIONMAP_EXPLICIT = false;
  23082. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  23083. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  23084. this.INVERTCUBICMAP = false;
  23085. this.LOGARITHMICDEPTH = false;
  23086. this.REFRACTION = false;
  23087. this.REFRACTIONMAP_3D = false;
  23088. this.REFLECTIONOVERALPHA = false;
  23089. this.OPENGLNORMALMAP = false;
  23090. this.rebuild();
  23091. }
  23092. return StandardMaterialDefines;
  23093. })(BABYLON.MaterialDefines);
  23094. var StandardMaterial = (function (_super) {
  23095. __extends(StandardMaterial, _super);
  23096. function StandardMaterial(name, scene) {
  23097. var _this = this;
  23098. _super.call(this, name, scene);
  23099. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23100. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  23101. this.specularColor = new BABYLON.Color3(1, 1, 1);
  23102. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  23103. this.specularPower = 64;
  23104. this.useAlphaFromDiffuseTexture = false;
  23105. this.useEmissiveAsIllumination = false;
  23106. this.linkEmissiveWithDiffuse = false;
  23107. this.useReflectionFresnelFromSpecular = false;
  23108. this.useSpecularOverAlpha = false;
  23109. this.useReflectionOverAlpha = false;
  23110. this.disableLighting = false;
  23111. this.useParallax = false;
  23112. this.useParallaxOcclusion = false;
  23113. this.parallaxScaleBias = 0.05;
  23114. this.roughness = 0;
  23115. this.indexOfRefraction = 0.98;
  23116. this.invertRefractionY = true;
  23117. this.useLightmapAsShadowmap = false;
  23118. this.useGlossinessFromSpecularMapAlpha = false;
  23119. this.maxSimultaneousLights = 4;
  23120. /**
  23121. * If sets to true, normal map will be considered following OpenGL convention.
  23122. */
  23123. this.useOpenGLNormalMap = false;
  23124. this._renderTargets = new BABYLON.SmartArray(16);
  23125. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  23126. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  23127. this._defines = new StandardMaterialDefines();
  23128. this._cachedDefines = new StandardMaterialDefines();
  23129. this._cachedDefines.BonesPerMesh = -1;
  23130. this.getRenderTargetTextures = function () {
  23131. _this._renderTargets.reset();
  23132. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  23133. _this._renderTargets.push(_this.reflectionTexture);
  23134. }
  23135. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  23136. _this._renderTargets.push(_this.refractionTexture);
  23137. }
  23138. return _this._renderTargets;
  23139. };
  23140. }
  23141. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  23142. get: function () {
  23143. return this._useLogarithmicDepth;
  23144. },
  23145. set: function (value) {
  23146. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  23147. },
  23148. enumerable: true,
  23149. configurable: true
  23150. });
  23151. StandardMaterial.prototype.needAlphaBlending = function () {
  23152. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  23153. };
  23154. StandardMaterial.prototype.needAlphaTesting = function () {
  23155. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  23156. };
  23157. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  23158. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  23159. };
  23160. StandardMaterial.prototype.getAlphaTestTexture = function () {
  23161. return this.diffuseTexture;
  23162. };
  23163. // Methods
  23164. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  23165. if (!mesh) {
  23166. return true;
  23167. }
  23168. if (this._defines.INSTANCES !== useInstances) {
  23169. return false;
  23170. }
  23171. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  23172. return true;
  23173. }
  23174. return false;
  23175. };
  23176. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  23177. if (this.isFrozen) {
  23178. if (this._wasPreviouslyReady) {
  23179. return true;
  23180. }
  23181. }
  23182. var scene = this.getScene();
  23183. if (!this.checkReadyOnEveryCall) {
  23184. if (this._renderId === scene.getRenderId()) {
  23185. if (this._checkCache(scene, mesh, useInstances)) {
  23186. return true;
  23187. }
  23188. }
  23189. }
  23190. var engine = scene.getEngine();
  23191. var needNormals = false;
  23192. var needUVs = false;
  23193. this._defines.reset();
  23194. // Textures
  23195. if (scene.texturesEnabled) {
  23196. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23197. if (!this.diffuseTexture.isReady()) {
  23198. return false;
  23199. }
  23200. else {
  23201. needUVs = true;
  23202. this._defines.DIFFUSE = true;
  23203. }
  23204. }
  23205. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23206. if (!this.ambientTexture.isReady()) {
  23207. return false;
  23208. }
  23209. else {
  23210. needUVs = true;
  23211. this._defines.AMBIENT = true;
  23212. }
  23213. }
  23214. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23215. if (!this.opacityTexture.isReady()) {
  23216. return false;
  23217. }
  23218. else {
  23219. needUVs = true;
  23220. this._defines.OPACITY = true;
  23221. if (this.opacityTexture.getAlphaFromRGB) {
  23222. this._defines.OPACITYRGB = true;
  23223. }
  23224. }
  23225. }
  23226. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23227. if (!this.reflectionTexture.isReady()) {
  23228. return false;
  23229. }
  23230. else {
  23231. needNormals = true;
  23232. this._defines.REFLECTION = true;
  23233. if (this.roughness > 0) {
  23234. this._defines.ROUGHNESS = true;
  23235. }
  23236. if (this.useReflectionOverAlpha) {
  23237. this._defines.REFLECTIONOVERALPHA = true;
  23238. }
  23239. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  23240. this._defines.INVERTCUBICMAP = true;
  23241. }
  23242. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  23243. switch (this.reflectionTexture.coordinatesMode) {
  23244. case BABYLON.Texture.CUBIC_MODE:
  23245. case BABYLON.Texture.INVCUBIC_MODE:
  23246. this._defines.REFLECTIONMAP_CUBIC = true;
  23247. break;
  23248. case BABYLON.Texture.EXPLICIT_MODE:
  23249. this._defines.REFLECTIONMAP_EXPLICIT = true;
  23250. break;
  23251. case BABYLON.Texture.PLANAR_MODE:
  23252. this._defines.REFLECTIONMAP_PLANAR = true;
  23253. break;
  23254. case BABYLON.Texture.PROJECTION_MODE:
  23255. this._defines.REFLECTIONMAP_PROJECTION = true;
  23256. break;
  23257. case BABYLON.Texture.SKYBOX_MODE:
  23258. this._defines.REFLECTIONMAP_SKYBOX = true;
  23259. break;
  23260. case BABYLON.Texture.SPHERICAL_MODE:
  23261. this._defines.REFLECTIONMAP_SPHERICAL = true;
  23262. break;
  23263. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  23264. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  23265. break;
  23266. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  23267. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  23268. break;
  23269. }
  23270. }
  23271. }
  23272. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23273. if (!this.emissiveTexture.isReady()) {
  23274. return false;
  23275. }
  23276. else {
  23277. needUVs = true;
  23278. this._defines.EMISSIVE = true;
  23279. }
  23280. }
  23281. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23282. if (!this.lightmapTexture.isReady()) {
  23283. return false;
  23284. }
  23285. else {
  23286. needUVs = true;
  23287. this._defines.LIGHTMAP = true;
  23288. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  23289. }
  23290. }
  23291. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23292. if (!this.specularTexture.isReady()) {
  23293. return false;
  23294. }
  23295. else {
  23296. needUVs = true;
  23297. this._defines.SPECULAR = true;
  23298. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  23299. }
  23300. }
  23301. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  23302. if (!this.bumpTexture.isReady()) {
  23303. return false;
  23304. }
  23305. else {
  23306. needUVs = true;
  23307. this._defines.BUMP = true;
  23308. if (this.useParallax) {
  23309. this._defines.PARALLAX = true;
  23310. if (this.useParallaxOcclusion) {
  23311. this._defines.PARALLAXOCCLUSION = true;
  23312. }
  23313. }
  23314. if (this.useOpenGLNormalMap) {
  23315. this._defines.OPENGLNORMALMAP = true;
  23316. }
  23317. }
  23318. }
  23319. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23320. if (!this.refractionTexture.isReady()) {
  23321. return false;
  23322. }
  23323. else {
  23324. needUVs = true;
  23325. this._defines.REFRACTION = true;
  23326. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  23327. }
  23328. }
  23329. }
  23330. // Effect
  23331. if (scene.clipPlane) {
  23332. this._defines.CLIPPLANE = true;
  23333. }
  23334. if (engine.getAlphaTesting()) {
  23335. this._defines.ALPHATEST = true;
  23336. }
  23337. if (this._shouldUseAlphaFromDiffuseTexture()) {
  23338. this._defines.ALPHAFROMDIFFUSE = true;
  23339. }
  23340. if (this.useEmissiveAsIllumination) {
  23341. this._defines.EMISSIVEASILLUMINATION = true;
  23342. }
  23343. if (this.linkEmissiveWithDiffuse) {
  23344. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  23345. }
  23346. if (this.useLogarithmicDepth) {
  23347. this._defines.LOGARITHMICDEPTH = true;
  23348. }
  23349. // Point size
  23350. if (this.pointsCloud || scene.forcePointsCloud) {
  23351. this._defines.POINTSIZE = true;
  23352. }
  23353. // Fog
  23354. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23355. this._defines.FOG = true;
  23356. }
  23357. if (scene.lightsEnabled && !this.disableLighting) {
  23358. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  23359. }
  23360. if (StandardMaterial.FresnelEnabled) {
  23361. // Fresnel
  23362. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  23363. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  23364. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  23365. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  23366. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23367. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23368. this._defines.DIFFUSEFRESNEL = true;
  23369. }
  23370. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23371. this._defines.OPACITYFRESNEL = true;
  23372. }
  23373. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23374. this._defines.REFLECTIONFRESNEL = true;
  23375. if (this.useReflectionFresnelFromSpecular) {
  23376. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  23377. }
  23378. }
  23379. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23380. this._defines.REFRACTIONFRESNEL = true;
  23381. }
  23382. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23383. this._defines.EMISSIVEFRESNEL = true;
  23384. }
  23385. needNormals = true;
  23386. this._defines.FRESNEL = true;
  23387. }
  23388. }
  23389. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  23390. this._defines.SPECULAROVERALPHA = true;
  23391. }
  23392. // Attribs
  23393. if (mesh) {
  23394. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23395. this._defines.NORMAL = true;
  23396. }
  23397. if (needUVs) {
  23398. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23399. this._defines.UV1 = true;
  23400. }
  23401. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23402. this._defines.UV2 = true;
  23403. }
  23404. }
  23405. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23406. this._defines.VERTEXCOLOR = true;
  23407. if (mesh.hasVertexAlpha) {
  23408. this._defines.VERTEXALPHA = true;
  23409. }
  23410. }
  23411. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23412. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  23413. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  23414. }
  23415. // Instances
  23416. if (useInstances) {
  23417. this._defines.INSTANCES = true;
  23418. }
  23419. }
  23420. // Get correct effect
  23421. if (!this._defines.isEqual(this._cachedDefines)) {
  23422. this._defines.cloneTo(this._cachedDefines);
  23423. scene.resetCachedMaterial();
  23424. // Fallbacks
  23425. var fallbacks = new BABYLON.EffectFallbacks();
  23426. if (this._defines.REFLECTION) {
  23427. fallbacks.addFallback(0, "REFLECTION");
  23428. }
  23429. if (this._defines.SPECULAR) {
  23430. fallbacks.addFallback(0, "SPECULAR");
  23431. }
  23432. if (this._defines.BUMP) {
  23433. fallbacks.addFallback(0, "BUMP");
  23434. }
  23435. if (this._defines.PARALLAX) {
  23436. fallbacks.addFallback(1, "PARALLAX");
  23437. }
  23438. if (this._defines.PARALLAXOCCLUSION) {
  23439. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  23440. }
  23441. if (this._defines.SPECULAROVERALPHA) {
  23442. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  23443. }
  23444. if (this._defines.FOG) {
  23445. fallbacks.addFallback(1, "FOG");
  23446. }
  23447. if (this._defines.POINTSIZE) {
  23448. fallbacks.addFallback(0, "POINTSIZE");
  23449. }
  23450. if (this._defines.LOGARITHMICDEPTH) {
  23451. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  23452. }
  23453. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  23454. if (this._defines.SPECULARTERM) {
  23455. fallbacks.addFallback(0, "SPECULARTERM");
  23456. }
  23457. if (this._defines.DIFFUSEFRESNEL) {
  23458. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  23459. }
  23460. if (this._defines.OPACITYFRESNEL) {
  23461. fallbacks.addFallback(2, "OPACITYFRESNEL");
  23462. }
  23463. if (this._defines.REFLECTIONFRESNEL) {
  23464. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  23465. }
  23466. if (this._defines.EMISSIVEFRESNEL) {
  23467. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  23468. }
  23469. if (this._defines.FRESNEL) {
  23470. fallbacks.addFallback(4, "FRESNEL");
  23471. }
  23472. //Attributes
  23473. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23474. if (this._defines.NORMAL) {
  23475. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23476. }
  23477. if (this._defines.UV1) {
  23478. attribs.push(BABYLON.VertexBuffer.UVKind);
  23479. }
  23480. if (this._defines.UV2) {
  23481. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23482. }
  23483. if (this._defines.VERTEXCOLOR) {
  23484. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23485. }
  23486. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23487. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23488. // Legacy browser patch
  23489. var shaderName = "default";
  23490. if (!scene.getEngine().getCaps().standardDerivatives) {
  23491. shaderName = "legacydefault";
  23492. }
  23493. var join = this._defines.toString();
  23494. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23495. "vFogInfos", "vFogColor", "pointSize",
  23496. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23497. "mBones",
  23498. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23499. "depthValues",
  23500. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23501. "logarithmicDepthConstant"
  23502. ];
  23503. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  23504. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  23505. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  23506. }
  23507. if (!this._effect.isReady()) {
  23508. return false;
  23509. }
  23510. this._renderId = scene.getRenderId();
  23511. this._wasPreviouslyReady = true;
  23512. if (mesh) {
  23513. if (!mesh._materialDefines) {
  23514. mesh._materialDefines = new StandardMaterialDefines();
  23515. }
  23516. this._defines.cloneTo(mesh._materialDefines);
  23517. }
  23518. return true;
  23519. };
  23520. StandardMaterial.prototype.unbind = function () {
  23521. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23522. this._effect.setTexture("reflection2DSampler", null);
  23523. }
  23524. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23525. this._effect.setTexture("refraction2DSampler", null);
  23526. }
  23527. _super.prototype.unbind.call(this);
  23528. };
  23529. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23530. this._effect.setMatrix("world", world);
  23531. };
  23532. StandardMaterial.prototype.bind = function (world, mesh) {
  23533. var scene = this.getScene();
  23534. // Matrices
  23535. this.bindOnlyWorldMatrix(world);
  23536. // Bones
  23537. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23538. if (scene.getCachedMaterial() !== this) {
  23539. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23540. if (StandardMaterial.FresnelEnabled) {
  23541. // Fresnel
  23542. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23543. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23544. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23545. }
  23546. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23547. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23548. }
  23549. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23550. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23551. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23552. }
  23553. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23554. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23555. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23556. }
  23557. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23558. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23559. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23560. }
  23561. }
  23562. // Textures
  23563. if (scene.texturesEnabled) {
  23564. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23565. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23566. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23567. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23568. }
  23569. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23570. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23571. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23572. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23573. }
  23574. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23575. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23576. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23577. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23578. }
  23579. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23580. if (this.reflectionTexture.isCube) {
  23581. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23582. }
  23583. else {
  23584. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23585. }
  23586. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23587. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23588. }
  23589. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23590. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23591. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23592. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23593. }
  23594. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23595. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23596. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23597. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23598. }
  23599. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23600. this._effect.setTexture("specularSampler", this.specularTexture);
  23601. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23602. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23603. }
  23604. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23605. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23606. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23607. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23608. }
  23609. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23610. var depth = 1.0;
  23611. if (this.refractionTexture.isCube) {
  23612. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23613. }
  23614. else {
  23615. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23616. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23617. if (this.refractionTexture.depth) {
  23618. depth = this.refractionTexture.depth;
  23619. }
  23620. }
  23621. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23622. }
  23623. }
  23624. // Clip plane
  23625. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23626. // Point size
  23627. if (this.pointsCloud) {
  23628. this._effect.setFloat("pointSize", this.pointSize);
  23629. }
  23630. // Colors
  23631. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23632. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23633. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23634. if (this._defines.SPECULARTERM) {
  23635. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23636. }
  23637. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23638. }
  23639. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23640. // Diffuse
  23641. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23642. // Lights
  23643. if (scene.lightsEnabled && !this.disableLighting) {
  23644. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  23645. }
  23646. // View
  23647. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23648. this._effect.setMatrix("view", scene.getViewMatrix());
  23649. }
  23650. // Fog
  23651. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23652. // Log. depth
  23653. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23654. }
  23655. _super.prototype.bind.call(this, world, mesh);
  23656. };
  23657. StandardMaterial.prototype.getAnimatables = function () {
  23658. var results = [];
  23659. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23660. results.push(this.diffuseTexture);
  23661. }
  23662. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23663. results.push(this.ambientTexture);
  23664. }
  23665. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23666. results.push(this.opacityTexture);
  23667. }
  23668. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23669. results.push(this.reflectionTexture);
  23670. }
  23671. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23672. results.push(this.emissiveTexture);
  23673. }
  23674. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23675. results.push(this.specularTexture);
  23676. }
  23677. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23678. results.push(this.bumpTexture);
  23679. }
  23680. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23681. results.push(this.lightmapTexture);
  23682. }
  23683. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23684. results.push(this.refractionTexture);
  23685. }
  23686. return results;
  23687. };
  23688. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23689. if (forceDisposeTextures) {
  23690. if (this.diffuseTexture) {
  23691. this.diffuseTexture.dispose();
  23692. }
  23693. if (this.ambientTexture) {
  23694. this.ambientTexture.dispose();
  23695. }
  23696. if (this.opacityTexture) {
  23697. this.opacityTexture.dispose();
  23698. }
  23699. if (this.reflectionTexture) {
  23700. this.reflectionTexture.dispose();
  23701. }
  23702. if (this.emissiveTexture) {
  23703. this.emissiveTexture.dispose();
  23704. }
  23705. if (this.specularTexture) {
  23706. this.specularTexture.dispose();
  23707. }
  23708. if (this.bumpTexture) {
  23709. this.bumpTexture.dispose();
  23710. }
  23711. if (this.lightmapTexture) {
  23712. this.lightmapTexture.dispose();
  23713. }
  23714. if (this.refractionTexture) {
  23715. this.refractionTexture.dispose();
  23716. }
  23717. }
  23718. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  23719. };
  23720. StandardMaterial.prototype.clone = function (name) {
  23721. var _this = this;
  23722. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23723. };
  23724. StandardMaterial.prototype.serialize = function () {
  23725. return BABYLON.SerializationHelper.Serialize(this);
  23726. };
  23727. // Statics
  23728. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23729. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23730. };
  23731. // Flags used to enable or disable a type of texture for all Standard Materials
  23732. StandardMaterial.DiffuseTextureEnabled = true;
  23733. StandardMaterial.AmbientTextureEnabled = true;
  23734. StandardMaterial.OpacityTextureEnabled = true;
  23735. StandardMaterial.ReflectionTextureEnabled = true;
  23736. StandardMaterial.EmissiveTextureEnabled = true;
  23737. StandardMaterial.SpecularTextureEnabled = true;
  23738. StandardMaterial.BumpTextureEnabled = true;
  23739. StandardMaterial.FresnelEnabled = true;
  23740. StandardMaterial.LightmapTextureEnabled = true;
  23741. StandardMaterial.RefractionTextureEnabled = true;
  23742. __decorate([
  23743. BABYLON.serializeAsTexture()
  23744. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23745. __decorate([
  23746. BABYLON.serializeAsTexture()
  23747. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23748. __decorate([
  23749. BABYLON.serializeAsTexture()
  23750. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23751. __decorate([
  23752. BABYLON.serializeAsTexture()
  23753. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23754. __decorate([
  23755. BABYLON.serializeAsTexture()
  23756. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23757. __decorate([
  23758. BABYLON.serializeAsTexture()
  23759. ], StandardMaterial.prototype, "specularTexture", void 0);
  23760. __decorate([
  23761. BABYLON.serializeAsTexture()
  23762. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23763. __decorate([
  23764. BABYLON.serializeAsTexture()
  23765. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23766. __decorate([
  23767. BABYLON.serializeAsTexture()
  23768. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23769. __decorate([
  23770. BABYLON.serializeAsColor3("ambient")
  23771. ], StandardMaterial.prototype, "ambientColor", void 0);
  23772. __decorate([
  23773. BABYLON.serializeAsColor3("diffuse")
  23774. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23775. __decorate([
  23776. BABYLON.serializeAsColor3("specular")
  23777. ], StandardMaterial.prototype, "specularColor", void 0);
  23778. __decorate([
  23779. BABYLON.serializeAsColor3("emissive")
  23780. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23781. __decorate([
  23782. BABYLON.serialize()
  23783. ], StandardMaterial.prototype, "specularPower", void 0);
  23784. __decorate([
  23785. BABYLON.serialize()
  23786. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23787. __decorate([
  23788. BABYLON.serialize()
  23789. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23790. __decorate([
  23791. BABYLON.serialize()
  23792. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23793. __decorate([
  23794. BABYLON.serialize()
  23795. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23796. __decorate([
  23797. BABYLON.serialize()
  23798. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23799. __decorate([
  23800. BABYLON.serialize()
  23801. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23802. __decorate([
  23803. BABYLON.serialize()
  23804. ], StandardMaterial.prototype, "disableLighting", void 0);
  23805. __decorate([
  23806. BABYLON.serialize()
  23807. ], StandardMaterial.prototype, "useParallax", void 0);
  23808. __decorate([
  23809. BABYLON.serialize()
  23810. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23811. __decorate([
  23812. BABYLON.serialize()
  23813. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23814. __decorate([
  23815. BABYLON.serialize()
  23816. ], StandardMaterial.prototype, "roughness", void 0);
  23817. __decorate([
  23818. BABYLON.serialize()
  23819. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23820. __decorate([
  23821. BABYLON.serialize()
  23822. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23823. __decorate([
  23824. BABYLON.serialize()
  23825. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23826. __decorate([
  23827. BABYLON.serializeAsFresnelParameters()
  23828. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23829. __decorate([
  23830. BABYLON.serializeAsFresnelParameters()
  23831. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23832. __decorate([
  23833. BABYLON.serializeAsFresnelParameters()
  23834. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23835. __decorate([
  23836. BABYLON.serializeAsFresnelParameters()
  23837. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23838. __decorate([
  23839. BABYLON.serializeAsFresnelParameters()
  23840. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23841. __decorate([
  23842. BABYLON.serialize()
  23843. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23844. __decorate([
  23845. BABYLON.serialize()
  23846. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  23847. __decorate([
  23848. BABYLON.serialize()
  23849. ], StandardMaterial.prototype, "useOpenGLNormalMap", void 0);
  23850. __decorate([
  23851. BABYLON.serialize()
  23852. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23853. return StandardMaterial;
  23854. })(BABYLON.Material);
  23855. BABYLON.StandardMaterial = StandardMaterial;
  23856. })(BABYLON || (BABYLON = {}));
  23857. var BABYLON;
  23858. (function (BABYLON) {
  23859. var MultiMaterial = (function (_super) {
  23860. __extends(MultiMaterial, _super);
  23861. function MultiMaterial(name, scene) {
  23862. _super.call(this, name, scene, true);
  23863. this.subMaterials = new Array();
  23864. scene.multiMaterials.push(this);
  23865. }
  23866. // Properties
  23867. MultiMaterial.prototype.getSubMaterial = function (index) {
  23868. if (index < 0 || index >= this.subMaterials.length) {
  23869. return this.getScene().defaultMaterial;
  23870. }
  23871. return this.subMaterials[index];
  23872. };
  23873. // Methods
  23874. MultiMaterial.prototype.isReady = function (mesh) {
  23875. for (var index = 0; index < this.subMaterials.length; index++) {
  23876. var subMaterial = this.subMaterials[index];
  23877. if (subMaterial) {
  23878. if (!this.subMaterials[index].isReady(mesh)) {
  23879. return false;
  23880. }
  23881. }
  23882. }
  23883. return true;
  23884. };
  23885. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23886. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23887. for (var index = 0; index < this.subMaterials.length; index++) {
  23888. var subMaterial = null;
  23889. if (cloneChildren) {
  23890. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23891. }
  23892. else {
  23893. subMaterial = this.subMaterials[index];
  23894. }
  23895. newMultiMaterial.subMaterials.push(subMaterial);
  23896. }
  23897. return newMultiMaterial;
  23898. };
  23899. MultiMaterial.prototype.serialize = function () {
  23900. var serializationObject = {};
  23901. serializationObject.name = this.name;
  23902. serializationObject.id = this.id;
  23903. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23904. serializationObject.materials = [];
  23905. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23906. var subMat = this.subMaterials[matIndex];
  23907. if (subMat) {
  23908. serializationObject.materials.push(subMat.id);
  23909. }
  23910. else {
  23911. serializationObject.materials.push(null);
  23912. }
  23913. }
  23914. return serializationObject;
  23915. };
  23916. return MultiMaterial;
  23917. })(BABYLON.Material);
  23918. BABYLON.MultiMaterial = MultiMaterial;
  23919. })(BABYLON || (BABYLON = {}));
  23920. var BABYLON;
  23921. (function (BABYLON) {
  23922. var SceneLoader = (function () {
  23923. function SceneLoader() {
  23924. }
  23925. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23926. get: function () {
  23927. return 0;
  23928. },
  23929. enumerable: true,
  23930. configurable: true
  23931. });
  23932. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23933. get: function () {
  23934. return 1;
  23935. },
  23936. enumerable: true,
  23937. configurable: true
  23938. });
  23939. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23940. get: function () {
  23941. return 2;
  23942. },
  23943. enumerable: true,
  23944. configurable: true
  23945. });
  23946. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23947. get: function () {
  23948. return 3;
  23949. },
  23950. enumerable: true,
  23951. configurable: true
  23952. });
  23953. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23954. get: function () {
  23955. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23956. },
  23957. set: function (value) {
  23958. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23959. },
  23960. enumerable: true,
  23961. configurable: true
  23962. });
  23963. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23964. get: function () {
  23965. return SceneLoader._ShowLoadingScreen;
  23966. },
  23967. set: function (value) {
  23968. SceneLoader._ShowLoadingScreen = value;
  23969. },
  23970. enumerable: true,
  23971. configurable: true
  23972. });
  23973. Object.defineProperty(SceneLoader, "loggingLevel", {
  23974. get: function () {
  23975. return SceneLoader._loggingLevel;
  23976. },
  23977. set: function (value) {
  23978. SceneLoader._loggingLevel = value;
  23979. },
  23980. enumerable: true,
  23981. configurable: true
  23982. });
  23983. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23984. var dotPosition = sceneFilename.lastIndexOf(".");
  23985. var queryStringPosition = sceneFilename.indexOf("?");
  23986. if (queryStringPosition === -1) {
  23987. queryStringPosition = sceneFilename.length;
  23988. }
  23989. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23990. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23991. var plugin = this._registeredPlugins[index];
  23992. if (plugin.extensions.indexOf(extension) !== -1) {
  23993. return plugin;
  23994. }
  23995. }
  23996. return this._registeredPlugins[0];
  23997. };
  23998. // Public functions
  23999. SceneLoader.GetPluginForExtension = function (extension) {
  24000. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24001. var plugin = this._registeredPlugins[index];
  24002. if (plugin.extensions.indexOf(extension) !== -1) {
  24003. return plugin;
  24004. }
  24005. }
  24006. return null;
  24007. };
  24008. SceneLoader.RegisterPlugin = function (plugin) {
  24009. plugin.extensions = plugin.extensions.toLowerCase();
  24010. SceneLoader._registeredPlugins.push(plugin);
  24011. };
  24012. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24013. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24014. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24015. return;
  24016. }
  24017. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24018. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24019. return;
  24020. }
  24021. var loadingToken = {};
  24022. scene._addPendingData(loadingToken);
  24023. var manifestChecked = function (success) {
  24024. scene.database = database;
  24025. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  24026. var importMeshFromData = function (data) {
  24027. var meshes = [];
  24028. var particleSystems = [];
  24029. var skeletons = [];
  24030. try {
  24031. if (plugin.importMesh) {
  24032. var syncedPlugin = plugin;
  24033. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  24034. if (onerror) {
  24035. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24036. }
  24037. scene._removePendingData(loadingToken);
  24038. return;
  24039. }
  24040. if (onsuccess) {
  24041. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24042. onsuccess(meshes, particleSystems, skeletons);
  24043. scene._removePendingData(loadingToken);
  24044. }
  24045. }
  24046. else {
  24047. var asyncedPlugin = plugin;
  24048. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  24049. if (onsuccess) {
  24050. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24051. onsuccess(meshes, particleSystems, skeletons);
  24052. scene._removePendingData(loadingToken);
  24053. }
  24054. }, function () {
  24055. if (onerror) {
  24056. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24057. }
  24058. scene._removePendingData(loadingToken);
  24059. });
  24060. }
  24061. }
  24062. catch (e) {
  24063. if (onerror) {
  24064. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  24065. }
  24066. scene._removePendingData(loadingToken);
  24067. }
  24068. };
  24069. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24070. // Direct load
  24071. importMeshFromData(sceneFilename.substr(5));
  24072. return;
  24073. }
  24074. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  24075. importMeshFromData(data);
  24076. }, progressCallBack, database);
  24077. };
  24078. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  24079. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24080. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24081. }
  24082. else {
  24083. // If the scene is a data stream or offline support is not enabled, it's a direct load
  24084. manifestChecked(true);
  24085. }
  24086. };
  24087. /**
  24088. * Load a scene
  24089. * @param rootUrl a string that defines the root url for scene and resources
  24090. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24091. * @param engine is the instance of BABYLON.Engine to use to create the scene
  24092. */
  24093. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  24094. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  24095. };
  24096. /**
  24097. * Append a scene
  24098. * @param rootUrl a string that defines the root url for scene and resources
  24099. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24100. * @param scene is the instance of BABYLON.Scene to append to
  24101. */
  24102. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24103. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24104. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24105. return;
  24106. }
  24107. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  24108. var database;
  24109. var loadingToken = {};
  24110. scene._addPendingData(loadingToken);
  24111. if (SceneLoader.ShowLoadingScreen) {
  24112. scene.getEngine().displayLoadingUI();
  24113. }
  24114. var loadSceneFromData = function (data) {
  24115. scene.database = database;
  24116. if (plugin.load) {
  24117. var syncedPlugin = plugin;
  24118. if (!syncedPlugin.load(scene, data, rootUrl)) {
  24119. if (onerror) {
  24120. onerror(scene);
  24121. }
  24122. scene._removePendingData(loadingToken);
  24123. scene.getEngine().hideLoadingUI();
  24124. return;
  24125. }
  24126. if (onsuccess) {
  24127. onsuccess(scene);
  24128. }
  24129. scene._removePendingData(loadingToken);
  24130. }
  24131. else {
  24132. var asyncedPlugin = plugin;
  24133. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  24134. if (onsuccess) {
  24135. onsuccess(scene);
  24136. }
  24137. }, function () {
  24138. if (onerror) {
  24139. onerror(scene);
  24140. }
  24141. scene._removePendingData(loadingToken);
  24142. scene.getEngine().hideLoadingUI();
  24143. });
  24144. }
  24145. if (SceneLoader.ShowLoadingScreen) {
  24146. scene.executeWhenReady(function () {
  24147. scene.getEngine().hideLoadingUI();
  24148. });
  24149. }
  24150. };
  24151. var manifestChecked = function (success) {
  24152. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  24153. };
  24154. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24155. // Direct load
  24156. loadSceneFromData(sceneFilename.substr(5));
  24157. return;
  24158. }
  24159. if (rootUrl.indexOf("file:") === -1) {
  24160. if (scene.getEngine().enableOfflineSupport) {
  24161. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24162. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24163. }
  24164. else {
  24165. manifestChecked(true);
  24166. }
  24167. }
  24168. else {
  24169. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  24170. }
  24171. };
  24172. // Flags
  24173. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  24174. SceneLoader._ShowLoadingScreen = true;
  24175. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  24176. // Members
  24177. SceneLoader._registeredPlugins = new Array();
  24178. return SceneLoader;
  24179. })();
  24180. BABYLON.SceneLoader = SceneLoader;
  24181. ;
  24182. })(BABYLON || (BABYLON = {}));
  24183. var BABYLON;
  24184. (function (BABYLON) {
  24185. var Internals;
  24186. (function (Internals) {
  24187. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  24188. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24189. var parsedMaterial = parsedData.materials[index];
  24190. if (parsedMaterial.id === id) {
  24191. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24192. }
  24193. }
  24194. return null;
  24195. };
  24196. var isDescendantOf = function (mesh, names, hierarchyIds) {
  24197. names = (names instanceof Array) ? names : [names];
  24198. for (var i in names) {
  24199. if (mesh.name === names[i]) {
  24200. hierarchyIds.push(mesh.id);
  24201. return true;
  24202. }
  24203. }
  24204. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  24205. hierarchyIds.push(mesh.id);
  24206. return true;
  24207. }
  24208. return false;
  24209. };
  24210. var logOperation = function (operation, producer) {
  24211. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  24212. };
  24213. BABYLON.SceneLoader.RegisterPlugin({
  24214. extensions: ".babylon",
  24215. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  24216. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24217. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24218. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24219. // and avoid problems with multiple concurrent .babylon loads.
  24220. var log = "importMesh has failed JSON parse";
  24221. try {
  24222. var parsedData = JSON.parse(data);
  24223. log = "";
  24224. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24225. var loadedSkeletonsIds = [];
  24226. var loadedMaterialsIds = [];
  24227. var hierarchyIds = [];
  24228. var index;
  24229. var cache;
  24230. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24231. var parsedMesh = parsedData.meshes[index];
  24232. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  24233. if (meshesNames instanceof Array) {
  24234. // Remove found mesh name from list.
  24235. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  24236. }
  24237. //Geometry?
  24238. if (parsedMesh.geometryId) {
  24239. //does the file contain geometries?
  24240. if (parsedData.geometries) {
  24241. //find the correct geometry and add it to the scene
  24242. var found = false;
  24243. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  24244. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  24245. return;
  24246. }
  24247. else {
  24248. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  24249. if (parsedGeometryData.id === parsedMesh.geometryId) {
  24250. switch (geometryType) {
  24251. case "boxes":
  24252. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  24253. break;
  24254. case "spheres":
  24255. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  24256. break;
  24257. case "cylinders":
  24258. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  24259. break;
  24260. case "toruses":
  24261. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  24262. break;
  24263. case "grounds":
  24264. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  24265. break;
  24266. case "planes":
  24267. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  24268. break;
  24269. case "torusKnots":
  24270. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  24271. break;
  24272. case "vertexData":
  24273. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  24274. break;
  24275. }
  24276. found = true;
  24277. }
  24278. });
  24279. }
  24280. });
  24281. if (!found) {
  24282. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  24283. }
  24284. }
  24285. }
  24286. // Material ?
  24287. if (parsedMesh.materialId) {
  24288. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  24289. if (!materialFound && parsedData.multiMaterials) {
  24290. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  24291. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  24292. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  24293. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  24294. var subMatId = parsedMultiMaterial.materials[matIndex];
  24295. loadedMaterialsIds.push(subMatId);
  24296. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  24297. log += "\n\tMaterial " + mat.toString(fullDetails);
  24298. }
  24299. loadedMaterialsIds.push(parsedMultiMaterial.id);
  24300. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24301. materialFound = true;
  24302. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  24303. break;
  24304. }
  24305. }
  24306. }
  24307. if (!materialFound) {
  24308. loadedMaterialsIds.push(parsedMesh.materialId);
  24309. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  24310. if (!mat) {
  24311. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  24312. }
  24313. else {
  24314. log += "\n\tMaterial " + mat.toString(fullDetails);
  24315. }
  24316. }
  24317. }
  24318. // Skeleton ?
  24319. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  24320. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  24321. if (!skeletonAlreadyLoaded) {
  24322. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  24323. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  24324. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  24325. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24326. skeletons.push(skeleton);
  24327. loadedSkeletonsIds.push(parsedSkeleton.id);
  24328. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  24329. }
  24330. }
  24331. }
  24332. }
  24333. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24334. meshes.push(mesh);
  24335. log += "\n\tMesh " + mesh.toString(fullDetails);
  24336. }
  24337. }
  24338. // Connecting parents
  24339. var currentMesh;
  24340. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24341. currentMesh = scene.meshes[index];
  24342. if (currentMesh._waitingParentId) {
  24343. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  24344. currentMesh._waitingParentId = undefined;
  24345. }
  24346. }
  24347. // freeze and compute world matrix application
  24348. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24349. currentMesh = scene.meshes[index];
  24350. if (currentMesh._waitingFreezeWorldMatrix) {
  24351. currentMesh.freezeWorldMatrix();
  24352. currentMesh._waitingFreezeWorldMatrix = undefined;
  24353. }
  24354. else {
  24355. currentMesh.computeWorldMatrix(true);
  24356. }
  24357. }
  24358. // Particles
  24359. if (parsedData.particleSystems) {
  24360. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24361. var parsedParticleSystem = parsedData.particleSystems[index];
  24362. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  24363. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  24364. }
  24365. }
  24366. }
  24367. return true;
  24368. }
  24369. catch (err) {
  24370. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  24371. log = null;
  24372. throw err;
  24373. }
  24374. finally {
  24375. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24376. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24377. }
  24378. }
  24379. },
  24380. load: function (scene, data, rootUrl) {
  24381. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24382. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24383. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24384. // and avoid problems with multiple concurrent .babylon loads.
  24385. var log = "importScene has failed JSON parse";
  24386. try {
  24387. var parsedData = JSON.parse(data);
  24388. log = "";
  24389. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24390. // Scene
  24391. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  24392. scene.autoClear = parsedData.autoClear;
  24393. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  24394. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  24395. if (parsedData.gravity) {
  24396. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  24397. }
  24398. // Fog
  24399. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  24400. scene.fogMode = parsedData.fogMode;
  24401. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  24402. scene.fogStart = parsedData.fogStart;
  24403. scene.fogEnd = parsedData.fogEnd;
  24404. scene.fogDensity = parsedData.fogDensity;
  24405. log += "\tFog mode for scene: ";
  24406. switch (scene.fogMode) {
  24407. // getters not compiling, so using hardcoded
  24408. case 1:
  24409. log += "exp\n";
  24410. break;
  24411. case 2:
  24412. log += "exp2\n";
  24413. break;
  24414. case 3:
  24415. log += "linear\n";
  24416. break;
  24417. }
  24418. }
  24419. //Physics
  24420. if (parsedData.physicsEnabled) {
  24421. var physicsPlugin;
  24422. if (parsedData.physicsEngine === "cannon") {
  24423. physicsPlugin = new BABYLON.CannonJSPlugin();
  24424. }
  24425. else if (parsedData.physicsEngine === "oimo") {
  24426. physicsPlugin = new BABYLON.OimoJSPlugin();
  24427. }
  24428. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  24429. //else - default engine, which is currently oimo
  24430. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  24431. scene.enablePhysics(physicsGravity, physicsPlugin);
  24432. }
  24433. //collisions, if defined. otherwise, default is true
  24434. if (parsedData.collisionsEnabled != undefined) {
  24435. scene.collisionsEnabled = parsedData.collisionsEnabled;
  24436. }
  24437. scene.workerCollisions = !!parsedData.workerCollisions;
  24438. var index;
  24439. var cache;
  24440. // Lights
  24441. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  24442. var parsedLight = parsedData.lights[index];
  24443. var light = BABYLON.Light.Parse(parsedLight, scene);
  24444. log += (index === 0 ? "\n\tLights:" : "");
  24445. log += "\n\t\t" + light.toString(fullDetails);
  24446. }
  24447. // Animations
  24448. if (parsedData.animations) {
  24449. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  24450. var parsedAnimation = parsedData.animations[index];
  24451. var animation = BABYLON.Animation.Parse(parsedAnimation);
  24452. scene.animations.push(animation);
  24453. log += (index === 0 ? "\n\tAnimations:" : "");
  24454. log += "\n\t\t" + animation.toString(fullDetails);
  24455. }
  24456. }
  24457. if (parsedData.autoAnimate) {
  24458. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  24459. }
  24460. // Materials
  24461. if (parsedData.materials) {
  24462. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24463. var parsedMaterial = parsedData.materials[index];
  24464. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24465. log += (index === 0 ? "\n\tMaterials:" : "");
  24466. log += "\n\t\t" + mat.toString(fullDetails);
  24467. }
  24468. }
  24469. if (parsedData.multiMaterials) {
  24470. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  24471. var parsedMultiMaterial = parsedData.multiMaterials[index];
  24472. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24473. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  24474. log += "\n\t\t" + mmat.toString(fullDetails);
  24475. }
  24476. }
  24477. // Skeletons
  24478. if (parsedData.skeletons) {
  24479. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  24480. var parsedSkeleton = parsedData.skeletons[index];
  24481. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24482. log += (index === 0 ? "\n\tSkeletons:" : "");
  24483. log += "\n\t\t" + skeleton.toString(fullDetails);
  24484. }
  24485. }
  24486. // Geometries
  24487. var geometries = parsedData.geometries;
  24488. if (geometries) {
  24489. // Boxes
  24490. var boxes = geometries.boxes;
  24491. if (boxes) {
  24492. for (index = 0, cache = boxes.length; index < cache; index++) {
  24493. var parsedBox = boxes[index];
  24494. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24495. }
  24496. }
  24497. // Spheres
  24498. var spheres = geometries.spheres;
  24499. if (spheres) {
  24500. for (index = 0, cache = spheres.length; index < cache; index++) {
  24501. var parsedSphere = spheres[index];
  24502. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24503. }
  24504. }
  24505. // Cylinders
  24506. var cylinders = geometries.cylinders;
  24507. if (cylinders) {
  24508. for (index = 0, cache = cylinders.length; index < cache; index++) {
  24509. var parsedCylinder = cylinders[index];
  24510. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  24511. }
  24512. }
  24513. // Toruses
  24514. var toruses = geometries.toruses;
  24515. if (toruses) {
  24516. for (index = 0, cache = toruses.length; index < cache; index++) {
  24517. var parsedTorus = toruses[index];
  24518. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24519. }
  24520. }
  24521. // Grounds
  24522. var grounds = geometries.grounds;
  24523. if (grounds) {
  24524. for (index = 0, cache = grounds.length; index < cache; index++) {
  24525. var parsedGround = grounds[index];
  24526. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24527. }
  24528. }
  24529. // Planes
  24530. var planes = geometries.planes;
  24531. if (planes) {
  24532. for (index = 0, cache = planes.length; index < cache; index++) {
  24533. var parsedPlane = planes[index];
  24534. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24535. }
  24536. }
  24537. // TorusKnots
  24538. var torusKnots = geometries.torusKnots;
  24539. if (torusKnots) {
  24540. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24541. var parsedTorusKnot = torusKnots[index];
  24542. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24543. }
  24544. }
  24545. // VertexData
  24546. var vertexData = geometries.vertexData;
  24547. if (vertexData) {
  24548. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24549. var parsedVertexData = vertexData[index];
  24550. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24551. }
  24552. }
  24553. }
  24554. // Meshes
  24555. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24556. var parsedMesh = parsedData.meshes[index];
  24557. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24558. log += (index === 0 ? "\n\tMeshes:" : "");
  24559. log += "\n\t\t" + mesh.toString(fullDetails);
  24560. }
  24561. // Cameras
  24562. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24563. var parsedCamera = parsedData.cameras[index];
  24564. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24565. log += (index === 0 ? "\n\tCameras:" : "");
  24566. log += "\n\t\t" + camera.toString(fullDetails);
  24567. }
  24568. if (parsedData.activeCameraID) {
  24569. scene.setActiveCameraByID(parsedData.activeCameraID);
  24570. }
  24571. // Browsing all the graph to connect the dots
  24572. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24573. var camera = scene.cameras[index];
  24574. if (camera._waitingParentId) {
  24575. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24576. camera._waitingParentId = undefined;
  24577. }
  24578. }
  24579. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24580. var light = scene.lights[index];
  24581. if (light._waitingParentId) {
  24582. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24583. light._waitingParentId = undefined;
  24584. }
  24585. }
  24586. // Sounds
  24587. var loadedSounds = [];
  24588. var loadedSound;
  24589. if (BABYLON.AudioEngine && parsedData.sounds) {
  24590. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24591. var parsedSound = parsedData.sounds[index];
  24592. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24593. if (!parsedSound.url)
  24594. parsedSound.url = parsedSound.name;
  24595. if (!loadedSounds[parsedSound.url]) {
  24596. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24597. loadedSounds[parsedSound.url] = loadedSound;
  24598. }
  24599. else {
  24600. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24601. }
  24602. }
  24603. else {
  24604. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24605. }
  24606. }
  24607. }
  24608. loadedSounds = [];
  24609. // Connect parents & children and parse actions
  24610. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24611. var mesh = scene.meshes[index];
  24612. if (mesh._waitingParentId) {
  24613. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24614. mesh._waitingParentId = undefined;
  24615. }
  24616. if (mesh._waitingActions) {
  24617. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24618. mesh._waitingActions = undefined;
  24619. }
  24620. }
  24621. // freeze world matrix application
  24622. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24623. var currentMesh = scene.meshes[index];
  24624. if (currentMesh._waitingFreezeWorldMatrix) {
  24625. currentMesh.freezeWorldMatrix();
  24626. currentMesh._waitingFreezeWorldMatrix = undefined;
  24627. }
  24628. else {
  24629. currentMesh.computeWorldMatrix(true);
  24630. }
  24631. }
  24632. // Particles Systems
  24633. if (parsedData.particleSystems) {
  24634. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24635. var parsedParticleSystem = parsedData.particleSystems[index];
  24636. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24637. }
  24638. }
  24639. // Lens flares
  24640. if (parsedData.lensFlareSystems) {
  24641. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24642. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24643. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24644. }
  24645. }
  24646. // Shadows
  24647. if (parsedData.shadowGenerators) {
  24648. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24649. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24650. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24651. }
  24652. }
  24653. // Actions (scene)
  24654. if (parsedData.actions) {
  24655. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24656. }
  24657. // Finish
  24658. return true;
  24659. }
  24660. catch (err) {
  24661. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24662. log = null;
  24663. throw err;
  24664. }
  24665. finally {
  24666. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24667. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24668. }
  24669. }
  24670. }
  24671. });
  24672. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24673. })(BABYLON || (BABYLON = {}));
  24674. var BABYLON;
  24675. (function (BABYLON) {
  24676. var SpriteManager = (function () {
  24677. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24679. this.name = name;
  24680. this.cellSize = cellSize;
  24681. this.sprites = new Array();
  24682. this.renderingGroupId = 0;
  24683. this.layerMask = 0x0FFFFFFF;
  24684. this.fogEnabled = true;
  24685. this.isPickable = false;
  24686. /**
  24687. * An event triggered when the manager is disposed.
  24688. * @type {BABYLON.Observable}
  24689. */
  24690. this.onDisposeObservable = new BABYLON.Observable();
  24691. this._vertexDeclaration = [4, 4, 4, 4];
  24692. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24693. this._capacity = capacity;
  24694. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24695. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24696. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24697. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24698. this._scene = scene;
  24699. this._scene.spriteManagers.push(this);
  24700. // VBO
  24701. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24702. var indices = [];
  24703. var index = 0;
  24704. for (var count = 0; count < capacity; count++) {
  24705. indices.push(index);
  24706. indices.push(index + 1);
  24707. indices.push(index + 2);
  24708. indices.push(index);
  24709. indices.push(index + 2);
  24710. indices.push(index + 3);
  24711. index += 4;
  24712. }
  24713. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24714. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24715. // Effects
  24716. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24717. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24718. }
  24719. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  24720. set: function (callback) {
  24721. if (this._onDisposeObserver) {
  24722. this.onDisposeObservable.remove(this._onDisposeObserver);
  24723. }
  24724. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24725. },
  24726. enumerable: true,
  24727. configurable: true
  24728. });
  24729. Object.defineProperty(SpriteManager.prototype, "texture", {
  24730. get: function () {
  24731. return this._spriteTexture;
  24732. },
  24733. set: function (value) {
  24734. this._spriteTexture = value;
  24735. },
  24736. enumerable: true,
  24737. configurable: true
  24738. });
  24739. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24740. var arrayOffset = index * 16;
  24741. if (offsetX === 0)
  24742. offsetX = this._epsilon;
  24743. else if (offsetX === 1)
  24744. offsetX = 1 - this._epsilon;
  24745. if (offsetY === 0)
  24746. offsetY = this._epsilon;
  24747. else if (offsetY === 1)
  24748. offsetY = 1 - this._epsilon;
  24749. this._vertices[arrayOffset] = sprite.position.x;
  24750. this._vertices[arrayOffset + 1] = sprite.position.y;
  24751. this._vertices[arrayOffset + 2] = sprite.position.z;
  24752. this._vertices[arrayOffset + 3] = sprite.angle;
  24753. this._vertices[arrayOffset + 4] = sprite.width;
  24754. this._vertices[arrayOffset + 5] = sprite.height;
  24755. this._vertices[arrayOffset + 6] = offsetX;
  24756. this._vertices[arrayOffset + 7] = offsetY;
  24757. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24758. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24759. var offset = (sprite.cellIndex / rowSize) >> 0;
  24760. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24761. this._vertices[arrayOffset + 11] = offset;
  24762. // Color
  24763. this._vertices[arrayOffset + 12] = sprite.color.r;
  24764. this._vertices[arrayOffset + 13] = sprite.color.g;
  24765. this._vertices[arrayOffset + 14] = sprite.color.b;
  24766. this._vertices[arrayOffset + 15] = sprite.color.a;
  24767. };
  24768. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24769. var count = Math.min(this._capacity, this.sprites.length);
  24770. var min = BABYLON.Vector3.Zero();
  24771. var max = BABYLON.Vector3.Zero();
  24772. var distance = Number.MAX_VALUE;
  24773. var currentSprite;
  24774. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24775. var cameraView = camera.getViewMatrix();
  24776. for (var index = 0; index < count; index++) {
  24777. var sprite = this.sprites[index];
  24778. if (!sprite) {
  24779. continue;
  24780. }
  24781. if (predicate) {
  24782. if (!predicate(sprite)) {
  24783. continue;
  24784. }
  24785. }
  24786. else if (!sprite.isPickable) {
  24787. continue;
  24788. }
  24789. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24790. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24791. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24792. if (ray.intersectsBoxMinMax(min, max)) {
  24793. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24794. if (distance > currentDistance) {
  24795. distance = currentDistance;
  24796. currentSprite = sprite;
  24797. if (fastCheck) {
  24798. break;
  24799. }
  24800. }
  24801. }
  24802. }
  24803. if (currentSprite) {
  24804. var result = new BABYLON.PickingInfo();
  24805. result.hit = true;
  24806. result.pickedSprite = currentSprite;
  24807. result.distance = distance;
  24808. return result;
  24809. }
  24810. return null;
  24811. };
  24812. SpriteManager.prototype.render = function () {
  24813. // Check
  24814. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24815. return;
  24816. var engine = this._scene.getEngine();
  24817. var baseSize = this._spriteTexture.getBaseSize();
  24818. // Sprites
  24819. var deltaTime = engine.getDeltaTime();
  24820. var max = Math.min(this._capacity, this.sprites.length);
  24821. var rowSize = baseSize.width / this.cellSize;
  24822. var offset = 0;
  24823. for (var index = 0; index < max; index++) {
  24824. var sprite = this.sprites[index];
  24825. if (!sprite) {
  24826. continue;
  24827. }
  24828. sprite._animate(deltaTime);
  24829. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24830. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24831. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24832. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24833. }
  24834. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24835. // Render
  24836. var effect = this._effectBase;
  24837. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24838. effect = this._effectFog;
  24839. }
  24840. engine.enableEffect(effect);
  24841. var viewMatrix = this._scene.getViewMatrix();
  24842. effect.setTexture("diffuseSampler", this._spriteTexture);
  24843. effect.setMatrix("view", viewMatrix);
  24844. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24845. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24846. // Fog
  24847. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24848. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24849. effect.setColor3("vFogColor", this._scene.fogColor);
  24850. }
  24851. // VBOs
  24852. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24853. // Draw order
  24854. engine.setDepthFunctionToLessOrEqual();
  24855. effect.setBool("alphaTest", true);
  24856. engine.setColorWrite(false);
  24857. engine.draw(true, 0, max * 6);
  24858. engine.setColorWrite(true);
  24859. effect.setBool("alphaTest", false);
  24860. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24861. engine.draw(true, 0, max * 6);
  24862. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24863. };
  24864. SpriteManager.prototype.dispose = function () {
  24865. if (this._vertexBuffer) {
  24866. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24867. this._vertexBuffer = null;
  24868. }
  24869. if (this._indexBuffer) {
  24870. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24871. this._indexBuffer = null;
  24872. }
  24873. if (this._spriteTexture) {
  24874. this._spriteTexture.dispose();
  24875. this._spriteTexture = null;
  24876. }
  24877. // Remove from scene
  24878. var index = this._scene.spriteManagers.indexOf(this);
  24879. this._scene.spriteManagers.splice(index, 1);
  24880. // Callback
  24881. this.onDisposeObservable.notifyObservers(this);
  24882. this.onDisposeObservable.clear();
  24883. };
  24884. return SpriteManager;
  24885. })();
  24886. BABYLON.SpriteManager = SpriteManager;
  24887. })(BABYLON || (BABYLON = {}));
  24888. var BABYLON;
  24889. (function (BABYLON) {
  24890. var Sprite = (function () {
  24891. function Sprite(name, manager) {
  24892. this.name = name;
  24893. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24894. this.width = 1.0;
  24895. this.height = 1.0;
  24896. this.angle = 0;
  24897. this.cellIndex = 0;
  24898. this.invertU = 0;
  24899. this.invertV = 0;
  24900. this.animations = new Array();
  24901. this.isPickable = false;
  24902. this._animationStarted = false;
  24903. this._loopAnimation = false;
  24904. this._fromIndex = 0;
  24905. this._toIndex = 0;
  24906. this._delay = 0;
  24907. this._direction = 1;
  24908. this._frameCount = 0;
  24909. this._time = 0;
  24910. this._manager = manager;
  24911. this._manager.sprites.push(this);
  24912. this.position = BABYLON.Vector3.Zero();
  24913. }
  24914. Object.defineProperty(Sprite.prototype, "size", {
  24915. get: function () {
  24916. return this.width;
  24917. },
  24918. set: function (value) {
  24919. this.width = value;
  24920. this.height = value;
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24926. this._fromIndex = from;
  24927. this._toIndex = to;
  24928. this._loopAnimation = loop;
  24929. this._delay = delay;
  24930. this._animationStarted = true;
  24931. this._direction = from < to ? 1 : -1;
  24932. this.cellIndex = from;
  24933. this._time = 0;
  24934. };
  24935. Sprite.prototype.stopAnimation = function () {
  24936. this._animationStarted = false;
  24937. };
  24938. Sprite.prototype._animate = function (deltaTime) {
  24939. if (!this._animationStarted)
  24940. return;
  24941. this._time += deltaTime;
  24942. if (this._time > this._delay) {
  24943. this._time = this._time % this._delay;
  24944. this.cellIndex += this._direction;
  24945. if (this.cellIndex == this._toIndex) {
  24946. if (this._loopAnimation) {
  24947. this.cellIndex = this._fromIndex;
  24948. }
  24949. else {
  24950. this._animationStarted = false;
  24951. if (this.disposeWhenFinishedAnimating) {
  24952. this.dispose();
  24953. }
  24954. }
  24955. }
  24956. }
  24957. };
  24958. Sprite.prototype.dispose = function () {
  24959. for (var i = 0; i < this._manager.sprites.length; i++) {
  24960. if (this._manager.sprites[i] == this) {
  24961. this._manager.sprites.splice(i, 1);
  24962. }
  24963. }
  24964. };
  24965. return Sprite;
  24966. })();
  24967. BABYLON.Sprite = Sprite;
  24968. })(BABYLON || (BABYLON = {}));
  24969. var BABYLON;
  24970. (function (BABYLON) {
  24971. var Layer = (function () {
  24972. function Layer(name, imgUrl, scene, isBackground, color) {
  24973. this.name = name;
  24974. this.scale = new BABYLON.Vector2(1, 1);
  24975. this.offset = new BABYLON.Vector2(0, 0);
  24976. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24977. this._vertexDeclaration = [2];
  24978. this._vertexStrideSize = 2 * 4;
  24979. // Events
  24980. /**
  24981. * An event triggered when the layer is disposed.
  24982. * @type {BABYLON.Observable}
  24983. */
  24984. this.onDisposeObservable = new BABYLON.Observable();
  24985. /**
  24986. * An event triggered before rendering the scene
  24987. * @type {BABYLON.Observable}
  24988. */
  24989. this.onBeforeRenderObservable = new BABYLON.Observable();
  24990. /**
  24991. * An event triggered after rendering the scene
  24992. * @type {BABYLON.Observable}
  24993. */
  24994. this.onAfterRenderObservable = new BABYLON.Observable();
  24995. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24996. this.isBackground = isBackground === undefined ? true : isBackground;
  24997. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24998. this._scene = scene;
  24999. this._scene.layers.push(this);
  25000. // VBO
  25001. var vertices = [];
  25002. vertices.push(1, 1);
  25003. vertices.push(-1, 1);
  25004. vertices.push(-1, -1);
  25005. vertices.push(1, -1);
  25006. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  25007. // Indices
  25008. var indices = [];
  25009. indices.push(0);
  25010. indices.push(1);
  25011. indices.push(2);
  25012. indices.push(0);
  25013. indices.push(2);
  25014. indices.push(3);
  25015. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25016. // Effects
  25017. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  25018. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  25019. }
  25020. Object.defineProperty(Layer.prototype, "onDispose", {
  25021. set: function (callback) {
  25022. if (this._onDisposeObserver) {
  25023. this.onDisposeObservable.remove(this._onDisposeObserver);
  25024. }
  25025. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25026. },
  25027. enumerable: true,
  25028. configurable: true
  25029. });
  25030. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  25031. set: function (callback) {
  25032. if (this._onBeforeRenderObserver) {
  25033. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25034. }
  25035. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25036. },
  25037. enumerable: true,
  25038. configurable: true
  25039. });
  25040. Object.defineProperty(Layer.prototype, "onAfterRender", {
  25041. set: function (callback) {
  25042. if (this._onAfterRenderObserver) {
  25043. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25044. }
  25045. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25046. },
  25047. enumerable: true,
  25048. configurable: true
  25049. });
  25050. Layer.prototype.render = function () {
  25051. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  25052. // Check
  25053. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  25054. return;
  25055. var engine = this._scene.getEngine();
  25056. this.onBeforeRenderObservable.notifyObservers(this);
  25057. // Render
  25058. engine.enableEffect(currentEffect);
  25059. engine.setState(false);
  25060. // Texture
  25061. currentEffect.setTexture("textureSampler", this.texture);
  25062. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  25063. // Color
  25064. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  25065. // Scale / offset
  25066. currentEffect.setVector2("offset", this.offset);
  25067. currentEffect.setVector2("scale", this.scale);
  25068. // VBOs
  25069. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  25070. // Draw order
  25071. if (!this._alphaTestEffect) {
  25072. engine.setAlphaMode(this.alphaBlendingMode);
  25073. engine.draw(true, 0, 6);
  25074. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25075. }
  25076. else {
  25077. engine.draw(true, 0, 6);
  25078. }
  25079. this.onAfterRenderObservable.notifyObservers(this);
  25080. };
  25081. Layer.prototype.dispose = function () {
  25082. if (this._vertexBuffer) {
  25083. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25084. this._vertexBuffer = null;
  25085. }
  25086. if (this._indexBuffer) {
  25087. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25088. this._indexBuffer = null;
  25089. }
  25090. if (this.texture) {
  25091. this.texture.dispose();
  25092. this.texture = null;
  25093. }
  25094. // Remove from scene
  25095. var index = this._scene.layers.indexOf(this);
  25096. this._scene.layers.splice(index, 1);
  25097. // Callback
  25098. this.onDisposeObservable.notifyObservers(this);
  25099. this.onDisposeObservable.clear();
  25100. this.onAfterRenderObservable.clear();
  25101. this.onBeforeRenderObservable.clear();
  25102. };
  25103. return Layer;
  25104. })();
  25105. BABYLON.Layer = Layer;
  25106. })(BABYLON || (BABYLON = {}));
  25107. var BABYLON;
  25108. (function (BABYLON) {
  25109. var Particle = (function () {
  25110. function Particle() {
  25111. this.position = BABYLON.Vector3.Zero();
  25112. this.direction = BABYLON.Vector3.Zero();
  25113. this.color = new BABYLON.Color4(0, 0, 0, 0);
  25114. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  25115. this.lifeTime = 1.0;
  25116. this.age = 0;
  25117. this.size = 0;
  25118. this.angle = 0;
  25119. this.angularSpeed = 0;
  25120. }
  25121. Particle.prototype.copyTo = function (other) {
  25122. other.position.copyFrom(this.position);
  25123. other.direction.copyFrom(this.direction);
  25124. other.color.copyFrom(this.color);
  25125. other.colorStep.copyFrom(this.colorStep);
  25126. other.lifeTime = this.lifeTime;
  25127. other.age = this.age;
  25128. other.size = this.size;
  25129. other.angle = this.angle;
  25130. other.angularSpeed = this.angularSpeed;
  25131. };
  25132. return Particle;
  25133. })();
  25134. BABYLON.Particle = Particle;
  25135. })(BABYLON || (BABYLON = {}));
  25136. var BABYLON;
  25137. (function (BABYLON) {
  25138. var randomNumber = function (min, max) {
  25139. if (min === max) {
  25140. return (min);
  25141. }
  25142. var random = Math.random();
  25143. return ((random * (max - min)) + min);
  25144. };
  25145. var ParticleSystem = (function () {
  25146. function ParticleSystem(name, capacity, scene, customEffect) {
  25147. var _this = this;
  25148. this.name = name;
  25149. // Members
  25150. this.animations = [];
  25151. this.renderingGroupId = 0;
  25152. this.emitter = null;
  25153. this.emitRate = 10;
  25154. this.manualEmitCount = -1;
  25155. this.updateSpeed = 0.01;
  25156. this.targetStopDuration = 0;
  25157. this.disposeOnStop = false;
  25158. this.minEmitPower = 1;
  25159. this.maxEmitPower = 1;
  25160. this.minLifeTime = 1;
  25161. this.maxLifeTime = 1;
  25162. this.minSize = 1;
  25163. this.maxSize = 1;
  25164. this.minAngularSpeed = 0;
  25165. this.maxAngularSpeed = 0;
  25166. this.layerMask = 0x0FFFFFFF;
  25167. /**
  25168. * An event triggered when the system is disposed.
  25169. * @type {BABYLON.Observable}
  25170. */
  25171. this.onDisposeObservable = new BABYLON.Observable();
  25172. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  25173. this.forceDepthWrite = false;
  25174. this.gravity = BABYLON.Vector3.Zero();
  25175. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  25176. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  25177. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  25178. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  25179. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25180. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25181. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  25182. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25183. this.particles = new Array();
  25184. this._vertexDeclaration = [3, 4, 4];
  25185. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  25186. this._stockParticles = new Array();
  25187. this._newPartsExcess = 0;
  25188. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  25189. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  25190. this._scaledDirection = BABYLON.Vector3.Zero();
  25191. this._scaledGravity = BABYLON.Vector3.Zero();
  25192. this._currentRenderId = -1;
  25193. this._started = false;
  25194. this._stopped = false;
  25195. this._actualFrame = 0;
  25196. this.id = name;
  25197. this._capacity = capacity;
  25198. this._scene = scene;
  25199. this._customEffect = customEffect;
  25200. scene.particleSystems.push(this);
  25201. // VBO
  25202. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  25203. var indices = [];
  25204. var index = 0;
  25205. for (var count = 0; count < capacity; count++) {
  25206. indices.push(index);
  25207. indices.push(index + 1);
  25208. indices.push(index + 2);
  25209. indices.push(index);
  25210. indices.push(index + 2);
  25211. indices.push(index + 3);
  25212. index += 4;
  25213. }
  25214. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25215. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  25216. // Default behaviors
  25217. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  25218. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  25219. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  25220. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  25221. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  25222. };
  25223. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  25224. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  25225. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  25226. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  25227. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  25228. };
  25229. this.updateFunction = function (particles) {
  25230. for (var index = 0; index < particles.length; index++) {
  25231. var particle = particles[index];
  25232. particle.age += _this._scaledUpdateSpeed;
  25233. if (particle.age >= particle.lifeTime) {
  25234. _this.recycleParticle(particle);
  25235. index--;
  25236. continue;
  25237. }
  25238. else {
  25239. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  25240. particle.color.addInPlace(_this._scaledColorStep);
  25241. if (particle.color.a < 0)
  25242. particle.color.a = 0;
  25243. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  25244. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  25245. particle.position.addInPlace(_this._scaledDirection);
  25246. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  25247. particle.direction.addInPlace(_this._scaledGravity);
  25248. }
  25249. }
  25250. };
  25251. }
  25252. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  25253. set: function (callback) {
  25254. if (this._onDisposeObserver) {
  25255. this.onDisposeObservable.remove(this._onDisposeObserver);
  25256. }
  25257. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25258. },
  25259. enumerable: true,
  25260. configurable: true
  25261. });
  25262. ParticleSystem.prototype.recycleParticle = function (particle) {
  25263. var lastParticle = this.particles.pop();
  25264. if (lastParticle !== particle) {
  25265. lastParticle.copyTo(particle);
  25266. this._stockParticles.push(lastParticle);
  25267. }
  25268. };
  25269. ParticleSystem.prototype.getCapacity = function () {
  25270. return this._capacity;
  25271. };
  25272. ParticleSystem.prototype.isAlive = function () {
  25273. return this._alive;
  25274. };
  25275. ParticleSystem.prototype.isStarted = function () {
  25276. return this._started;
  25277. };
  25278. ParticleSystem.prototype.start = function () {
  25279. this._started = true;
  25280. this._stopped = false;
  25281. this._actualFrame = 0;
  25282. };
  25283. ParticleSystem.prototype.stop = function () {
  25284. this._stopped = true;
  25285. };
  25286. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  25287. var offset = index * 11;
  25288. this._vertices[offset] = particle.position.x;
  25289. this._vertices[offset + 1] = particle.position.y;
  25290. this._vertices[offset + 2] = particle.position.z;
  25291. this._vertices[offset + 3] = particle.color.r;
  25292. this._vertices[offset + 4] = particle.color.g;
  25293. this._vertices[offset + 5] = particle.color.b;
  25294. this._vertices[offset + 6] = particle.color.a;
  25295. this._vertices[offset + 7] = particle.angle;
  25296. this._vertices[offset + 8] = particle.size;
  25297. this._vertices[offset + 9] = offsetX;
  25298. this._vertices[offset + 10] = offsetY;
  25299. };
  25300. ParticleSystem.prototype._update = function (newParticles) {
  25301. // Update current
  25302. this._alive = this.particles.length > 0;
  25303. this.updateFunction(this.particles);
  25304. // Add new ones
  25305. var worldMatrix;
  25306. if (this.emitter.position) {
  25307. worldMatrix = this.emitter.getWorldMatrix();
  25308. }
  25309. else {
  25310. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  25311. }
  25312. var particle;
  25313. for (var index = 0; index < newParticles; index++) {
  25314. if (this.particles.length === this._capacity) {
  25315. break;
  25316. }
  25317. if (this._stockParticles.length !== 0) {
  25318. particle = this._stockParticles.pop();
  25319. particle.age = 0;
  25320. }
  25321. else {
  25322. particle = new BABYLON.Particle();
  25323. }
  25324. this.particles.push(particle);
  25325. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  25326. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  25327. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  25328. particle.size = randomNumber(this.minSize, this.maxSize);
  25329. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  25330. this.startPositionFunction(worldMatrix, particle.position, particle);
  25331. var step = randomNumber(0, 1.0);
  25332. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  25333. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  25334. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  25335. }
  25336. };
  25337. ParticleSystem.prototype._getEffect = function () {
  25338. if (this._customEffect) {
  25339. return this._customEffect;
  25340. }
  25341. ;
  25342. var defines = [];
  25343. if (this._scene.clipPlane) {
  25344. defines.push("#define CLIPPLANE");
  25345. }
  25346. // Effect
  25347. var join = defines.join("\n");
  25348. if (this._cachedDefines !== join) {
  25349. this._cachedDefines = join;
  25350. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  25351. }
  25352. return this._effect;
  25353. };
  25354. ParticleSystem.prototype.animate = function () {
  25355. if (!this._started)
  25356. return;
  25357. var effect = this._getEffect();
  25358. // Check
  25359. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  25360. return;
  25361. if (this._currentRenderId === this._scene.getRenderId()) {
  25362. return;
  25363. }
  25364. this._currentRenderId = this._scene.getRenderId();
  25365. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  25366. // determine the number of particles we need to create
  25367. var newParticles;
  25368. if (this.manualEmitCount > -1) {
  25369. newParticles = this.manualEmitCount;
  25370. this._newPartsExcess = 0;
  25371. this.manualEmitCount = 0;
  25372. }
  25373. else {
  25374. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  25375. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  25376. }
  25377. if (this._newPartsExcess > 1.0) {
  25378. newParticles += this._newPartsExcess >> 0;
  25379. this._newPartsExcess -= this._newPartsExcess >> 0;
  25380. }
  25381. this._alive = false;
  25382. if (!this._stopped) {
  25383. this._actualFrame += this._scaledUpdateSpeed;
  25384. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  25385. this.stop();
  25386. }
  25387. else {
  25388. newParticles = 0;
  25389. }
  25390. this._update(newParticles);
  25391. // Stopped?
  25392. if (this._stopped) {
  25393. if (!this._alive) {
  25394. this._started = false;
  25395. if (this.disposeOnStop) {
  25396. this._scene._toBeDisposed.push(this);
  25397. }
  25398. }
  25399. }
  25400. // Update VBO
  25401. var offset = 0;
  25402. for (var index = 0; index < this.particles.length; index++) {
  25403. var particle = this.particles[index];
  25404. this._appendParticleVertex(offset++, particle, 0, 0);
  25405. this._appendParticleVertex(offset++, particle, 1, 0);
  25406. this._appendParticleVertex(offset++, particle, 1, 1);
  25407. this._appendParticleVertex(offset++, particle, 0, 1);
  25408. }
  25409. var engine = this._scene.getEngine();
  25410. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  25411. };
  25412. ParticleSystem.prototype.render = function () {
  25413. var effect = this._getEffect();
  25414. // Check
  25415. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  25416. return 0;
  25417. var engine = this._scene.getEngine();
  25418. // Render
  25419. engine.enableEffect(effect);
  25420. engine.setState(false);
  25421. var viewMatrix = this._scene.getViewMatrix();
  25422. effect.setTexture("diffuseSampler", this.particleTexture);
  25423. effect.setMatrix("view", viewMatrix);
  25424. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25425. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  25426. if (this._scene.clipPlane) {
  25427. var clipPlane = this._scene.clipPlane;
  25428. var invView = viewMatrix.clone();
  25429. invView.invert();
  25430. effect.setMatrix("invView", invView);
  25431. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25432. }
  25433. // VBOs
  25434. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25435. // Draw order
  25436. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  25437. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  25438. }
  25439. else {
  25440. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25441. }
  25442. if (this.forceDepthWrite) {
  25443. engine.setDepthWrite(true);
  25444. }
  25445. engine.draw(true, 0, this.particles.length * 6);
  25446. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25447. return this.particles.length;
  25448. };
  25449. ParticleSystem.prototype.dispose = function () {
  25450. if (this._vertexBuffer) {
  25451. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25452. this._vertexBuffer = null;
  25453. }
  25454. if (this._indexBuffer) {
  25455. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25456. this._indexBuffer = null;
  25457. }
  25458. if (this.particleTexture) {
  25459. this.particleTexture.dispose();
  25460. this.particleTexture = null;
  25461. }
  25462. // Remove from scene
  25463. var index = this._scene.particleSystems.indexOf(this);
  25464. this._scene.particleSystems.splice(index, 1);
  25465. // Callback
  25466. this.onDisposeObservable.notifyObservers(this);
  25467. this.onDisposeObservable.clear();
  25468. };
  25469. // Clone
  25470. ParticleSystem.prototype.clone = function (name, newEmitter) {
  25471. var result = new ParticleSystem(name, this._capacity, this._scene);
  25472. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  25473. if (newEmitter === undefined) {
  25474. newEmitter = this.emitter;
  25475. }
  25476. result.emitter = newEmitter;
  25477. if (this.particleTexture) {
  25478. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  25479. }
  25480. result.start();
  25481. return result;
  25482. };
  25483. ParticleSystem.prototype.serialize = function () {
  25484. var serializationObject = {};
  25485. serializationObject.name = this.name;
  25486. serializationObject.id = this.id;
  25487. // Emitter
  25488. if (this.emitter.position) {
  25489. serializationObject.emitterId = this.emitter.id;
  25490. }
  25491. else {
  25492. serializationObject.emitter = this.emitter.asArray();
  25493. }
  25494. serializationObject.capacity = this.getCapacity();
  25495. if (this.particleTexture) {
  25496. serializationObject.textureName = this.particleTexture.name;
  25497. }
  25498. // Animations
  25499. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25500. // Particle system
  25501. serializationObject.minAngularSpeed = this.minAngularSpeed;
  25502. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  25503. serializationObject.minSize = this.minSize;
  25504. serializationObject.maxSize = this.maxSize;
  25505. serializationObject.minEmitPower = this.minEmitPower;
  25506. serializationObject.maxEmitPower = this.maxEmitPower;
  25507. serializationObject.minLifeTime = this.minLifeTime;
  25508. serializationObject.maxLifeTime = this.maxLifeTime;
  25509. serializationObject.emitRate = this.emitRate;
  25510. serializationObject.minEmitBox = this.minEmitBox.asArray();
  25511. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  25512. serializationObject.gravity = this.gravity.asArray();
  25513. serializationObject.direction1 = this.direction1.asArray();
  25514. serializationObject.direction2 = this.direction2.asArray();
  25515. serializationObject.color1 = this.color1.asArray();
  25516. serializationObject.color2 = this.color2.asArray();
  25517. serializationObject.colorDead = this.colorDead.asArray();
  25518. serializationObject.updateSpeed = this.updateSpeed;
  25519. serializationObject.targetStopDuration = this.targetStopDuration;
  25520. serializationObject.textureMask = this.textureMask.asArray();
  25521. serializationObject.blendMode = this.blendMode;
  25522. return serializationObject;
  25523. };
  25524. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  25525. var name = parsedParticleSystem.name;
  25526. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  25527. if (parsedParticleSystem.id) {
  25528. particleSystem.id = parsedParticleSystem.id;
  25529. }
  25530. // Texture
  25531. if (parsedParticleSystem.textureName) {
  25532. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  25533. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  25534. }
  25535. // Emitter
  25536. if (parsedParticleSystem.emitterId) {
  25537. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  25538. }
  25539. else {
  25540. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  25541. }
  25542. // Animations
  25543. if (parsedParticleSystem.animations) {
  25544. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  25545. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  25546. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25547. }
  25548. }
  25549. if (parsedParticleSystem.autoAnimate) {
  25550. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  25551. }
  25552. // Particle system
  25553. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  25554. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  25555. particleSystem.minSize = parsedParticleSystem.minSize;
  25556. particleSystem.maxSize = parsedParticleSystem.maxSize;
  25557. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  25558. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  25559. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  25560. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  25561. particleSystem.emitRate = parsedParticleSystem.emitRate;
  25562. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  25563. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  25564. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  25565. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  25566. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  25567. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  25568. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  25569. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  25570. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  25571. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  25572. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  25573. particleSystem.blendMode = parsedParticleSystem.blendMode;
  25574. if (!parsedParticleSystem.preventAutoStart) {
  25575. particleSystem.start();
  25576. }
  25577. return particleSystem;
  25578. };
  25579. // Statics
  25580. ParticleSystem.BLENDMODE_ONEONE = 0;
  25581. ParticleSystem.BLENDMODE_STANDARD = 1;
  25582. return ParticleSystem;
  25583. })();
  25584. BABYLON.ParticleSystem = ParticleSystem;
  25585. })(BABYLON || (BABYLON = {}));
  25586. var BABYLON;
  25587. (function (BABYLON) {
  25588. var AnimationRange = (function () {
  25589. function AnimationRange(name, from, to) {
  25590. this.name = name;
  25591. this.from = from;
  25592. this.to = to;
  25593. }
  25594. AnimationRange.prototype.clone = function () {
  25595. return new AnimationRange(this.name, this.from, this.to);
  25596. };
  25597. return AnimationRange;
  25598. })();
  25599. BABYLON.AnimationRange = AnimationRange;
  25600. /**
  25601. * Composed of a frame, and an action function
  25602. */
  25603. var AnimationEvent = (function () {
  25604. function AnimationEvent(frame, action, onlyOnce) {
  25605. this.frame = frame;
  25606. this.action = action;
  25607. this.onlyOnce = onlyOnce;
  25608. this.isDone = false;
  25609. }
  25610. return AnimationEvent;
  25611. })();
  25612. BABYLON.AnimationEvent = AnimationEvent;
  25613. var PathCursor = (function () {
  25614. function PathCursor(path) {
  25615. this.path = path;
  25616. this._onchange = new Array();
  25617. this.value = 0;
  25618. this.animations = new Array();
  25619. }
  25620. PathCursor.prototype.getPoint = function () {
  25621. var point = this.path.getPointAtLengthPosition(this.value);
  25622. return new BABYLON.Vector3(point.x, 0, point.y);
  25623. };
  25624. PathCursor.prototype.moveAhead = function (step) {
  25625. if (step === void 0) { step = 0.002; }
  25626. this.move(step);
  25627. return this;
  25628. };
  25629. PathCursor.prototype.moveBack = function (step) {
  25630. if (step === void 0) { step = 0.002; }
  25631. this.move(-step);
  25632. return this;
  25633. };
  25634. PathCursor.prototype.move = function (step) {
  25635. if (Math.abs(step) > 1) {
  25636. throw "step size should be less than 1.";
  25637. }
  25638. this.value += step;
  25639. this.ensureLimits();
  25640. this.raiseOnChange();
  25641. return this;
  25642. };
  25643. PathCursor.prototype.ensureLimits = function () {
  25644. while (this.value > 1) {
  25645. this.value -= 1;
  25646. }
  25647. while (this.value < 0) {
  25648. this.value += 1;
  25649. }
  25650. return this;
  25651. };
  25652. // used by animation engine
  25653. PathCursor.prototype.markAsDirty = function (propertyName) {
  25654. this.ensureLimits();
  25655. this.raiseOnChange();
  25656. return this;
  25657. };
  25658. PathCursor.prototype.raiseOnChange = function () {
  25659. var _this = this;
  25660. this._onchange.forEach(function (f) { return f(_this); });
  25661. return this;
  25662. };
  25663. PathCursor.prototype.onchange = function (f) {
  25664. this._onchange.push(f);
  25665. return this;
  25666. };
  25667. return PathCursor;
  25668. })();
  25669. BABYLON.PathCursor = PathCursor;
  25670. var Animation = (function () {
  25671. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25672. this.name = name;
  25673. this.targetProperty = targetProperty;
  25674. this.framePerSecond = framePerSecond;
  25675. this.dataType = dataType;
  25676. this.loopMode = loopMode;
  25677. this.enableBlending = enableBlending;
  25678. this._offsetsCache = {};
  25679. this._highLimitsCache = {};
  25680. this._stopped = false;
  25681. this._blendingFactor = 0;
  25682. // The set of event that will be linked to this animation
  25683. this._events = new Array();
  25684. this.allowMatricesInterpolation = false;
  25685. this.blendingSpeed = 0.01;
  25686. this._ranges = {};
  25687. this.targetPropertyPath = targetProperty.split(".");
  25688. this.dataType = dataType;
  25689. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25690. }
  25691. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25692. var dataType = undefined;
  25693. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25694. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25695. }
  25696. else if (from instanceof BABYLON.Quaternion) {
  25697. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25698. }
  25699. else if (from instanceof BABYLON.Vector3) {
  25700. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25701. }
  25702. else if (from instanceof BABYLON.Vector2) {
  25703. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25704. }
  25705. else if (from instanceof BABYLON.Color3) {
  25706. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25707. }
  25708. if (dataType == undefined) {
  25709. return null;
  25710. }
  25711. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25712. var keys = [];
  25713. keys.push({ frame: 0, value: from });
  25714. keys.push({ frame: totalFrame, value: to });
  25715. animation.setKeys(keys);
  25716. if (easingFunction !== undefined) {
  25717. animation.setEasingFunction(easingFunction);
  25718. }
  25719. return animation;
  25720. };
  25721. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25722. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25723. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25724. };
  25725. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25726. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25727. node.animations.push(animation);
  25728. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25729. };
  25730. // Methods
  25731. /**
  25732. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25733. */
  25734. Animation.prototype.toString = function (fullDetails) {
  25735. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25736. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25737. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25738. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25739. if (fullDetails) {
  25740. ret += ", Ranges: {";
  25741. var first = true;
  25742. for (var name in this._ranges) {
  25743. if (first) {
  25744. ret += ", ";
  25745. first = false;
  25746. }
  25747. ret += name;
  25748. }
  25749. ret += "}";
  25750. }
  25751. return ret;
  25752. };
  25753. /**
  25754. * Add an event to this animation.
  25755. */
  25756. Animation.prototype.addEvent = function (event) {
  25757. this._events.push(event);
  25758. };
  25759. /**
  25760. * Remove all events found at the given frame
  25761. * @param frame
  25762. */
  25763. Animation.prototype.removeEvents = function (frame) {
  25764. for (var index = 0; index < this._events.length; index++) {
  25765. if (this._events[index].frame === frame) {
  25766. this._events.splice(index, 1);
  25767. index--;
  25768. }
  25769. }
  25770. };
  25771. Animation.prototype.createRange = function (name, from, to) {
  25772. // check name not already in use; could happen for bones after serialized
  25773. if (!this._ranges[name]) {
  25774. this._ranges[name] = new AnimationRange(name, from, to);
  25775. }
  25776. };
  25777. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25778. if (deleteFrames === void 0) { deleteFrames = true; }
  25779. if (this._ranges[name]) {
  25780. if (deleteFrames) {
  25781. var from = this._ranges[name].from;
  25782. var to = this._ranges[name].to;
  25783. // this loop MUST go high to low for multiple splices to work
  25784. for (var key = this._keys.length - 1; key >= 0; key--) {
  25785. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25786. this._keys.splice(key, 1);
  25787. }
  25788. }
  25789. }
  25790. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25791. }
  25792. };
  25793. Animation.prototype.getRange = function (name) {
  25794. return this._ranges[name];
  25795. };
  25796. Animation.prototype.reset = function () {
  25797. this._offsetsCache = {};
  25798. this._highLimitsCache = {};
  25799. this.currentFrame = 0;
  25800. this._blendingFactor = 0;
  25801. this._originalBlendValue = null;
  25802. };
  25803. Animation.prototype.isStopped = function () {
  25804. return this._stopped;
  25805. };
  25806. Animation.prototype.getKeys = function () {
  25807. return this._keys;
  25808. };
  25809. Animation.prototype.getHighestFrame = function () {
  25810. var ret = 0;
  25811. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25812. if (ret < this._keys[key].frame) {
  25813. ret = this._keys[key].frame;
  25814. }
  25815. }
  25816. return ret;
  25817. };
  25818. Animation.prototype.getEasingFunction = function () {
  25819. return this._easingFunction;
  25820. };
  25821. Animation.prototype.setEasingFunction = function (easingFunction) {
  25822. this._easingFunction = easingFunction;
  25823. };
  25824. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25825. return startValue + (endValue - startValue) * gradient;
  25826. };
  25827. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25828. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25829. };
  25830. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25831. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25832. };
  25833. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25834. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25835. };
  25836. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25837. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25838. };
  25839. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25840. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25841. };
  25842. Animation.prototype.clone = function () {
  25843. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25844. if (this._keys) {
  25845. clone.setKeys(this._keys);
  25846. }
  25847. if (this._ranges) {
  25848. clone._ranges = {};
  25849. for (var name in this._ranges) {
  25850. clone._ranges[name] = this._ranges[name].clone();
  25851. }
  25852. }
  25853. return clone;
  25854. };
  25855. Animation.prototype.setKeys = function (values) {
  25856. this._keys = values.slice(0);
  25857. this._offsetsCache = {};
  25858. this._highLimitsCache = {};
  25859. };
  25860. Animation.prototype._getKeyValue = function (value) {
  25861. if (typeof value === "function") {
  25862. return value();
  25863. }
  25864. return value;
  25865. };
  25866. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25867. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25868. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25869. }
  25870. this.currentFrame = currentFrame;
  25871. // Try to get a hash to find the right key
  25872. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  25873. if (this._keys[startKey].frame >= currentFrame) {
  25874. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25875. startKey--;
  25876. }
  25877. }
  25878. for (var key = startKey; key < this._keys.length; key++) {
  25879. if (this._keys[key + 1].frame >= currentFrame) {
  25880. var startValue = this._getKeyValue(this._keys[key].value);
  25881. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25882. // gradient : percent of currentFrame between the frame inf and the frame sup
  25883. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25884. // check for easingFunction and correction of gradient
  25885. if (this._easingFunction != null) {
  25886. gradient = this._easingFunction.ease(gradient);
  25887. }
  25888. switch (this.dataType) {
  25889. // Float
  25890. case Animation.ANIMATIONTYPE_FLOAT:
  25891. switch (loopMode) {
  25892. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25893. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25894. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25895. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25896. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25897. }
  25898. break;
  25899. // Quaternion
  25900. case Animation.ANIMATIONTYPE_QUATERNION:
  25901. var quaternion = null;
  25902. switch (loopMode) {
  25903. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25904. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25905. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25906. break;
  25907. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25908. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25909. break;
  25910. }
  25911. return quaternion;
  25912. // Vector3
  25913. case Animation.ANIMATIONTYPE_VECTOR3:
  25914. switch (loopMode) {
  25915. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25916. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25917. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25918. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25919. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25920. }
  25921. // Vector2
  25922. case Animation.ANIMATIONTYPE_VECTOR2:
  25923. switch (loopMode) {
  25924. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25925. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25926. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25927. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25928. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25929. }
  25930. // Color3
  25931. case Animation.ANIMATIONTYPE_COLOR3:
  25932. switch (loopMode) {
  25933. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25934. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25935. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25936. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25937. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25938. }
  25939. // Matrix
  25940. case Animation.ANIMATIONTYPE_MATRIX:
  25941. switch (loopMode) {
  25942. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25943. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25944. if (this.allowMatricesInterpolation) {
  25945. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25946. }
  25947. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25948. return startValue;
  25949. }
  25950. default:
  25951. break;
  25952. }
  25953. break;
  25954. }
  25955. }
  25956. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25957. };
  25958. Animation.prototype.setValue = function (currentValue, blend) {
  25959. if (blend === void 0) { blend = false; }
  25960. // Set value
  25961. var path;
  25962. var destination;
  25963. if (this.targetPropertyPath.length > 1) {
  25964. var property = this._target[this.targetPropertyPath[0]];
  25965. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25966. property = property[this.targetPropertyPath[index]];
  25967. }
  25968. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25969. destination = property;
  25970. }
  25971. else {
  25972. path = this.targetPropertyPath[0];
  25973. destination = this._target;
  25974. }
  25975. // Blending
  25976. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25977. if (!this._originalBlendValue) {
  25978. if (destination[path].clone) {
  25979. this._originalBlendValue = destination[path].clone();
  25980. }
  25981. else {
  25982. this._originalBlendValue = destination[path];
  25983. }
  25984. }
  25985. if (this._originalBlendValue.prototype) {
  25986. if (this._originalBlendValue.prototype.Lerp) {
  25987. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25988. }
  25989. else {
  25990. destination[path] = currentValue;
  25991. }
  25992. }
  25993. else if (this._originalBlendValue.m) {
  25994. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  25995. }
  25996. else {
  25997. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25998. }
  25999. this._blendingFactor += this.blendingSpeed;
  26000. }
  26001. else {
  26002. destination[path] = currentValue;
  26003. }
  26004. if (this._target.markAsDirty) {
  26005. this._target.markAsDirty(this.targetProperty);
  26006. }
  26007. };
  26008. Animation.prototype.goToFrame = function (frame) {
  26009. if (frame < this._keys[0].frame) {
  26010. frame = this._keys[0].frame;
  26011. }
  26012. else if (frame > this._keys[this._keys.length - 1].frame) {
  26013. frame = this._keys[this._keys.length - 1].frame;
  26014. }
  26015. var currentValue = this._interpolate(frame, 0, this.loopMode);
  26016. this.setValue(currentValue);
  26017. };
  26018. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  26019. if (blend === void 0) { blend = false; }
  26020. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  26021. this._stopped = true;
  26022. return false;
  26023. }
  26024. var returnValue = true;
  26025. // Adding a start key at frame 0 if missing
  26026. if (this._keys[0].frame !== 0) {
  26027. var newKey = { frame: 0, value: this._keys[0].value };
  26028. this._keys.splice(0, 0, newKey);
  26029. }
  26030. // Check limits
  26031. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  26032. from = this._keys[0].frame;
  26033. }
  26034. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  26035. to = this._keys[this._keys.length - 1].frame;
  26036. }
  26037. // Compute ratio
  26038. var range = to - from;
  26039. var offsetValue;
  26040. // ratio represents the frame delta between from and to
  26041. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  26042. var highLimitValue = 0;
  26043. if (ratio > range && !loop) {
  26044. returnValue = false;
  26045. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  26046. }
  26047. else {
  26048. // Get max value if required
  26049. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  26050. var keyOffset = to.toString() + from.toString();
  26051. if (!this._offsetsCache[keyOffset]) {
  26052. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26053. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26054. switch (this.dataType) {
  26055. // Float
  26056. case Animation.ANIMATIONTYPE_FLOAT:
  26057. this._offsetsCache[keyOffset] = toValue - fromValue;
  26058. break;
  26059. // Quaternion
  26060. case Animation.ANIMATIONTYPE_QUATERNION:
  26061. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26062. break;
  26063. // Vector3
  26064. case Animation.ANIMATIONTYPE_VECTOR3:
  26065. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26066. // Vector2
  26067. case Animation.ANIMATIONTYPE_VECTOR2:
  26068. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26069. // Color3
  26070. case Animation.ANIMATIONTYPE_COLOR3:
  26071. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26072. default:
  26073. break;
  26074. }
  26075. this._highLimitsCache[keyOffset] = toValue;
  26076. }
  26077. highLimitValue = this._highLimitsCache[keyOffset];
  26078. offsetValue = this._offsetsCache[keyOffset];
  26079. }
  26080. }
  26081. if (offsetValue === undefined) {
  26082. switch (this.dataType) {
  26083. // Float
  26084. case Animation.ANIMATIONTYPE_FLOAT:
  26085. offsetValue = 0;
  26086. break;
  26087. // Quaternion
  26088. case Animation.ANIMATIONTYPE_QUATERNION:
  26089. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  26090. break;
  26091. // Vector3
  26092. case Animation.ANIMATIONTYPE_VECTOR3:
  26093. offsetValue = BABYLON.Vector3.Zero();
  26094. break;
  26095. // Vector2
  26096. case Animation.ANIMATIONTYPE_VECTOR2:
  26097. offsetValue = BABYLON.Vector2.Zero();
  26098. break;
  26099. // Color3
  26100. case Animation.ANIMATIONTYPE_COLOR3:
  26101. offsetValue = BABYLON.Color3.Black();
  26102. }
  26103. }
  26104. // Compute value
  26105. var repeatCount = (ratio / range) >> 0;
  26106. var currentFrame = returnValue ? from + ratio % range : to;
  26107. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  26108. // Set value
  26109. this.setValue(currentValue);
  26110. // Check events
  26111. for (var index = 0; index < this._events.length; index++) {
  26112. if (currentFrame >= this._events[index].frame) {
  26113. var event = this._events[index];
  26114. if (!event.isDone) {
  26115. // If event should be done only once, remove it.
  26116. if (event.onlyOnce) {
  26117. this._events.splice(index, 1);
  26118. index--;
  26119. }
  26120. event.isDone = true;
  26121. event.action();
  26122. } // Don't do anything if the event has already be done.
  26123. }
  26124. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  26125. // reset event, the animation is looping
  26126. this._events[index].isDone = false;
  26127. }
  26128. }
  26129. if (!returnValue) {
  26130. this._stopped = true;
  26131. }
  26132. return returnValue;
  26133. };
  26134. Animation.prototype.serialize = function () {
  26135. var serializationObject = {};
  26136. serializationObject.name = this.name;
  26137. serializationObject.property = this.targetProperty;
  26138. serializationObject.framePerSecond = this.framePerSecond;
  26139. serializationObject.dataType = this.dataType;
  26140. serializationObject.loopBehavior = this.loopMode;
  26141. var dataType = this.dataType;
  26142. serializationObject.keys = [];
  26143. var keys = this.getKeys();
  26144. for (var index = 0; index < keys.length; index++) {
  26145. var animationKey = keys[index];
  26146. var key = {};
  26147. key.frame = animationKey.frame;
  26148. switch (dataType) {
  26149. case Animation.ANIMATIONTYPE_FLOAT:
  26150. key.values = [animationKey.value];
  26151. break;
  26152. case Animation.ANIMATIONTYPE_QUATERNION:
  26153. case Animation.ANIMATIONTYPE_MATRIX:
  26154. case Animation.ANIMATIONTYPE_VECTOR3:
  26155. case Animation.ANIMATIONTYPE_COLOR3:
  26156. key.values = animationKey.value.asArray();
  26157. break;
  26158. }
  26159. serializationObject.keys.push(key);
  26160. }
  26161. serializationObject.ranges = [];
  26162. for (var name in this._ranges) {
  26163. var range = {};
  26164. range.name = name;
  26165. range.from = this._ranges[name].from;
  26166. range.to = this._ranges[name].to;
  26167. serializationObject.ranges.push(range);
  26168. }
  26169. return serializationObject;
  26170. };
  26171. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  26172. get: function () {
  26173. return Animation._ANIMATIONTYPE_FLOAT;
  26174. },
  26175. enumerable: true,
  26176. configurable: true
  26177. });
  26178. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  26179. get: function () {
  26180. return Animation._ANIMATIONTYPE_VECTOR3;
  26181. },
  26182. enumerable: true,
  26183. configurable: true
  26184. });
  26185. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  26186. get: function () {
  26187. return Animation._ANIMATIONTYPE_VECTOR2;
  26188. },
  26189. enumerable: true,
  26190. configurable: true
  26191. });
  26192. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  26193. get: function () {
  26194. return Animation._ANIMATIONTYPE_QUATERNION;
  26195. },
  26196. enumerable: true,
  26197. configurable: true
  26198. });
  26199. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  26200. get: function () {
  26201. return Animation._ANIMATIONTYPE_MATRIX;
  26202. },
  26203. enumerable: true,
  26204. configurable: true
  26205. });
  26206. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  26207. get: function () {
  26208. return Animation._ANIMATIONTYPE_COLOR3;
  26209. },
  26210. enumerable: true,
  26211. configurable: true
  26212. });
  26213. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  26214. get: function () {
  26215. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  26216. },
  26217. enumerable: true,
  26218. configurable: true
  26219. });
  26220. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  26221. get: function () {
  26222. return Animation._ANIMATIONLOOPMODE_CYCLE;
  26223. },
  26224. enumerable: true,
  26225. configurable: true
  26226. });
  26227. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  26228. get: function () {
  26229. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  26230. },
  26231. enumerable: true,
  26232. configurable: true
  26233. });
  26234. Animation.Parse = function (parsedAnimation) {
  26235. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  26236. var dataType = parsedAnimation.dataType;
  26237. var keys = [];
  26238. var data;
  26239. var index;
  26240. for (index = 0; index < parsedAnimation.keys.length; index++) {
  26241. var key = parsedAnimation.keys[index];
  26242. switch (dataType) {
  26243. case Animation.ANIMATIONTYPE_FLOAT:
  26244. data = key.values[0];
  26245. break;
  26246. case Animation.ANIMATIONTYPE_QUATERNION:
  26247. data = BABYLON.Quaternion.FromArray(key.values);
  26248. break;
  26249. case Animation.ANIMATIONTYPE_MATRIX:
  26250. data = BABYLON.Matrix.FromArray(key.values);
  26251. break;
  26252. case Animation.ANIMATIONTYPE_COLOR3:
  26253. data = BABYLON.Color3.FromArray(key.values);
  26254. break;
  26255. case Animation.ANIMATIONTYPE_VECTOR3:
  26256. default:
  26257. data = BABYLON.Vector3.FromArray(key.values);
  26258. break;
  26259. }
  26260. keys.push({
  26261. frame: key.frame,
  26262. value: data
  26263. });
  26264. }
  26265. animation.setKeys(keys);
  26266. if (parsedAnimation.ranges) {
  26267. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  26268. data = parsedAnimation.ranges[index];
  26269. animation.createRange(data.name, data.from, data.to);
  26270. }
  26271. }
  26272. return animation;
  26273. };
  26274. Animation.AppendSerializedAnimations = function (source, destination) {
  26275. if (source.animations) {
  26276. destination.animations = [];
  26277. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  26278. var animation = source.animations[animationIndex];
  26279. destination.animations.push(animation.serialize());
  26280. }
  26281. }
  26282. };
  26283. // Statics
  26284. Animation._ANIMATIONTYPE_FLOAT = 0;
  26285. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  26286. Animation._ANIMATIONTYPE_QUATERNION = 2;
  26287. Animation._ANIMATIONTYPE_MATRIX = 3;
  26288. Animation._ANIMATIONTYPE_COLOR3 = 4;
  26289. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  26290. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  26291. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  26292. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  26293. return Animation;
  26294. })();
  26295. BABYLON.Animation = Animation;
  26296. })(BABYLON || (BABYLON = {}));
  26297. var BABYLON;
  26298. (function (BABYLON) {
  26299. var Animatable = (function () {
  26300. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  26301. if (fromFrame === void 0) { fromFrame = 0; }
  26302. if (toFrame === void 0) { toFrame = 100; }
  26303. if (loopAnimation === void 0) { loopAnimation = false; }
  26304. if (speedRatio === void 0) { speedRatio = 1.0; }
  26305. this.target = target;
  26306. this.fromFrame = fromFrame;
  26307. this.toFrame = toFrame;
  26308. this.loopAnimation = loopAnimation;
  26309. this.speedRatio = speedRatio;
  26310. this.onAnimationEnd = onAnimationEnd;
  26311. this._animations = new Array();
  26312. this._paused = false;
  26313. this.animationStarted = false;
  26314. if (animations) {
  26315. this.appendAnimations(target, animations);
  26316. }
  26317. this._scene = scene;
  26318. scene._activeAnimatables.push(this);
  26319. }
  26320. // Methods
  26321. Animatable.prototype.getAnimations = function () {
  26322. return this._animations;
  26323. };
  26324. Animatable.prototype.appendAnimations = function (target, animations) {
  26325. for (var index = 0; index < animations.length; index++) {
  26326. var animation = animations[index];
  26327. animation._target = target;
  26328. this._animations.push(animation);
  26329. }
  26330. };
  26331. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  26332. var animations = this._animations;
  26333. for (var index = 0; index < animations.length; index++) {
  26334. if (animations[index].targetProperty === property) {
  26335. return animations[index];
  26336. }
  26337. }
  26338. return null;
  26339. };
  26340. Animatable.prototype.reset = function () {
  26341. var animations = this._animations;
  26342. for (var index = 0; index < animations.length; index++) {
  26343. animations[index].reset();
  26344. }
  26345. this._localDelayOffset = null;
  26346. this._pausedDelay = null;
  26347. };
  26348. Animatable.prototype.enableBlending = function (blendingSpeed) {
  26349. var animations = this._animations;
  26350. for (var index = 0; index < animations.length; index++) {
  26351. animations[index].enableBlending = true;
  26352. animations[index].blendingSpeed = blendingSpeed;
  26353. }
  26354. };
  26355. Animatable.prototype.disableBlending = function () {
  26356. var animations = this._animations;
  26357. for (var index = 0; index < animations.length; index++) {
  26358. animations[index].enableBlending = false;
  26359. }
  26360. };
  26361. Animatable.prototype.goToFrame = function (frame) {
  26362. var animations = this._animations;
  26363. for (var index = 0; index < animations.length; index++) {
  26364. animations[index].goToFrame(frame);
  26365. }
  26366. };
  26367. Animatable.prototype.pause = function () {
  26368. if (this._paused) {
  26369. return;
  26370. }
  26371. this._paused = true;
  26372. };
  26373. Animatable.prototype.restart = function () {
  26374. this._paused = false;
  26375. };
  26376. Animatable.prototype.stop = function () {
  26377. var index = this._scene._activeAnimatables.indexOf(this);
  26378. if (index > -1) {
  26379. this._scene._activeAnimatables.splice(index, 1);
  26380. var animations = this._animations;
  26381. for (var index = 0; index < animations.length; index++) {
  26382. animations[index].reset();
  26383. }
  26384. if (this.onAnimationEnd) {
  26385. this.onAnimationEnd();
  26386. }
  26387. }
  26388. };
  26389. Animatable.prototype._animate = function (delay) {
  26390. if (this._paused) {
  26391. this.animationStarted = false;
  26392. if (!this._pausedDelay) {
  26393. this._pausedDelay = delay;
  26394. }
  26395. return true;
  26396. }
  26397. if (!this._localDelayOffset) {
  26398. this._localDelayOffset = delay;
  26399. }
  26400. else if (this._pausedDelay) {
  26401. this._localDelayOffset += delay - this._pausedDelay;
  26402. this._pausedDelay = null;
  26403. }
  26404. // Animating
  26405. var running = false;
  26406. var animations = this._animations;
  26407. var index;
  26408. for (index = 0; index < animations.length; index++) {
  26409. var animation = animations[index];
  26410. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  26411. running = running || isRunning;
  26412. }
  26413. this.animationStarted = running;
  26414. if (!running) {
  26415. // Remove from active animatables
  26416. index = this._scene._activeAnimatables.indexOf(this);
  26417. this._scene._activeAnimatables.splice(index, 1);
  26418. }
  26419. if (!running && this.onAnimationEnd) {
  26420. this.onAnimationEnd();
  26421. this.onAnimationEnd = null;
  26422. }
  26423. return running;
  26424. };
  26425. return Animatable;
  26426. })();
  26427. BABYLON.Animatable = Animatable;
  26428. })(BABYLON || (BABYLON = {}));
  26429. var BABYLON;
  26430. (function (BABYLON) {
  26431. var EasingFunction = (function () {
  26432. function EasingFunction() {
  26433. // Properties
  26434. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  26435. }
  26436. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  26437. get: function () {
  26438. return EasingFunction._EASINGMODE_EASEIN;
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  26444. get: function () {
  26445. return EasingFunction._EASINGMODE_EASEOUT;
  26446. },
  26447. enumerable: true,
  26448. configurable: true
  26449. });
  26450. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  26451. get: function () {
  26452. return EasingFunction._EASINGMODE_EASEINOUT;
  26453. },
  26454. enumerable: true,
  26455. configurable: true
  26456. });
  26457. EasingFunction.prototype.setEasingMode = function (easingMode) {
  26458. var n = Math.min(Math.max(easingMode, 0), 2);
  26459. this._easingMode = n;
  26460. };
  26461. EasingFunction.prototype.getEasingMode = function () {
  26462. return this._easingMode;
  26463. };
  26464. EasingFunction.prototype.easeInCore = function (gradient) {
  26465. throw new Error('You must implement this method');
  26466. };
  26467. EasingFunction.prototype.ease = function (gradient) {
  26468. switch (this._easingMode) {
  26469. case EasingFunction.EASINGMODE_EASEIN:
  26470. return this.easeInCore(gradient);
  26471. case EasingFunction.EASINGMODE_EASEOUT:
  26472. return (1 - this.easeInCore(1 - gradient));
  26473. }
  26474. if (gradient >= 0.5) {
  26475. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  26476. }
  26477. return (this.easeInCore(gradient * 2) * 0.5);
  26478. };
  26479. //Statics
  26480. EasingFunction._EASINGMODE_EASEIN = 0;
  26481. EasingFunction._EASINGMODE_EASEOUT = 1;
  26482. EasingFunction._EASINGMODE_EASEINOUT = 2;
  26483. return EasingFunction;
  26484. })();
  26485. BABYLON.EasingFunction = EasingFunction;
  26486. var CircleEase = (function (_super) {
  26487. __extends(CircleEase, _super);
  26488. function CircleEase() {
  26489. _super.apply(this, arguments);
  26490. }
  26491. CircleEase.prototype.easeInCore = function (gradient) {
  26492. gradient = Math.max(0, Math.min(1, gradient));
  26493. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  26494. };
  26495. return CircleEase;
  26496. })(EasingFunction);
  26497. BABYLON.CircleEase = CircleEase;
  26498. var BackEase = (function (_super) {
  26499. __extends(BackEase, _super);
  26500. function BackEase(amplitude) {
  26501. if (amplitude === void 0) { amplitude = 1; }
  26502. _super.call(this);
  26503. this.amplitude = amplitude;
  26504. }
  26505. BackEase.prototype.easeInCore = function (gradient) {
  26506. var num = Math.max(0, this.amplitude);
  26507. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  26508. };
  26509. return BackEase;
  26510. })(EasingFunction);
  26511. BABYLON.BackEase = BackEase;
  26512. var BounceEase = (function (_super) {
  26513. __extends(BounceEase, _super);
  26514. function BounceEase(bounces, bounciness) {
  26515. if (bounces === void 0) { bounces = 3; }
  26516. if (bounciness === void 0) { bounciness = 2; }
  26517. _super.call(this);
  26518. this.bounces = bounces;
  26519. this.bounciness = bounciness;
  26520. }
  26521. BounceEase.prototype.easeInCore = function (gradient) {
  26522. var y = Math.max(0.0, this.bounces);
  26523. var bounciness = this.bounciness;
  26524. if (bounciness <= 1.0) {
  26525. bounciness = 1.001;
  26526. }
  26527. var num9 = Math.pow(bounciness, y);
  26528. var num5 = 1.0 - bounciness;
  26529. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  26530. var num15 = gradient * num4;
  26531. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  26532. var num3 = Math.floor(num65);
  26533. var num13 = num3 + 1.0;
  26534. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  26535. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  26536. var num7 = (num8 + num12) * 0.5;
  26537. var num6 = gradient - num7;
  26538. var num2 = num7 - num8;
  26539. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  26540. };
  26541. return BounceEase;
  26542. })(EasingFunction);
  26543. BABYLON.BounceEase = BounceEase;
  26544. var CubicEase = (function (_super) {
  26545. __extends(CubicEase, _super);
  26546. function CubicEase() {
  26547. _super.apply(this, arguments);
  26548. }
  26549. CubicEase.prototype.easeInCore = function (gradient) {
  26550. return (gradient * gradient * gradient);
  26551. };
  26552. return CubicEase;
  26553. })(EasingFunction);
  26554. BABYLON.CubicEase = CubicEase;
  26555. var ElasticEase = (function (_super) {
  26556. __extends(ElasticEase, _super);
  26557. function ElasticEase(oscillations, springiness) {
  26558. if (oscillations === void 0) { oscillations = 3; }
  26559. if (springiness === void 0) { springiness = 3; }
  26560. _super.call(this);
  26561. this.oscillations = oscillations;
  26562. this.springiness = springiness;
  26563. }
  26564. ElasticEase.prototype.easeInCore = function (gradient) {
  26565. var num2;
  26566. var num3 = Math.max(0.0, this.oscillations);
  26567. var num = Math.max(0.0, this.springiness);
  26568. if (num == 0) {
  26569. num2 = gradient;
  26570. }
  26571. else {
  26572. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  26573. }
  26574. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  26575. };
  26576. return ElasticEase;
  26577. })(EasingFunction);
  26578. BABYLON.ElasticEase = ElasticEase;
  26579. var ExponentialEase = (function (_super) {
  26580. __extends(ExponentialEase, _super);
  26581. function ExponentialEase(exponent) {
  26582. if (exponent === void 0) { exponent = 2; }
  26583. _super.call(this);
  26584. this.exponent = exponent;
  26585. }
  26586. ExponentialEase.prototype.easeInCore = function (gradient) {
  26587. if (this.exponent <= 0) {
  26588. return gradient;
  26589. }
  26590. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  26591. };
  26592. return ExponentialEase;
  26593. })(EasingFunction);
  26594. BABYLON.ExponentialEase = ExponentialEase;
  26595. var PowerEase = (function (_super) {
  26596. __extends(PowerEase, _super);
  26597. function PowerEase(power) {
  26598. if (power === void 0) { power = 2; }
  26599. _super.call(this);
  26600. this.power = power;
  26601. }
  26602. PowerEase.prototype.easeInCore = function (gradient) {
  26603. var y = Math.max(0.0, this.power);
  26604. return Math.pow(gradient, y);
  26605. };
  26606. return PowerEase;
  26607. })(EasingFunction);
  26608. BABYLON.PowerEase = PowerEase;
  26609. var QuadraticEase = (function (_super) {
  26610. __extends(QuadraticEase, _super);
  26611. function QuadraticEase() {
  26612. _super.apply(this, arguments);
  26613. }
  26614. QuadraticEase.prototype.easeInCore = function (gradient) {
  26615. return (gradient * gradient);
  26616. };
  26617. return QuadraticEase;
  26618. })(EasingFunction);
  26619. BABYLON.QuadraticEase = QuadraticEase;
  26620. var QuarticEase = (function (_super) {
  26621. __extends(QuarticEase, _super);
  26622. function QuarticEase() {
  26623. _super.apply(this, arguments);
  26624. }
  26625. QuarticEase.prototype.easeInCore = function (gradient) {
  26626. return (gradient * gradient * gradient * gradient);
  26627. };
  26628. return QuarticEase;
  26629. })(EasingFunction);
  26630. BABYLON.QuarticEase = QuarticEase;
  26631. var QuinticEase = (function (_super) {
  26632. __extends(QuinticEase, _super);
  26633. function QuinticEase() {
  26634. _super.apply(this, arguments);
  26635. }
  26636. QuinticEase.prototype.easeInCore = function (gradient) {
  26637. return (gradient * gradient * gradient * gradient * gradient);
  26638. };
  26639. return QuinticEase;
  26640. })(EasingFunction);
  26641. BABYLON.QuinticEase = QuinticEase;
  26642. var SineEase = (function (_super) {
  26643. __extends(SineEase, _super);
  26644. function SineEase() {
  26645. _super.apply(this, arguments);
  26646. }
  26647. SineEase.prototype.easeInCore = function (gradient) {
  26648. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26649. };
  26650. return SineEase;
  26651. })(EasingFunction);
  26652. BABYLON.SineEase = SineEase;
  26653. var BezierCurveEase = (function (_super) {
  26654. __extends(BezierCurveEase, _super);
  26655. function BezierCurveEase(x1, y1, x2, y2) {
  26656. if (x1 === void 0) { x1 = 0; }
  26657. if (y1 === void 0) { y1 = 0; }
  26658. if (x2 === void 0) { x2 = 1; }
  26659. if (y2 === void 0) { y2 = 1; }
  26660. _super.call(this);
  26661. this.x1 = x1;
  26662. this.y1 = y1;
  26663. this.x2 = x2;
  26664. this.y2 = y2;
  26665. }
  26666. BezierCurveEase.prototype.easeInCore = function (gradient) {
  26667. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  26668. };
  26669. return BezierCurveEase;
  26670. })(EasingFunction);
  26671. BABYLON.BezierCurveEase = BezierCurveEase;
  26672. })(BABYLON || (BABYLON = {}));
  26673. var BABYLON;
  26674. (function (BABYLON) {
  26675. var Bone = (function (_super) {
  26676. __extends(Bone, _super);
  26677. function Bone(name, skeleton, parentBone, matrix, restPose) {
  26678. _super.call(this, name, skeleton.getScene());
  26679. this.name = name;
  26680. this.children = new Array();
  26681. this.animations = new Array();
  26682. this._worldTransform = new BABYLON.Matrix();
  26683. this._absoluteTransform = new BABYLON.Matrix();
  26684. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26685. this._skeleton = skeleton;
  26686. this._matrix = matrix;
  26687. this._baseMatrix = matrix;
  26688. this._restPose = restPose ? restPose : matrix.clone();
  26689. skeleton.bones.push(this);
  26690. if (parentBone) {
  26691. this._parent = parentBone;
  26692. parentBone.children.push(this);
  26693. }
  26694. else {
  26695. this._parent = null;
  26696. }
  26697. this._updateDifferenceMatrix();
  26698. }
  26699. // Members
  26700. Bone.prototype.getParent = function () {
  26701. return this._parent;
  26702. };
  26703. Bone.prototype.getLocalMatrix = function () {
  26704. return this._matrix;
  26705. };
  26706. Bone.prototype.getBaseMatrix = function () {
  26707. return this._baseMatrix;
  26708. };
  26709. Bone.prototype.getRestPose = function () {
  26710. return this._restPose;
  26711. };
  26712. Bone.prototype.returnToRest = function () {
  26713. this.updateMatrix(this._restPose.clone());
  26714. };
  26715. Bone.prototype.getWorldMatrix = function () {
  26716. return this._worldTransform;
  26717. };
  26718. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26719. return this._invertedAbsoluteTransform;
  26720. };
  26721. Bone.prototype.getAbsoluteTransform = function () {
  26722. return this._absoluteTransform;
  26723. };
  26724. // Methods
  26725. Bone.prototype.updateMatrix = function (matrix) {
  26726. this._baseMatrix = matrix.clone();
  26727. this._matrix = matrix.clone();
  26728. this._skeleton._markAsDirty();
  26729. this._updateDifferenceMatrix();
  26730. };
  26731. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26732. if (!rootMatrix) {
  26733. rootMatrix = this._baseMatrix;
  26734. }
  26735. if (this._parent) {
  26736. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26737. }
  26738. else {
  26739. this._absoluteTransform.copyFrom(rootMatrix);
  26740. }
  26741. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26742. for (var index = 0; index < this.children.length; index++) {
  26743. this.children[index]._updateDifferenceMatrix();
  26744. }
  26745. };
  26746. Bone.prototype.markAsDirty = function () {
  26747. this._currentRenderId++;
  26748. this._skeleton._markAsDirty();
  26749. };
  26750. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26751. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26752. // all animation may be coming from a library skeleton, so may need to create animation
  26753. if (this.animations.length === 0) {
  26754. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26755. this.animations[0].setKeys([]);
  26756. }
  26757. // get animation info / verify there is such a range from the source bone
  26758. var sourceRange = source.animations[0].getRange(rangeName);
  26759. if (!sourceRange) {
  26760. return false;
  26761. }
  26762. var from = sourceRange.from;
  26763. var to = sourceRange.to;
  26764. var sourceKeys = source.animations[0].getKeys();
  26765. // rescaling prep
  26766. var sourceBoneLength = source.length;
  26767. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26768. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26769. var destKeys = this.animations[0].getKeys();
  26770. // loop vars declaration / initialization
  26771. var orig;
  26772. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26773. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26774. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26775. var mat;
  26776. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26777. orig = sourceKeys[key];
  26778. if (orig.frame >= from && orig.frame <= to) {
  26779. if (scalingReqd) {
  26780. orig.value.decompose(origScale, origRotation, origTranslation);
  26781. origTranslation.scaleInPlace(ratio);
  26782. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26783. }
  26784. else {
  26785. mat = orig.value;
  26786. }
  26787. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26788. }
  26789. }
  26790. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26791. return true;
  26792. };
  26793. return Bone;
  26794. })(BABYLON.Node);
  26795. BABYLON.Bone = Bone;
  26796. })(BABYLON || (BABYLON = {}));
  26797. var BABYLON;
  26798. (function (BABYLON) {
  26799. var Skeleton = (function () {
  26800. function Skeleton(name, id, scene) {
  26801. this.name = name;
  26802. this.id = id;
  26803. this.bones = new Array();
  26804. this.needInitialSkinMatrix = false;
  26805. this._isDirty = true;
  26806. this._meshesWithPoseMatrix = new Array();
  26807. this._identity = BABYLON.Matrix.Identity();
  26808. this._ranges = {};
  26809. this.bones = [];
  26810. this._scene = scene;
  26811. scene.skeletons.push(this);
  26812. //make sure it will recalculate the matrix next time prepare is called.
  26813. this._isDirty = true;
  26814. }
  26815. // Members
  26816. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26817. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26818. return mesh._bonesTransformMatrices;
  26819. }
  26820. return this._transformMatrices;
  26821. };
  26822. Skeleton.prototype.getScene = function () {
  26823. return this._scene;
  26824. };
  26825. // Methods
  26826. /**
  26827. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26828. */
  26829. Skeleton.prototype.toString = function (fullDetails) {
  26830. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26831. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26832. if (fullDetails) {
  26833. ret += ", Ranges: {";
  26834. var first = true;
  26835. for (var name_1 in this._ranges) {
  26836. if (first) {
  26837. ret += ", ";
  26838. first = false;
  26839. }
  26840. ret += name_1;
  26841. }
  26842. ret += "}";
  26843. }
  26844. return ret;
  26845. };
  26846. /**
  26847. * Get bone's index searching by name
  26848. * @param {string} name is bone's name to search for
  26849. * @return {number} Indice of the bone. Returns -1 if not found
  26850. */
  26851. Skeleton.prototype.getBoneIndexByName = function (name) {
  26852. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26853. if (this.bones[boneIndex].name === name) {
  26854. return boneIndex;
  26855. }
  26856. }
  26857. return -1;
  26858. };
  26859. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26860. // check name not already in use
  26861. if (!this._ranges[name]) {
  26862. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26863. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26864. if (this.bones[i].animations[0]) {
  26865. this.bones[i].animations[0].createRange(name, from, to);
  26866. }
  26867. }
  26868. }
  26869. };
  26870. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26871. if (deleteFrames === void 0) { deleteFrames = true; }
  26872. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26873. if (this.bones[i].animations[0]) {
  26874. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26875. }
  26876. }
  26877. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26878. };
  26879. Skeleton.prototype.getAnimationRange = function (name) {
  26880. return this._ranges[name];
  26881. };
  26882. /**
  26883. * Returns as an Array, all AnimationRanges defined on this skeleton
  26884. */
  26885. Skeleton.prototype.getAnimationRanges = function () {
  26886. var animationRanges = [];
  26887. var name;
  26888. var i = 0;
  26889. for (name in this._ranges) {
  26890. animationRanges[i] = this._ranges[name];
  26891. i++;
  26892. }
  26893. return animationRanges;
  26894. };
  26895. /**
  26896. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26897. */
  26898. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26899. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26900. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26901. return false;
  26902. }
  26903. var ret = true;
  26904. var frameOffset = this._getHighestAnimationFrame() + 1;
  26905. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26906. var boneDict = {};
  26907. var sourceBones = source.bones;
  26908. var nBones;
  26909. var i;
  26910. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26911. boneDict[sourceBones[i].name] = sourceBones[i];
  26912. }
  26913. if (this.bones.length !== sourceBones.length) {
  26914. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26915. ret = false;
  26916. }
  26917. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  26918. var boneName = this.bones[i].name;
  26919. var sourceBone = boneDict[boneName];
  26920. if (sourceBone) {
  26921. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26922. }
  26923. else {
  26924. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26925. ret = false;
  26926. }
  26927. }
  26928. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26929. var range = source.getAnimationRange(name);
  26930. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26931. return ret;
  26932. };
  26933. Skeleton.prototype.returnToRest = function () {
  26934. for (var index = 0; index < this.bones.length; index++) {
  26935. this.bones[index].returnToRest();
  26936. }
  26937. };
  26938. Skeleton.prototype._getHighestAnimationFrame = function () {
  26939. var ret = 0;
  26940. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26941. if (this.bones[i].animations[0]) {
  26942. var highest = this.bones[i].animations[0].getHighestFrame();
  26943. if (ret < highest) {
  26944. ret = highest;
  26945. }
  26946. }
  26947. }
  26948. return ret;
  26949. };
  26950. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26951. var range = this.getAnimationRange(name);
  26952. if (!range) {
  26953. return null;
  26954. }
  26955. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26956. };
  26957. Skeleton.prototype._markAsDirty = function () {
  26958. this._isDirty = true;
  26959. };
  26960. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26961. this._meshesWithPoseMatrix.push(mesh);
  26962. };
  26963. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26964. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26965. if (index > -1) {
  26966. this._meshesWithPoseMatrix.splice(index, 1);
  26967. }
  26968. };
  26969. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26970. for (var index = 0; index < this.bones.length; index++) {
  26971. var bone = this.bones[index];
  26972. var parentBone = bone.getParent();
  26973. if (parentBone) {
  26974. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26975. }
  26976. else {
  26977. if (initialSkinMatrix) {
  26978. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26979. }
  26980. else {
  26981. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26982. }
  26983. }
  26984. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26985. }
  26986. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26987. };
  26988. Skeleton.prototype.prepare = function () {
  26989. if (!this._isDirty) {
  26990. return;
  26991. }
  26992. if (this.needInitialSkinMatrix) {
  26993. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26994. var mesh = this._meshesWithPoseMatrix[index];
  26995. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26996. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26997. }
  26998. var poseMatrix = mesh.getPoseMatrix();
  26999. // Prepare bones
  27000. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  27001. var bone = this.bones[boneIndex];
  27002. if (!bone.getParent()) {
  27003. var matrix = bone.getBaseMatrix();
  27004. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  27005. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  27006. }
  27007. }
  27008. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  27009. }
  27010. }
  27011. else {
  27012. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  27013. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27014. }
  27015. this._computeTransformMatrices(this._transformMatrices, null);
  27016. }
  27017. this._isDirty = false;
  27018. this._scene._activeBones += this.bones.length;
  27019. };
  27020. Skeleton.prototype.getAnimatables = function () {
  27021. if (!this._animatables || this._animatables.length !== this.bones.length) {
  27022. this._animatables = [];
  27023. for (var index = 0; index < this.bones.length; index++) {
  27024. this._animatables.push(this.bones[index]);
  27025. }
  27026. }
  27027. return this._animatables;
  27028. };
  27029. Skeleton.prototype.clone = function (name, id) {
  27030. var result = new Skeleton(name, id || name, this._scene);
  27031. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27032. for (var index = 0; index < this.bones.length; index++) {
  27033. var source = this.bones[index];
  27034. var parentBone = null;
  27035. if (source.getParent()) {
  27036. var parentIndex = this.bones.indexOf(source.getParent());
  27037. parentBone = result.bones[parentIndex];
  27038. }
  27039. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  27040. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  27041. }
  27042. if (this._ranges) {
  27043. result._ranges = {};
  27044. for (var rangeName in this._ranges) {
  27045. result._ranges[rangeName] = this._ranges[rangeName].clone();
  27046. }
  27047. }
  27048. this._isDirty = true;
  27049. return result;
  27050. };
  27051. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  27052. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  27053. this.bones.forEach(function (bone) {
  27054. bone.animations.forEach(function (animation) {
  27055. animation.enableBlending = true;
  27056. animation.blendingSpeed = blendingSpeed;
  27057. });
  27058. });
  27059. };
  27060. Skeleton.prototype.dispose = function () {
  27061. this._meshesWithPoseMatrix = [];
  27062. // Animations
  27063. this.getScene().stopAnimation(this);
  27064. // Remove from scene
  27065. this.getScene().removeSkeleton(this);
  27066. };
  27067. Skeleton.prototype.serialize = function () {
  27068. var serializationObject = {};
  27069. serializationObject.name = this.name;
  27070. serializationObject.id = this.id;
  27071. serializationObject.bones = [];
  27072. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27073. for (var index = 0; index < this.bones.length; index++) {
  27074. var bone = this.bones[index];
  27075. var serializedBone = {
  27076. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  27077. name: bone.name,
  27078. matrix: bone.getLocalMatrix().toArray(),
  27079. rest: bone.getRestPose().toArray()
  27080. };
  27081. serializationObject.bones.push(serializedBone);
  27082. if (bone.length) {
  27083. serializedBone.length = bone.length;
  27084. }
  27085. if (bone.animations && bone.animations.length > 0) {
  27086. serializedBone.animation = bone.animations[0].serialize();
  27087. }
  27088. serializationObject.ranges = [];
  27089. for (var name in this._ranges) {
  27090. var range = {};
  27091. range.name = name;
  27092. range.from = this._ranges[name].from;
  27093. range.to = this._ranges[name].to;
  27094. serializationObject.ranges.push(range);
  27095. }
  27096. }
  27097. return serializationObject;
  27098. };
  27099. Skeleton.Parse = function (parsedSkeleton, scene) {
  27100. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  27101. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  27102. var index;
  27103. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  27104. var parsedBone = parsedSkeleton.bones[index];
  27105. var parentBone = null;
  27106. if (parsedBone.parentBoneIndex > -1) {
  27107. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  27108. }
  27109. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  27110. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  27111. if (parsedBone.length) {
  27112. bone.length = parsedBone.length;
  27113. }
  27114. if (parsedBone.animation) {
  27115. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  27116. }
  27117. }
  27118. // placed after bones, so createAnimationRange can cascade down
  27119. if (parsedSkeleton.ranges) {
  27120. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  27121. var data = parsedSkeleton.ranges[index];
  27122. skeleton.createAnimationRange(data.name, data.from, data.to);
  27123. }
  27124. }
  27125. return skeleton;
  27126. };
  27127. return Skeleton;
  27128. })();
  27129. BABYLON.Skeleton = Skeleton;
  27130. })(BABYLON || (BABYLON = {}));
  27131. var BABYLON;
  27132. (function (BABYLON) {
  27133. var PostProcess = (function () {
  27134. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  27135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  27136. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27137. this.name = name;
  27138. this.width = -1;
  27139. this.height = -1;
  27140. /*
  27141. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  27142. Can only be used on a single postprocess or on the last one of a chain.
  27143. */
  27144. this.enablePixelPerfectMode = false;
  27145. this._reusable = false;
  27146. this._textures = new BABYLON.SmartArray(2);
  27147. this._currentRenderTextureInd = 0;
  27148. this._scaleRatio = new BABYLON.Vector2(1, 1);
  27149. // Events
  27150. /**
  27151. * An event triggered when the postprocess is activated.
  27152. * @type {BABYLON.Observable}
  27153. */
  27154. this.onActivateObservable = new BABYLON.Observable();
  27155. /**
  27156. * An event triggered when the postprocess changes its size.
  27157. * @type {BABYLON.Observable}
  27158. */
  27159. this.onSizeChangedObservable = new BABYLON.Observable();
  27160. /**
  27161. * An event triggered when the postprocess applies its effect.
  27162. * @type {BABYLON.Observable}
  27163. */
  27164. this.onApplyObservable = new BABYLON.Observable();
  27165. /**
  27166. * An event triggered before rendering the postprocess
  27167. * @type {BABYLON.Observable}
  27168. */
  27169. this.onBeforeRenderObservable = new BABYLON.Observable();
  27170. /**
  27171. * An event triggered after rendering the postprocess
  27172. * @type {BABYLON.Observable}
  27173. */
  27174. this.onAfterRenderObservable = new BABYLON.Observable();
  27175. if (camera != null) {
  27176. this._camera = camera;
  27177. this._scene = camera.getScene();
  27178. camera.attachPostProcess(this);
  27179. this._engine = this._scene.getEngine();
  27180. }
  27181. else {
  27182. this._engine = engine;
  27183. }
  27184. this._renderRatio = ratio;
  27185. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  27186. this._reusable = reusable || false;
  27187. this._textureType = textureType;
  27188. this._samplers = samplers || [];
  27189. this._samplers.push("textureSampler");
  27190. this._fragmentUrl = fragmentUrl;
  27191. this._parameters = parameters || [];
  27192. this._parameters.push("scale");
  27193. this.updateEffect(defines);
  27194. }
  27195. Object.defineProperty(PostProcess.prototype, "onActivate", {
  27196. set: function (callback) {
  27197. if (this._onActivateObserver) {
  27198. this.onActivateObservable.remove(this._onActivateObserver);
  27199. }
  27200. this._onActivateObserver = this.onActivateObservable.add(callback);
  27201. },
  27202. enumerable: true,
  27203. configurable: true
  27204. });
  27205. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  27206. set: function (callback) {
  27207. if (this._onSizeChangedObserver) {
  27208. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  27209. }
  27210. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  27211. },
  27212. enumerable: true,
  27213. configurable: true
  27214. });
  27215. Object.defineProperty(PostProcess.prototype, "onApply", {
  27216. set: function (callback) {
  27217. if (this._onApplyObserver) {
  27218. this.onApplyObservable.remove(this._onApplyObserver);
  27219. }
  27220. this._onApplyObserver = this.onApplyObservable.add(callback);
  27221. },
  27222. enumerable: true,
  27223. configurable: true
  27224. });
  27225. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  27226. set: function (callback) {
  27227. if (this._onBeforeRenderObserver) {
  27228. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27229. }
  27230. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27231. },
  27232. enumerable: true,
  27233. configurable: true
  27234. });
  27235. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  27236. set: function (callback) {
  27237. if (this._onAfterRenderObserver) {
  27238. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27239. }
  27240. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27241. },
  27242. enumerable: true,
  27243. configurable: true
  27244. });
  27245. PostProcess.prototype.updateEffect = function (defines) {
  27246. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  27247. };
  27248. PostProcess.prototype.isReusable = function () {
  27249. return this._reusable;
  27250. };
  27251. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  27252. PostProcess.prototype.markTextureDirty = function () {
  27253. this.width = -1;
  27254. };
  27255. PostProcess.prototype.activate = function (camera, sourceTexture) {
  27256. camera = camera || this._camera;
  27257. var scene = camera.getScene();
  27258. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  27259. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  27260. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  27261. var desiredWidth = this._renderRatio.width || requiredWidth;
  27262. var desiredHeight = this._renderRatio.height || requiredHeight;
  27263. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27264. if (!this._renderRatio.width) {
  27265. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  27266. }
  27267. if (!this._renderRatio.height) {
  27268. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  27269. }
  27270. }
  27271. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  27272. if (this._textures.length > 0) {
  27273. for (var i = 0; i < this._textures.length; i++) {
  27274. this._engine._releaseTexture(this._textures.data[i]);
  27275. }
  27276. this._textures.reset();
  27277. }
  27278. this.width = desiredWidth;
  27279. this.height = desiredHeight;
  27280. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  27281. if (this._reusable) {
  27282. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  27283. }
  27284. this.onSizeChangedObservable.notifyObservers(this);
  27285. }
  27286. if (this.enablePixelPerfectMode) {
  27287. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  27288. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  27289. }
  27290. else {
  27291. this._scaleRatio.copyFromFloats(1, 1);
  27292. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  27293. }
  27294. this.onActivateObservable.notifyObservers(camera);
  27295. // Clear
  27296. if (this.clearColor) {
  27297. this._engine.clear(this.clearColor, true, true);
  27298. }
  27299. else {
  27300. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  27301. }
  27302. if (this._reusable) {
  27303. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  27304. }
  27305. };
  27306. Object.defineProperty(PostProcess.prototype, "isSupported", {
  27307. get: function () {
  27308. return this._effect.isSupported;
  27309. },
  27310. enumerable: true,
  27311. configurable: true
  27312. });
  27313. PostProcess.prototype.apply = function () {
  27314. // Check
  27315. if (!this._effect.isReady())
  27316. return null;
  27317. // States
  27318. this._engine.enableEffect(this._effect);
  27319. this._engine.setState(false);
  27320. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27321. this._engine.setDepthBuffer(false);
  27322. this._engine.setDepthWrite(false);
  27323. // Texture
  27324. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  27325. // Parameters
  27326. this._effect.setVector2("scale", this._scaleRatio);
  27327. this.onApplyObservable.notifyObservers(this._effect);
  27328. return this._effect;
  27329. };
  27330. PostProcess.prototype.dispose = function (camera) {
  27331. camera = camera || this._camera;
  27332. if (this._textures.length > 0) {
  27333. for (var i = 0; i < this._textures.length; i++) {
  27334. this._engine._releaseTexture(this._textures.data[i]);
  27335. }
  27336. this._textures.reset();
  27337. }
  27338. if (!camera) {
  27339. return;
  27340. }
  27341. camera.detachPostProcess(this);
  27342. var index = camera._postProcesses.indexOf(this);
  27343. if (index === 0 && camera._postProcesses.length > 0) {
  27344. this._camera._postProcesses[0].markTextureDirty();
  27345. }
  27346. this.onActivateObservable.clear();
  27347. this.onAfterRenderObservable.clear();
  27348. this.onApplyObservable.clear();
  27349. this.onBeforeRenderObservable.clear();
  27350. this.onSizeChangedObservable.clear();
  27351. };
  27352. return PostProcess;
  27353. })();
  27354. BABYLON.PostProcess = PostProcess;
  27355. })(BABYLON || (BABYLON = {}));
  27356. var BABYLON;
  27357. (function (BABYLON) {
  27358. var PostProcessManager = (function () {
  27359. function PostProcessManager(scene) {
  27360. this._vertexDeclaration = [2];
  27361. this._vertexStrideSize = 2 * 4;
  27362. this._scene = scene;
  27363. }
  27364. PostProcessManager.prototype._prepareBuffers = function () {
  27365. if (this._vertexBuffer) {
  27366. return;
  27367. }
  27368. // VBO
  27369. var vertices = [];
  27370. vertices.push(1, 1);
  27371. vertices.push(-1, 1);
  27372. vertices.push(-1, -1);
  27373. vertices.push(1, -1);
  27374. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  27375. // Indices
  27376. var indices = [];
  27377. indices.push(0);
  27378. indices.push(1);
  27379. indices.push(2);
  27380. indices.push(0);
  27381. indices.push(2);
  27382. indices.push(3);
  27383. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27384. };
  27385. // Methods
  27386. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27387. var postProcesses = this._scene.activeCamera._postProcesses;
  27388. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27389. return false;
  27390. }
  27391. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27392. return true;
  27393. };
  27394. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  27395. var engine = this._scene.getEngine();
  27396. for (var index = 0; index < postProcesses.length; index++) {
  27397. if (index < postProcesses.length - 1) {
  27398. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27399. }
  27400. else {
  27401. if (targetTexture) {
  27402. engine.bindFramebuffer(targetTexture);
  27403. }
  27404. else {
  27405. engine.restoreDefaultFramebuffer();
  27406. }
  27407. }
  27408. var pp = postProcesses[index];
  27409. var effect = pp.apply();
  27410. if (effect) {
  27411. pp.onBeforeRenderObservable.notifyObservers(effect);
  27412. // VBOs
  27413. this._prepareBuffers();
  27414. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  27415. // Draw order
  27416. engine.draw(true, 0, 6);
  27417. pp.onAfterRenderObservable.notifyObservers(effect);
  27418. }
  27419. }
  27420. // Restore depth buffer
  27421. engine.setDepthBuffer(true);
  27422. engine.setDepthWrite(true);
  27423. };
  27424. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27425. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27426. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27427. return;
  27428. }
  27429. var engine = this._scene.getEngine();
  27430. for (var index = 0, len = postProcesses.length; index < len; index++) {
  27431. if (index < len - 1) {
  27432. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27433. }
  27434. else {
  27435. if (targetTexture) {
  27436. engine.bindFramebuffer(targetTexture, faceIndex);
  27437. }
  27438. else {
  27439. engine.restoreDefaultFramebuffer();
  27440. }
  27441. }
  27442. if (doNotPresent) {
  27443. break;
  27444. }
  27445. var pp = postProcesses[index];
  27446. var effect = pp.apply();
  27447. if (effect) {
  27448. pp.onBeforeRenderObservable.notifyObservers(effect);
  27449. // VBOs
  27450. this._prepareBuffers();
  27451. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  27452. // Draw order
  27453. engine.draw(true, 0, 6);
  27454. pp.onAfterRenderObservable.notifyObservers(effect);
  27455. }
  27456. }
  27457. // Restore depth buffer
  27458. engine.setDepthBuffer(true);
  27459. engine.setDepthWrite(true);
  27460. };
  27461. PostProcessManager.prototype.dispose = function () {
  27462. if (this._vertexBuffer) {
  27463. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  27464. this._vertexBuffer = null;
  27465. }
  27466. if (this._indexBuffer) {
  27467. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27468. this._indexBuffer = null;
  27469. }
  27470. };
  27471. return PostProcessManager;
  27472. })();
  27473. BABYLON.PostProcessManager = PostProcessManager;
  27474. })(BABYLON || (BABYLON = {}));
  27475. var BABYLON;
  27476. (function (BABYLON) {
  27477. var PassPostProcess = (function (_super) {
  27478. __extends(PassPostProcess, _super);
  27479. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27480. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  27481. }
  27482. return PassPostProcess;
  27483. })(BABYLON.PostProcess);
  27484. BABYLON.PassPostProcess = PassPostProcess;
  27485. })(BABYLON || (BABYLON = {}));
  27486. var BABYLON;
  27487. (function (BABYLON) {
  27488. /**
  27489. * This is a holder class for the physics joint created by the physics plugin.
  27490. * It holds a set of functions to control the underlying joint.
  27491. */
  27492. var PhysicsJoint = (function () {
  27493. function PhysicsJoint(type, jointData) {
  27494. this.type = type;
  27495. this.jointData = jointData;
  27496. jointData.nativeParams = jointData.nativeParams || {};
  27497. }
  27498. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  27499. get: function () {
  27500. return this._physicsJoint;
  27501. },
  27502. set: function (newJoint) {
  27503. if (this._physicsJoint) {
  27504. }
  27505. this._physicsJoint = newJoint;
  27506. },
  27507. enumerable: true,
  27508. configurable: true
  27509. });
  27510. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  27511. set: function (physicsPlugin) {
  27512. this._physicsPlugin = physicsPlugin;
  27513. },
  27514. enumerable: true,
  27515. configurable: true
  27516. });
  27517. /**
  27518. * Execute a function that is physics-plugin specific.
  27519. * @param {Function} func the function that will be executed.
  27520. * It accepts two parameters: the physics world and the physics joint.
  27521. */
  27522. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  27523. func(this._physicsPlugin.world, this._physicsJoint);
  27524. };
  27525. //TODO check if the native joints are the same
  27526. //Joint Types
  27527. PhysicsJoint.DistanceJoint = 0;
  27528. PhysicsJoint.HingeJoint = 1;
  27529. PhysicsJoint.BallAndSocketJoint = 2;
  27530. PhysicsJoint.WheelJoint = 3;
  27531. PhysicsJoint.SliderJoint = 4;
  27532. //OIMO
  27533. PhysicsJoint.PrismaticJoint = 5;
  27534. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  27535. PhysicsJoint.UniversalJoint = 6;
  27536. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  27537. //Cannon
  27538. //Similar to a Ball-Joint. Different in params
  27539. PhysicsJoint.PointToPointJoint = 8;
  27540. //Cannon only at the moment
  27541. PhysicsJoint.SpringJoint = 9;
  27542. return PhysicsJoint;
  27543. })();
  27544. BABYLON.PhysicsJoint = PhysicsJoint;
  27545. /**
  27546. * A class representing a physics distance joint.
  27547. */
  27548. var DistanceJoint = (function (_super) {
  27549. __extends(DistanceJoint, _super);
  27550. function DistanceJoint(jointData) {
  27551. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  27552. }
  27553. /**
  27554. * Update the predefined distance.
  27555. */
  27556. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  27557. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  27558. };
  27559. return DistanceJoint;
  27560. })(PhysicsJoint);
  27561. BABYLON.DistanceJoint = DistanceJoint;
  27562. var MotorEnabledJoint = (function (_super) {
  27563. __extends(MotorEnabledJoint, _super);
  27564. function MotorEnabledJoint(type, jointData) {
  27565. _super.call(this, type, jointData);
  27566. }
  27567. /**
  27568. * Set the motor values.
  27569. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27570. * @param {number} force the force to apply
  27571. * @param {number} maxForce max force for this motor.
  27572. */
  27573. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  27574. this._physicsPlugin.setMotor(this, force, maxForce);
  27575. };
  27576. /**
  27577. * Set the motor's limits.
  27578. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27579. */
  27580. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27581. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27582. };
  27583. return MotorEnabledJoint;
  27584. })(PhysicsJoint);
  27585. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  27586. /**
  27587. * This class represents a single hinge physics joint
  27588. */
  27589. var HingeJoint = (function (_super) {
  27590. __extends(HingeJoint, _super);
  27591. function HingeJoint(jointData) {
  27592. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  27593. }
  27594. /**
  27595. * Set the motor values.
  27596. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27597. * @param {number} force the force to apply
  27598. * @param {number} maxForce max force for this motor.
  27599. */
  27600. HingeJoint.prototype.setMotor = function (force, maxForce) {
  27601. this._physicsPlugin.setMotor(this, force, maxForce);
  27602. };
  27603. /**
  27604. * Set the motor's limits.
  27605. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27606. */
  27607. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27608. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27609. };
  27610. return HingeJoint;
  27611. })(MotorEnabledJoint);
  27612. BABYLON.HingeJoint = HingeJoint;
  27613. /**
  27614. * This class represents a dual hinge physics joint (same as wheel joint)
  27615. */
  27616. var Hinge2Joint = (function (_super) {
  27617. __extends(Hinge2Joint, _super);
  27618. function Hinge2Joint(jointData) {
  27619. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  27620. }
  27621. /**
  27622. * Set the motor values.
  27623. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27624. * @param {number} force the force to apply
  27625. * @param {number} maxForce max force for this motor.
  27626. * @param {motorIndex} the motor's index, 0 or 1.
  27627. */
  27628. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  27629. if (motorIndex === void 0) { motorIndex = 0; }
  27630. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  27631. };
  27632. /**
  27633. * Set the motor limits.
  27634. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27635. * @param {number} upperLimit the upper limit
  27636. * @param {number} lowerLimit lower limit
  27637. * @param {motorIndex} the motor's index, 0 or 1.
  27638. */
  27639. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  27640. if (motorIndex === void 0) { motorIndex = 0; }
  27641. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  27642. };
  27643. return Hinge2Joint;
  27644. })(MotorEnabledJoint);
  27645. BABYLON.Hinge2Joint = Hinge2Joint;
  27646. })(BABYLON || (BABYLON = {}));
  27647. var BABYLON;
  27648. (function (BABYLON) {
  27649. var PhysicsImpostor = (function () {
  27650. function PhysicsImpostor(object, type, _options, _scene) {
  27651. var _this = this;
  27652. if (_options === void 0) { _options = { mass: 0 }; }
  27653. this.object = object;
  27654. this.type = type;
  27655. this._options = _options;
  27656. this._scene = _scene;
  27657. this._bodyUpdateRequired = false;
  27658. this._onBeforePhysicsStepCallbacks = new Array();
  27659. this._onAfterPhysicsStepCallbacks = new Array();
  27660. this._onPhysicsCollideCallbacks = [];
  27661. this._deltaPosition = BABYLON.Vector3.Zero();
  27662. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  27663. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  27664. /**
  27665. * this function is executed by the physics engine.
  27666. */
  27667. this.beforeStep = function () {
  27668. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  27669. //conjugate deltaRotation
  27670. if (_this._deltaRotationConjugated) {
  27671. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  27672. }
  27673. else {
  27674. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  27675. }
  27676. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  27677. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  27678. func(_this);
  27679. });
  27680. };
  27681. /**
  27682. * this function is executed by the physics engine.
  27683. */
  27684. this.afterStep = function () {
  27685. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  27686. func(_this);
  27687. });
  27688. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  27689. _this.object.position.addInPlace(_this._deltaPosition);
  27690. if (_this._deltaRotation) {
  27691. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  27692. }
  27693. };
  27694. //event and body object due to cannon's event-based architecture.
  27695. this.onCollide = function (e) {
  27696. if (!_this._onPhysicsCollideCallbacks.length)
  27697. return;
  27698. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  27699. if (otherImpostor) {
  27700. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  27701. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  27702. }).forEach(function (obj) {
  27703. obj.callback(_this, otherImpostor);
  27704. });
  27705. }
  27706. };
  27707. //sanity check!
  27708. if (!this.object) {
  27709. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  27710. return;
  27711. }
  27712. //legacy support for old syntax.
  27713. if (!this._scene && object.getScene) {
  27714. this._scene = object.getScene();
  27715. }
  27716. this._physicsEngine = this._scene.getPhysicsEngine();
  27717. if (!this._physicsEngine) {
  27718. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  27719. }
  27720. else {
  27721. //set the object's quaternion, if not set
  27722. if (!this.object.rotationQuaternion) {
  27723. if (this.object.rotation) {
  27724. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  27725. }
  27726. else {
  27727. this.object.rotationQuaternion = new BABYLON.Quaternion();
  27728. }
  27729. }
  27730. //default options params
  27731. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  27732. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  27733. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  27734. this._joints = [];
  27735. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  27736. if (!this.object.parent) {
  27737. this._init();
  27738. }
  27739. }
  27740. }
  27741. /**
  27742. * This function will completly initialize this impostor.
  27743. * It will create a new body - but only if this mesh has no parent.
  27744. * If it has, this impostor will not be used other than to define the impostor
  27745. * of the child mesh.
  27746. */
  27747. PhysicsImpostor.prototype._init = function () {
  27748. this._physicsEngine.removeImpostor(this);
  27749. this.physicsBody = null;
  27750. this._parent = this._parent || this._getPhysicsParent();
  27751. if (!this.parent) {
  27752. this._physicsEngine.addImpostor(this);
  27753. }
  27754. };
  27755. PhysicsImpostor.prototype._getPhysicsParent = function () {
  27756. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  27757. var parentMesh = this.object.parent;
  27758. return parentMesh.physicsImpostor;
  27759. }
  27760. return;
  27761. };
  27762. /**
  27763. * Should a new body be generated.
  27764. */
  27765. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  27766. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  27767. };
  27768. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  27769. this.forceUpdate();
  27770. };
  27771. /**
  27772. * Force a regeneration of this or the parent's impostor's body.
  27773. * Use under cautious - This will remove all joints already implemented.
  27774. */
  27775. PhysicsImpostor.prototype.forceUpdate = function () {
  27776. this._init();
  27777. if (this.parent) {
  27778. this.parent.forceUpdate();
  27779. }
  27780. };
  27781. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  27782. /*public get mesh(): AbstractMesh {
  27783. return this._mesh;
  27784. }*/
  27785. /**
  27786. * Gets the body that holds this impostor. Either its own, or its parent.
  27787. */
  27788. get: function () {
  27789. return this._parent ? this._parent.physicsBody : this._physicsBody;
  27790. },
  27791. /**
  27792. * Set the physics body. Used mainly by the physics engine/plugin
  27793. */
  27794. set: function (physicsBody) {
  27795. if (this._physicsBody) {
  27796. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  27797. }
  27798. this._physicsBody = physicsBody;
  27799. this.resetUpdateFlags();
  27800. },
  27801. enumerable: true,
  27802. configurable: true
  27803. });
  27804. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  27805. get: function () {
  27806. return this._parent;
  27807. },
  27808. enumerable: true,
  27809. configurable: true
  27810. });
  27811. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  27812. this._bodyUpdateRequired = false;
  27813. };
  27814. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  27815. if (this.object.getBoundingInfo) {
  27816. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  27817. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  27818. }
  27819. else {
  27820. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  27821. }
  27822. };
  27823. PhysicsImpostor.prototype.getObjectCenter = function () {
  27824. if (this.object.getBoundingInfo) {
  27825. return this.object.getBoundingInfo().boundingBox.center;
  27826. }
  27827. else {
  27828. return this.object.position;
  27829. }
  27830. };
  27831. /**
  27832. * Get a specific parametes from the options parameter.
  27833. */
  27834. PhysicsImpostor.prototype.getParam = function (paramName) {
  27835. return this._options[paramName];
  27836. };
  27837. /**
  27838. * Sets a specific parameter in the options given to the physics plugin
  27839. */
  27840. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27841. this._options[paramName] = value;
  27842. this._bodyUpdateRequired = true;
  27843. };
  27844. /**
  27845. * Specifically change the body's mass option. Won't recreate the physics body object
  27846. */
  27847. PhysicsImpostor.prototype.setMass = function (mass) {
  27848. if (this.getParam("mass") !== mass) {
  27849. this.setParam("mass", mass);
  27850. }
  27851. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27852. };
  27853. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27854. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27855. };
  27856. /**
  27857. * Set the body's linear velocity.
  27858. */
  27859. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27860. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27861. };
  27862. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27863. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27864. };
  27865. /**
  27866. * Set the body's linear velocity.
  27867. */
  27868. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27869. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27870. };
  27871. /**
  27872. * Execute a function with the physics plugin native code.
  27873. * Provide a function the will have two variables - the world object and the physics body object.
  27874. */
  27875. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27876. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27877. };
  27878. /**
  27879. * Register a function that will be executed before the physics world is stepping forward.
  27880. */
  27881. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27882. this._onBeforePhysicsStepCallbacks.push(func);
  27883. };
  27884. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27885. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27886. if (index > -1) {
  27887. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27888. }
  27889. else {
  27890. BABYLON.Tools.Warn("Function to remove was not found");
  27891. }
  27892. };
  27893. /**
  27894. * Register a function that will be executed after the physics step
  27895. */
  27896. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27897. this._onAfterPhysicsStepCallbacks.push(func);
  27898. };
  27899. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27900. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27901. if (index > -1) {
  27902. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27903. }
  27904. else {
  27905. BABYLON.Tools.Warn("Function to remove was not found");
  27906. }
  27907. };
  27908. /**
  27909. * register a function that will be executed when this impostor collides against a different body.
  27910. */
  27911. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27912. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27913. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27914. };
  27915. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27916. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27917. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27918. if (index > -1) {
  27919. this._onPhysicsCollideCallbacks.splice(index, 1);
  27920. }
  27921. else {
  27922. BABYLON.Tools.Warn("Function to remove was not found");
  27923. }
  27924. };
  27925. /**
  27926. * Apply a force
  27927. */
  27928. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27929. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27930. };
  27931. /**
  27932. * Apply an impulse
  27933. */
  27934. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27935. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27936. };
  27937. /**
  27938. * A help function to create a joint.
  27939. */
  27940. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27941. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27942. this.addJoint(otherImpostor, joint);
  27943. };
  27944. /**
  27945. * Add a joint to this impostor with a different impostor.
  27946. */
  27947. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27948. this._joints.push({
  27949. otherImpostor: otherImpostor,
  27950. joint: joint
  27951. });
  27952. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27953. };
  27954. /**
  27955. * Will keep this body still, in a sleep mode.
  27956. */
  27957. PhysicsImpostor.prototype.sleep = function () {
  27958. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27959. };
  27960. /**
  27961. * Wake the body up.
  27962. */
  27963. PhysicsImpostor.prototype.wakeUp = function () {
  27964. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27965. };
  27966. PhysicsImpostor.prototype.clone = function (newObject) {
  27967. if (!newObject)
  27968. return null;
  27969. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27970. };
  27971. PhysicsImpostor.prototype.dispose = function () {
  27972. var _this = this;
  27973. //no dispose if no physics engine is available.
  27974. if (!this._physicsEngine) {
  27975. return;
  27976. }
  27977. this._joints.forEach(function (j) {
  27978. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  27979. });
  27980. //dispose the physics body
  27981. this._physicsEngine.removeImpostor(this);
  27982. if (this.parent) {
  27983. this.parent.forceUpdate();
  27984. }
  27985. else {
  27986. }
  27987. };
  27988. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27989. this._deltaPosition.copyFrom(position);
  27990. };
  27991. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27992. if (!this._deltaRotation) {
  27993. this._deltaRotation = new BABYLON.Quaternion();
  27994. }
  27995. this._deltaRotation.copyFrom(rotation);
  27996. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27997. };
  27998. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27999. //Impostor types
  28000. PhysicsImpostor.NoImpostor = 0;
  28001. PhysicsImpostor.SphereImpostor = 1;
  28002. PhysicsImpostor.BoxImpostor = 2;
  28003. PhysicsImpostor.PlaneImpostor = 3;
  28004. PhysicsImpostor.MeshImpostor = 4;
  28005. PhysicsImpostor.CylinderImpostor = 7;
  28006. PhysicsImpostor.ParticleImpostor = 8;
  28007. PhysicsImpostor.HeightmapImpostor = 9;
  28008. return PhysicsImpostor;
  28009. })();
  28010. BABYLON.PhysicsImpostor = PhysicsImpostor;
  28011. })(BABYLON || (BABYLON = {}));
  28012. var BABYLON;
  28013. (function (BABYLON) {
  28014. var PhysicsEngine = (function () {
  28015. function PhysicsEngine(gravity, _physicsPlugin) {
  28016. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  28017. this._physicsPlugin = _physicsPlugin;
  28018. //new methods and parameters
  28019. this._impostors = [];
  28020. this._joints = [];
  28021. if (!this._physicsPlugin.isSupported()) {
  28022. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  28023. + "Please make sure it is included.");
  28024. }
  28025. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  28026. this.setGravity(gravity);
  28027. this.setTimeStep();
  28028. }
  28029. PhysicsEngine.prototype.setGravity = function (gravity) {
  28030. this.gravity = gravity;
  28031. this._physicsPlugin.setGravity(this.gravity);
  28032. };
  28033. /**
  28034. * Set the time step of the physics engine.
  28035. * default is 1/60.
  28036. * To slow it down, enter 1/600 for example.
  28037. * To speed it up, 1/30
  28038. * @param {number} newTimeStep the new timestep to apply to this world.
  28039. */
  28040. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  28041. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  28042. this._physicsPlugin.setTimeStep(newTimeStep);
  28043. };
  28044. PhysicsEngine.prototype.dispose = function () {
  28045. this._impostors.forEach(function (impostor) {
  28046. impostor.dispose();
  28047. });
  28048. this._physicsPlugin.dispose();
  28049. };
  28050. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  28051. return this._physicsPlugin.name;
  28052. };
  28053. /**
  28054. * Adding a new impostor for the impostor tracking.
  28055. * This will be done by the impostor itself.
  28056. * @param {PhysicsImpostor} impostor the impostor to add
  28057. */
  28058. PhysicsEngine.prototype.addImpostor = function (impostor) {
  28059. impostor.uniqueId = this._impostors.push(impostor);
  28060. //if no parent, generate the body
  28061. if (!impostor.parent) {
  28062. this._physicsPlugin.generatePhysicsBody(impostor);
  28063. }
  28064. };
  28065. /**
  28066. * Remove an impostor from the engine.
  28067. * This impostor and its mesh will not longer be updated by the physics engine.
  28068. * @param {PhysicsImpostor} impostor the impostor to remove
  28069. */
  28070. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  28071. var index = this._impostors.indexOf(impostor);
  28072. if (index > -1) {
  28073. var removed = this._impostors.splice(index, 1);
  28074. //Is it needed?
  28075. if (removed.length) {
  28076. //this will also remove it from the world.
  28077. removed[0].physicsBody = null;
  28078. }
  28079. }
  28080. };
  28081. /**
  28082. * Add a joint to the physics engine
  28083. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  28084. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  28085. * @param {PhysicsJoint} the joint that will connect both impostors.
  28086. */
  28087. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  28088. var impostorJoint = {
  28089. mainImpostor: mainImpostor,
  28090. connectedImpostor: connectedImpostor,
  28091. joint: joint
  28092. };
  28093. joint.physicsPlugin = this._physicsPlugin;
  28094. this._joints.push(impostorJoint);
  28095. this._physicsPlugin.generateJoint(impostorJoint);
  28096. };
  28097. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  28098. var matchingJoints = this._joints.filter(function (impostorJoint) {
  28099. return (impostorJoint.connectedImpostor === connectedImpostor
  28100. && impostorJoint.joint === joint
  28101. && impostorJoint.mainImpostor === mainImpostor);
  28102. });
  28103. if (matchingJoints.length) {
  28104. this._physicsPlugin.removeJoint(matchingJoints[0]);
  28105. }
  28106. };
  28107. /**
  28108. * Called by the scene. no need to call it.
  28109. */
  28110. PhysicsEngine.prototype._step = function (delta) {
  28111. var _this = this;
  28112. //check if any mesh has no body / requires an update
  28113. this._impostors.forEach(function (impostor) {
  28114. if (impostor.isBodyInitRequired()) {
  28115. _this._physicsPlugin.generatePhysicsBody(impostor);
  28116. }
  28117. });
  28118. if (delta > 0.1) {
  28119. delta = 0.1;
  28120. }
  28121. else if (delta <= 0) {
  28122. delta = 1.0 / 60.0;
  28123. }
  28124. this._physicsPlugin.executeStep(delta, this._impostors);
  28125. };
  28126. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  28127. return this._physicsPlugin;
  28128. };
  28129. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  28130. for (var i = 0; i < this._impostors.length; ++i) {
  28131. if (this._impostors[i].object === object) {
  28132. return this._impostors[i];
  28133. }
  28134. }
  28135. };
  28136. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  28137. for (var i = 0; i < this._impostors.length; ++i) {
  28138. if (this._impostors[i].physicsBody === body) {
  28139. return this._impostors[i];
  28140. }
  28141. }
  28142. };
  28143. // Statics, Legacy support.
  28144. /**
  28145. * @Deprecated
  28146. *
  28147. */
  28148. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  28149. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  28150. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  28151. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  28152. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  28153. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  28154. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  28155. PhysicsEngine.CapsuleImpostor = -1;
  28156. PhysicsEngine.ConeImpostor = -1;
  28157. PhysicsEngine.ConvexHullImpostor = -1;
  28158. PhysicsEngine.Epsilon = 0.001;
  28159. return PhysicsEngine;
  28160. })();
  28161. BABYLON.PhysicsEngine = PhysicsEngine;
  28162. })(BABYLON || (BABYLON = {}));
  28163. var BABYLON;
  28164. (function (BABYLON) {
  28165. var VertexData = (function () {
  28166. function VertexData() {
  28167. }
  28168. VertexData.prototype.set = function (data, kind) {
  28169. switch (kind) {
  28170. case BABYLON.VertexBuffer.PositionKind:
  28171. this.positions = data;
  28172. break;
  28173. case BABYLON.VertexBuffer.NormalKind:
  28174. this.normals = data;
  28175. break;
  28176. case BABYLON.VertexBuffer.UVKind:
  28177. this.uvs = data;
  28178. break;
  28179. case BABYLON.VertexBuffer.UV2Kind:
  28180. this.uvs2 = data;
  28181. break;
  28182. case BABYLON.VertexBuffer.UV3Kind:
  28183. this.uvs3 = data;
  28184. break;
  28185. case BABYLON.VertexBuffer.UV4Kind:
  28186. this.uvs4 = data;
  28187. break;
  28188. case BABYLON.VertexBuffer.UV5Kind:
  28189. this.uvs5 = data;
  28190. break;
  28191. case BABYLON.VertexBuffer.UV6Kind:
  28192. this.uvs6 = data;
  28193. break;
  28194. case BABYLON.VertexBuffer.ColorKind:
  28195. this.colors = data;
  28196. break;
  28197. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28198. this.matricesIndices = data;
  28199. break;
  28200. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28201. this.matricesWeights = data;
  28202. break;
  28203. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28204. this.matricesIndicesExtra = data;
  28205. break;
  28206. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28207. this.matricesWeightsExtra = data;
  28208. break;
  28209. }
  28210. };
  28211. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28212. this._applyTo(mesh, updatable);
  28213. };
  28214. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28215. this._applyTo(geometry, updatable);
  28216. };
  28217. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28218. this._update(mesh);
  28219. };
  28220. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28221. this._update(geometry);
  28222. };
  28223. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28224. if (this.positions) {
  28225. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28226. }
  28227. if (this.normals) {
  28228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28229. }
  28230. if (this.uvs) {
  28231. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28232. }
  28233. if (this.uvs2) {
  28234. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28235. }
  28236. if (this.uvs3) {
  28237. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28238. }
  28239. if (this.uvs4) {
  28240. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28241. }
  28242. if (this.uvs5) {
  28243. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28244. }
  28245. if (this.uvs6) {
  28246. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28247. }
  28248. if (this.colors) {
  28249. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28250. }
  28251. if (this.matricesIndices) {
  28252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28253. }
  28254. if (this.matricesWeights) {
  28255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28256. }
  28257. if (this.matricesIndicesExtra) {
  28258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28259. }
  28260. if (this.matricesWeightsExtra) {
  28261. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28262. }
  28263. if (this.indices) {
  28264. meshOrGeometry.setIndices(this.indices);
  28265. }
  28266. };
  28267. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28268. if (this.positions) {
  28269. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28270. }
  28271. if (this.normals) {
  28272. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28273. }
  28274. if (this.uvs) {
  28275. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28276. }
  28277. if (this.uvs2) {
  28278. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28279. }
  28280. if (this.uvs3) {
  28281. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28282. }
  28283. if (this.uvs4) {
  28284. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28285. }
  28286. if (this.uvs5) {
  28287. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28288. }
  28289. if (this.uvs6) {
  28290. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28291. }
  28292. if (this.colors) {
  28293. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28294. }
  28295. if (this.matricesIndices) {
  28296. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28297. }
  28298. if (this.matricesWeights) {
  28299. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28300. }
  28301. if (this.matricesIndicesExtra) {
  28302. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28303. }
  28304. if (this.matricesWeightsExtra) {
  28305. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28306. }
  28307. if (this.indices) {
  28308. meshOrGeometry.setIndices(this.indices);
  28309. }
  28310. };
  28311. VertexData.prototype.transform = function (matrix) {
  28312. var transformed = BABYLON.Vector3.Zero();
  28313. var index;
  28314. if (this.positions) {
  28315. var position = BABYLON.Vector3.Zero();
  28316. for (index = 0; index < this.positions.length; index += 3) {
  28317. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28318. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28319. this.positions[index] = transformed.x;
  28320. this.positions[index + 1] = transformed.y;
  28321. this.positions[index + 2] = transformed.z;
  28322. }
  28323. }
  28324. if (this.normals) {
  28325. var normal = BABYLON.Vector3.Zero();
  28326. for (index = 0; index < this.normals.length; index += 3) {
  28327. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28328. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28329. this.normals[index] = transformed.x;
  28330. this.normals[index + 1] = transformed.y;
  28331. this.normals[index + 2] = transformed.z;
  28332. }
  28333. }
  28334. };
  28335. VertexData.prototype.merge = function (other) {
  28336. if (other.indices) {
  28337. if (!this.indices) {
  28338. this.indices = [];
  28339. }
  28340. var offset = this.positions ? this.positions.length / 3 : 0;
  28341. for (var index = 0; index < other.indices.length; index++) {
  28342. //TODO check type - if Int32Array!
  28343. this.indices.push(other.indices[index] + offset);
  28344. }
  28345. }
  28346. this.positions = this._mergeElement(this.positions, other.positions);
  28347. this.normals = this._mergeElement(this.normals, other.normals);
  28348. this.uvs = this._mergeElement(this.uvs, other.uvs);
  28349. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  28350. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  28351. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  28352. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  28353. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  28354. this.colors = this._mergeElement(this.colors, other.colors);
  28355. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  28356. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  28357. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  28358. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  28359. };
  28360. VertexData.prototype._mergeElement = function (source, other) {
  28361. if (!other)
  28362. return source;
  28363. if (!source)
  28364. return other;
  28365. var len = other.length + source.length;
  28366. var isSrcTypedArray = source instanceof Float32Array;
  28367. var isOthTypedArray = other instanceof Float32Array;
  28368. // use non-loop method when the source is Float32Array
  28369. if (isSrcTypedArray) {
  28370. var ret32 = new Float32Array(len);
  28371. ret32.set(source);
  28372. ret32.set(other, source.length);
  28373. return ret32;
  28374. }
  28375. else if (!isOthTypedArray) {
  28376. return source.concat(other);
  28377. }
  28378. else {
  28379. var ret = source.slice(0); // copy source to a separate array
  28380. for (var i = 0, len = other.length; i < len; i++) {
  28381. ret.push(other[i]);
  28382. }
  28383. return ret;
  28384. }
  28385. };
  28386. VertexData.prototype.serialize = function () {
  28387. var serializationObject = this.serialize();
  28388. if (this.positions) {
  28389. serializationObject.positions = this.positions;
  28390. }
  28391. if (this.normals) {
  28392. serializationObject.normals = this.normals;
  28393. }
  28394. if (this.uvs) {
  28395. serializationObject.uvs = this.uvs;
  28396. }
  28397. if (this.uvs2) {
  28398. serializationObject.uvs2 = this.uvs2;
  28399. }
  28400. if (this.uvs3) {
  28401. serializationObject.uvs3 = this.uvs3;
  28402. }
  28403. if (this.uvs4) {
  28404. serializationObject.uvs4 = this.uvs4;
  28405. }
  28406. if (this.uvs5) {
  28407. serializationObject.uvs5 = this.uvs5;
  28408. }
  28409. if (this.uvs6) {
  28410. serializationObject.uvs6 = this.uvs6;
  28411. }
  28412. if (this.colors) {
  28413. serializationObject.colors = this.colors;
  28414. }
  28415. if (this.matricesIndices) {
  28416. serializationObject.matricesIndices = this.matricesIndices;
  28417. serializationObject.matricesIndices._isExpanded = true;
  28418. }
  28419. if (this.matricesWeights) {
  28420. serializationObject.matricesWeights = this.matricesWeights;
  28421. }
  28422. if (this.matricesIndicesExtra) {
  28423. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28424. serializationObject.matricesIndicesExtra._isExpanded = true;
  28425. }
  28426. if (this.matricesWeightsExtra) {
  28427. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28428. }
  28429. serializationObject.indices = this.indices;
  28430. return serializationObject;
  28431. };
  28432. // Statics
  28433. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  28434. return VertexData._ExtractFrom(mesh, copyWhenShared);
  28435. };
  28436. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  28437. return VertexData._ExtractFrom(geometry, copyWhenShared);
  28438. };
  28439. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  28440. var result = new VertexData();
  28441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28442. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  28443. }
  28444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28445. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  28446. }
  28447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28448. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  28449. }
  28450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28451. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  28452. }
  28453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28454. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  28455. }
  28456. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28457. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  28458. }
  28459. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28460. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  28461. }
  28462. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28463. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  28464. }
  28465. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28466. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  28467. }
  28468. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28469. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  28470. }
  28471. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28472. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  28473. }
  28474. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28475. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  28476. }
  28477. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28478. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  28479. }
  28480. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28481. return result;
  28482. };
  28483. VertexData.CreateRibbon = function (options) {
  28484. var pathArray = options.pathArray;
  28485. var closeArray = options.closeArray || false;
  28486. var closePath = options.closePath || false;
  28487. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28488. var offset = options.offset || defaultOffset;
  28489. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28490. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28491. var positions = [];
  28492. var indices = [];
  28493. var normals = [];
  28494. var uvs = [];
  28495. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28496. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28497. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28498. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28499. var minlg; // minimal length among all paths from pathArray
  28500. var lg = []; // array of path lengths : nb of vertex per path
  28501. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28502. var p; // path iterator
  28503. var i; // point iterator
  28504. var j; // point iterator
  28505. // if single path in pathArray
  28506. if (pathArray.length < 2) {
  28507. var ar1 = [];
  28508. var ar2 = [];
  28509. for (i = 0; i < pathArray[0].length - offset; i++) {
  28510. ar1.push(pathArray[0][i]);
  28511. ar2.push(pathArray[0][i + offset]);
  28512. }
  28513. pathArray = [ar1, ar2];
  28514. }
  28515. // positions and horizontal distances (u)
  28516. var idc = 0;
  28517. var closePathCorr = (closePath) ? 1 : 0;
  28518. var path;
  28519. var l;
  28520. minlg = pathArray[0].length;
  28521. var vectlg;
  28522. var dist;
  28523. for (p = 0; p < pathArray.length; p++) {
  28524. uTotalDistance[p] = 0;
  28525. us[p] = [0];
  28526. path = pathArray[p];
  28527. l = path.length;
  28528. minlg = (minlg < l) ? minlg : l;
  28529. j = 0;
  28530. while (j < l) {
  28531. positions.push(path[j].x, path[j].y, path[j].z);
  28532. if (j > 0) {
  28533. vectlg = path[j].subtract(path[j - 1]).length();
  28534. dist = vectlg + uTotalDistance[p];
  28535. us[p].push(dist);
  28536. uTotalDistance[p] = dist;
  28537. }
  28538. j++;
  28539. }
  28540. if (closePath) {
  28541. j--;
  28542. positions.push(path[0].x, path[0].y, path[0].z);
  28543. vectlg = path[j].subtract(path[0]).length();
  28544. dist = vectlg + uTotalDistance[p];
  28545. us[p].push(dist);
  28546. uTotalDistance[p] = dist;
  28547. }
  28548. lg[p] = l + closePathCorr;
  28549. idx[p] = idc;
  28550. idc += (l + closePathCorr);
  28551. }
  28552. // vertical distances (v)
  28553. var path1;
  28554. var path2;
  28555. var vertex1;
  28556. var vertex2;
  28557. for (i = 0; i < minlg + closePathCorr; i++) {
  28558. vTotalDistance[i] = 0;
  28559. vs[i] = [0];
  28560. for (p = 0; p < pathArray.length - 1; p++) {
  28561. path1 = pathArray[p];
  28562. path2 = pathArray[p + 1];
  28563. if (i === minlg) {
  28564. vertex1 = path1[0];
  28565. vertex2 = path2[0];
  28566. }
  28567. else {
  28568. vertex1 = path1[i];
  28569. vertex2 = path2[i];
  28570. }
  28571. vectlg = vertex2.subtract(vertex1).length();
  28572. dist = vectlg + vTotalDistance[i];
  28573. vs[i].push(dist);
  28574. vTotalDistance[i] = dist;
  28575. }
  28576. if (closeArray) {
  28577. path1 = pathArray[p];
  28578. path2 = pathArray[0];
  28579. if (i === minlg) {
  28580. vertex2 = path2[0];
  28581. }
  28582. vectlg = vertex2.subtract(vertex1).length();
  28583. dist = vectlg + vTotalDistance[i];
  28584. vTotalDistance[i] = dist;
  28585. }
  28586. }
  28587. // uvs
  28588. var u;
  28589. var v;
  28590. for (p = 0; p < pathArray.length; p++) {
  28591. for (i = 0; i < minlg + closePathCorr; i++) {
  28592. u = us[p][i] / uTotalDistance[p];
  28593. v = vs[i][p] / vTotalDistance[i];
  28594. uvs.push(u, v);
  28595. }
  28596. }
  28597. // indices
  28598. p = 0; // path index
  28599. var pi = 0; // positions array index
  28600. var l1 = lg[p] - 1; // path1 length
  28601. var l2 = lg[p + 1] - 1; // path2 length
  28602. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28603. var shft = idx[1] - idx[0]; // shift
  28604. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28605. while (pi <= min && p < path1nb) {
  28606. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  28607. indices.push(pi, pi + shft, pi + 1);
  28608. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28609. pi += 1;
  28610. if (pi === min) {
  28611. p++;
  28612. if (p === lg.length - 1) {
  28613. shft = idx[0] - idx[p];
  28614. l1 = lg[p] - 1;
  28615. l2 = lg[0] - 1;
  28616. }
  28617. else {
  28618. shft = idx[p + 1] - idx[p];
  28619. l1 = lg[p] - 1;
  28620. l2 = lg[p + 1] - 1;
  28621. }
  28622. pi = idx[p];
  28623. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28624. }
  28625. }
  28626. // normals
  28627. VertexData.ComputeNormals(positions, indices, normals);
  28628. if (closePath) {
  28629. var indexFirst = 0;
  28630. var indexLast = 0;
  28631. for (p = 0; p < pathArray.length; p++) {
  28632. indexFirst = idx[p] * 3;
  28633. if (p + 1 < pathArray.length) {
  28634. indexLast = (idx[p + 1] - 1) * 3;
  28635. }
  28636. else {
  28637. indexLast = normals.length - 3;
  28638. }
  28639. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28640. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28641. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28642. normals[indexLast] = normals[indexFirst];
  28643. normals[indexLast + 1] = normals[indexFirst + 1];
  28644. normals[indexLast + 2] = normals[indexFirst + 2];
  28645. }
  28646. }
  28647. // sides
  28648. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28649. // Result
  28650. var vertexData = new VertexData();
  28651. vertexData.indices = indices;
  28652. vertexData.positions = positions;
  28653. vertexData.normals = normals;
  28654. vertexData.uvs = uvs;
  28655. if (closePath) {
  28656. vertexData._idx = idx;
  28657. }
  28658. return vertexData;
  28659. };
  28660. VertexData.CreateBox = function (options) {
  28661. var normalsSource = [
  28662. new BABYLON.Vector3(0, 0, 1),
  28663. new BABYLON.Vector3(0, 0, -1),
  28664. new BABYLON.Vector3(1, 0, 0),
  28665. new BABYLON.Vector3(-1, 0, 0),
  28666. new BABYLON.Vector3(0, 1, 0),
  28667. new BABYLON.Vector3(0, -1, 0)
  28668. ];
  28669. var indices = [];
  28670. var positions = [];
  28671. var normals = [];
  28672. var uvs = [];
  28673. var width = options.width || options.size || 1;
  28674. var height = options.height || options.size || 1;
  28675. var depth = options.depth || options.size || 1;
  28676. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28677. var faceUV = options.faceUV || new Array(6);
  28678. var faceColors = options.faceColors;
  28679. var colors = [];
  28680. // default face colors and UV if undefined
  28681. for (var f = 0; f < 6; f++) {
  28682. if (faceUV[f] === undefined) {
  28683. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28684. }
  28685. if (faceColors && faceColors[f] === undefined) {
  28686. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28687. }
  28688. }
  28689. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28690. // Create each face in turn.
  28691. for (var index = 0; index < normalsSource.length; index++) {
  28692. var normal = normalsSource[index];
  28693. // Get two vectors perpendicular to the face normal and to each other.
  28694. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28695. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28696. // Six indices (two triangles) per face.
  28697. var verticesLength = positions.length / 3;
  28698. indices.push(verticesLength);
  28699. indices.push(verticesLength + 1);
  28700. indices.push(verticesLength + 2);
  28701. indices.push(verticesLength);
  28702. indices.push(verticesLength + 2);
  28703. indices.push(verticesLength + 3);
  28704. // Four vertices per face.
  28705. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28706. positions.push(vertex.x, vertex.y, vertex.z);
  28707. normals.push(normal.x, normal.y, normal.z);
  28708. uvs.push(faceUV[index].z, faceUV[index].w);
  28709. if (faceColors) {
  28710. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28711. }
  28712. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28713. positions.push(vertex.x, vertex.y, vertex.z);
  28714. normals.push(normal.x, normal.y, normal.z);
  28715. uvs.push(faceUV[index].x, faceUV[index].w);
  28716. if (faceColors) {
  28717. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28718. }
  28719. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28720. positions.push(vertex.x, vertex.y, vertex.z);
  28721. normals.push(normal.x, normal.y, normal.z);
  28722. uvs.push(faceUV[index].x, faceUV[index].y);
  28723. if (faceColors) {
  28724. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28725. }
  28726. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28727. positions.push(vertex.x, vertex.y, vertex.z);
  28728. normals.push(normal.x, normal.y, normal.z);
  28729. uvs.push(faceUV[index].z, faceUV[index].y);
  28730. if (faceColors) {
  28731. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28732. }
  28733. }
  28734. // sides
  28735. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28736. // Result
  28737. var vertexData = new VertexData();
  28738. vertexData.indices = indices;
  28739. vertexData.positions = positions;
  28740. vertexData.normals = normals;
  28741. vertexData.uvs = uvs;
  28742. if (faceColors) {
  28743. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28744. vertexData.colors = totalColors;
  28745. }
  28746. return vertexData;
  28747. };
  28748. VertexData.CreateSphere = function (options) {
  28749. var segments = options.segments || 32;
  28750. var diameterX = options.diameterX || options.diameter || 1;
  28751. var diameterY = options.diameterY || options.diameter || 1;
  28752. var diameterZ = options.diameterZ || options.diameter || 1;
  28753. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28754. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28755. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28756. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28757. var totalZRotationSteps = 2 + segments;
  28758. var totalYRotationSteps = 2 * totalZRotationSteps;
  28759. var indices = [];
  28760. var positions = [];
  28761. var normals = [];
  28762. var uvs = [];
  28763. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28764. var normalizedZ = zRotationStep / totalZRotationSteps;
  28765. var angleZ = normalizedZ * Math.PI * slice;
  28766. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28767. var normalizedY = yRotationStep / totalYRotationSteps;
  28768. var angleY = normalizedY * Math.PI * 2 * arc;
  28769. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28770. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28771. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28772. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28773. var vertex = complete.multiply(radius);
  28774. var normal = complete.divide(radius).normalize();
  28775. positions.push(vertex.x, vertex.y, vertex.z);
  28776. normals.push(normal.x, normal.y, normal.z);
  28777. uvs.push(normalizedY, normalizedZ);
  28778. }
  28779. if (zRotationStep > 0) {
  28780. var verticesCount = positions.length / 3;
  28781. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28782. indices.push((firstIndex));
  28783. indices.push((firstIndex + 1));
  28784. indices.push(firstIndex + totalYRotationSteps + 1);
  28785. indices.push((firstIndex + totalYRotationSteps + 1));
  28786. indices.push((firstIndex + 1));
  28787. indices.push((firstIndex + totalYRotationSteps + 2));
  28788. }
  28789. }
  28790. }
  28791. // Sides
  28792. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28793. // Result
  28794. var vertexData = new VertexData();
  28795. vertexData.indices = indices;
  28796. vertexData.positions = positions;
  28797. vertexData.normals = normals;
  28798. vertexData.uvs = uvs;
  28799. return vertexData;
  28800. };
  28801. // Cylinder and cone
  28802. VertexData.CreateCylinder = function (options) {
  28803. var height = options.height || 2;
  28804. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28805. var diameterBottom = options.diameterBottom || options.diameter || 1;
  28806. var tessellation = options.tessellation || 24;
  28807. var subdivisions = options.subdivisions || 1;
  28808. var hasRings = options.hasRings;
  28809. var enclose = options.enclose;
  28810. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28811. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28812. var faceUV = options.faceUV || new Array(3);
  28813. var faceColors = options.faceColors;
  28814. // default face colors and UV if undefined
  28815. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28816. var ringNb = (hasRings) ? subdivisions : 1;
  28817. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28818. var f;
  28819. for (f = 0; f < surfaceNb; f++) {
  28820. if (faceColors && faceColors[f] === undefined) {
  28821. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28822. }
  28823. }
  28824. for (f = 0; f < surfaceNb; f++) {
  28825. if (faceUV && faceUV[f] === undefined) {
  28826. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28827. }
  28828. }
  28829. var indices = [];
  28830. var positions = [];
  28831. var normals = [];
  28832. var uvs = [];
  28833. var colors = [];
  28834. var angle_step = Math.PI * 2 * arc / tessellation;
  28835. var angle;
  28836. var h;
  28837. var radius;
  28838. var tan = (diameterBottom - diameterTop) / 2 / height;
  28839. var ringVertex = BABYLON.Vector3.Zero();
  28840. var ringNormal = BABYLON.Vector3.Zero();
  28841. var ringFirstVertex = BABYLON.Vector3.Zero();
  28842. var ringFirstNormal = BABYLON.Vector3.Zero();
  28843. var quadNormal = BABYLON.Vector3.Zero();
  28844. var Y = BABYLON.Axis.Y;
  28845. // positions, normals, uvs
  28846. var i;
  28847. var j;
  28848. var r;
  28849. var ringIdx = 1;
  28850. var s = 1; // surface index
  28851. var cs = 0;
  28852. var v = 0;
  28853. for (i = 0; i <= subdivisions; i++) {
  28854. h = i / subdivisions;
  28855. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28856. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28857. for (r = 0; r < ringIdx; r++) {
  28858. if (hasRings) {
  28859. s += r;
  28860. }
  28861. if (enclose) {
  28862. s += 2 * r;
  28863. }
  28864. for (j = 0; j <= tessellation; j++) {
  28865. angle = j * angle_step;
  28866. // position
  28867. ringVertex.x = Math.cos(-angle) * radius;
  28868. ringVertex.y = -height / 2 + h * height;
  28869. ringVertex.z = Math.sin(-angle) * radius;
  28870. // normal
  28871. if (diameterTop === 0 && i === subdivisions) {
  28872. // if no top cap, reuse former normals
  28873. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28874. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28875. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28876. }
  28877. else {
  28878. ringNormal.x = ringVertex.x;
  28879. ringNormal.z = ringVertex.z;
  28880. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28881. ringNormal.normalize();
  28882. }
  28883. // keep first ring vertex values for enclose
  28884. if (j === 0) {
  28885. ringFirstVertex.copyFrom(ringVertex);
  28886. ringFirstNormal.copyFrom(ringNormal);
  28887. }
  28888. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28889. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28890. if (hasRings) {
  28891. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28892. }
  28893. else {
  28894. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28895. }
  28896. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28897. if (faceColors) {
  28898. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28899. }
  28900. }
  28901. // if enclose, add four vertices and their dedicated normals
  28902. if (arc !== 1 && enclose) {
  28903. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28904. positions.push(0, ringVertex.y, 0);
  28905. positions.push(0, ringVertex.y, 0);
  28906. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28907. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28908. quadNormal.normalize();
  28909. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28910. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28911. quadNormal.normalize();
  28912. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28913. if (hasRings) {
  28914. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28915. }
  28916. else {
  28917. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28918. }
  28919. uvs.push(faceUV[s + 1].x, v);
  28920. uvs.push(faceUV[s + 1].z, v);
  28921. if (hasRings) {
  28922. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28923. }
  28924. else {
  28925. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28926. }
  28927. uvs.push(faceUV[s + 2].x, v);
  28928. uvs.push(faceUV[s + 2].z, v);
  28929. if (faceColors) {
  28930. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28931. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28932. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28933. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28934. }
  28935. }
  28936. if (cs !== s) {
  28937. cs = s;
  28938. }
  28939. }
  28940. }
  28941. // indices
  28942. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28943. var s;
  28944. i = 0;
  28945. for (s = 0; s < subdivisions; s++) {
  28946. for (j = 0; j < tessellation; j++) {
  28947. var i0 = i * (e + 1) + j;
  28948. var i1 = (i + 1) * (e + 1) + j;
  28949. var i2 = i * (e + 1) + (j + 1);
  28950. var i3 = (i + 1) * (e + 1) + (j + 1);
  28951. indices.push(i0, i1, i2);
  28952. indices.push(i3, i2, i1);
  28953. }
  28954. if (arc !== 1 && enclose) {
  28955. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28956. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28957. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28958. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28959. }
  28960. i = (hasRings) ? (i + 2) : (i + 1);
  28961. }
  28962. // Caps
  28963. var createCylinderCap = function (isTop) {
  28964. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28965. if (radius === 0) {
  28966. return;
  28967. }
  28968. // Cap positions, normals & uvs
  28969. var angle;
  28970. var circleVector;
  28971. var i;
  28972. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28973. var c;
  28974. if (faceColors) {
  28975. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28976. }
  28977. // cap center
  28978. var vbase = positions.length / 3;
  28979. var offset = isTop ? height / 2 : -height / 2;
  28980. var center = new BABYLON.Vector3(0, offset, 0);
  28981. positions.push(center.x, center.y, center.z);
  28982. normals.push(0, isTop ? 1 : -1, 0);
  28983. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28984. if (faceColors) {
  28985. colors.push(c.r, c.g, c.b, c.a);
  28986. }
  28987. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28988. for (i = 0; i <= tessellation; i++) {
  28989. angle = Math.PI * 2 * i * arc / tessellation;
  28990. var cos = Math.cos(-angle);
  28991. var sin = Math.sin(-angle);
  28992. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28993. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28994. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28995. normals.push(0, isTop ? 1 : -1, 0);
  28996. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28997. if (faceColors) {
  28998. colors.push(c.r, c.g, c.b, c.a);
  28999. }
  29000. }
  29001. // Cap indices
  29002. for (i = 0; i < tessellation; i++) {
  29003. if (!isTop) {
  29004. indices.push(vbase);
  29005. indices.push(vbase + (i + 1));
  29006. indices.push(vbase + (i + 2));
  29007. }
  29008. else {
  29009. indices.push(vbase);
  29010. indices.push(vbase + (i + 2));
  29011. indices.push(vbase + (i + 1));
  29012. }
  29013. }
  29014. };
  29015. // add caps to geometry
  29016. createCylinderCap(false);
  29017. createCylinderCap(true);
  29018. // Sides
  29019. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29020. var vertexData = new VertexData();
  29021. vertexData.indices = indices;
  29022. vertexData.positions = positions;
  29023. vertexData.normals = normals;
  29024. vertexData.uvs = uvs;
  29025. if (faceColors) {
  29026. vertexData.colors = colors;
  29027. }
  29028. return vertexData;
  29029. };
  29030. VertexData.CreateTorus = function (options) {
  29031. var indices = [];
  29032. var positions = [];
  29033. var normals = [];
  29034. var uvs = [];
  29035. var diameter = options.diameter || 1;
  29036. var thickness = options.thickness || 0.5;
  29037. var tessellation = options.tessellation || 16;
  29038. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29039. var stride = tessellation + 1;
  29040. for (var i = 0; i <= tessellation; i++) {
  29041. var u = i / tessellation;
  29042. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29043. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29044. for (var j = 0; j <= tessellation; j++) {
  29045. var v = 1 - j / tessellation;
  29046. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29047. var dx = Math.cos(innerAngle);
  29048. var dy = Math.sin(innerAngle);
  29049. // Create a vertex.
  29050. var normal = new BABYLON.Vector3(dx, dy, 0);
  29051. var position = normal.scale(thickness / 2);
  29052. var textureCoordinate = new BABYLON.Vector2(u, v);
  29053. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29054. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29055. positions.push(position.x, position.y, position.z);
  29056. normals.push(normal.x, normal.y, normal.z);
  29057. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29058. // And create indices for two triangles.
  29059. var nextI = (i + 1) % stride;
  29060. var nextJ = (j + 1) % stride;
  29061. indices.push(i * stride + j);
  29062. indices.push(i * stride + nextJ);
  29063. indices.push(nextI * stride + j);
  29064. indices.push(i * stride + nextJ);
  29065. indices.push(nextI * stride + nextJ);
  29066. indices.push(nextI * stride + j);
  29067. }
  29068. }
  29069. // Sides
  29070. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29071. // Result
  29072. var vertexData = new VertexData();
  29073. vertexData.indices = indices;
  29074. vertexData.positions = positions;
  29075. vertexData.normals = normals;
  29076. vertexData.uvs = uvs;
  29077. return vertexData;
  29078. };
  29079. VertexData.CreateLineSystem = function (options) {
  29080. var indices = [];
  29081. var positions = [];
  29082. var lines = options.lines;
  29083. var idx = 0;
  29084. for (var l = 0; l < lines.length; l++) {
  29085. var points = lines[l];
  29086. for (var index = 0; index < points.length; index++) {
  29087. positions.push(points[index].x, points[index].y, points[index].z);
  29088. if (index > 0) {
  29089. indices.push(idx - 1);
  29090. indices.push(idx);
  29091. }
  29092. idx++;
  29093. }
  29094. }
  29095. var vertexData = new VertexData();
  29096. vertexData.indices = indices;
  29097. vertexData.positions = positions;
  29098. return vertexData;
  29099. };
  29100. VertexData.CreateDashedLines = function (options) {
  29101. var dashSize = options.dashSize || 3;
  29102. var gapSize = options.gapSize || 1;
  29103. var dashNb = options.dashNb || 200;
  29104. var points = options.points;
  29105. var positions = new Array();
  29106. var indices = new Array();
  29107. var curvect = BABYLON.Vector3.Zero();
  29108. var lg = 0;
  29109. var nb = 0;
  29110. var shft = 0;
  29111. var dashshft = 0;
  29112. var curshft = 0;
  29113. var idx = 0;
  29114. var i = 0;
  29115. for (i = 0; i < points.length - 1; i++) {
  29116. points[i + 1].subtractToRef(points[i], curvect);
  29117. lg += curvect.length();
  29118. }
  29119. shft = lg / dashNb;
  29120. dashshft = dashSize * shft / (dashSize + gapSize);
  29121. for (i = 0; i < points.length - 1; i++) {
  29122. points[i + 1].subtractToRef(points[i], curvect);
  29123. nb = Math.floor(curvect.length() / shft);
  29124. curvect.normalize();
  29125. for (var j = 0; j < nb; j++) {
  29126. curshft = shft * j;
  29127. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29128. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29129. indices.push(idx, idx + 1);
  29130. idx += 2;
  29131. }
  29132. }
  29133. // Result
  29134. var vertexData = new VertexData();
  29135. vertexData.positions = positions;
  29136. vertexData.indices = indices;
  29137. return vertexData;
  29138. };
  29139. VertexData.CreateGround = function (options) {
  29140. var indices = [];
  29141. var positions = [];
  29142. var normals = [];
  29143. var uvs = [];
  29144. var row, col;
  29145. var width = options.width || 1;
  29146. var height = options.height || 1;
  29147. var subdivisions = options.subdivisions || 1;
  29148. for (row = 0; row <= subdivisions; row++) {
  29149. for (col = 0; col <= subdivisions; col++) {
  29150. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  29151. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29152. positions.push(position.x, position.y, position.z);
  29153. normals.push(normal.x, normal.y, normal.z);
  29154. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  29155. }
  29156. }
  29157. for (row = 0; row < subdivisions; row++) {
  29158. for (col = 0; col < subdivisions; col++) {
  29159. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29160. indices.push(col + 1 + row * (subdivisions + 1));
  29161. indices.push(col + row * (subdivisions + 1));
  29162. indices.push(col + (row + 1) * (subdivisions + 1));
  29163. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29164. indices.push(col + row * (subdivisions + 1));
  29165. }
  29166. }
  29167. // Result
  29168. var vertexData = new VertexData();
  29169. vertexData.indices = indices;
  29170. vertexData.positions = positions;
  29171. vertexData.normals = normals;
  29172. vertexData.uvs = uvs;
  29173. return vertexData;
  29174. };
  29175. VertexData.CreateTiledGround = function (options) {
  29176. var xmin = options.xmin;
  29177. var zmin = options.zmin;
  29178. var xmax = options.xmax;
  29179. var zmax = options.zmax;
  29180. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29181. var precision = options.precision || { w: 1, h: 1 };
  29182. var indices = [];
  29183. var positions = [];
  29184. var normals = [];
  29185. var uvs = [];
  29186. var row, col, tileRow, tileCol;
  29187. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  29188. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29189. precision.w = (precision.w < 1) ? 1 : precision.w;
  29190. precision.h = (precision.h < 1) ? 1 : precision.h;
  29191. var tileSize = {
  29192. 'w': (xmax - xmin) / subdivisions.w,
  29193. 'h': (zmax - zmin) / subdivisions.h
  29194. };
  29195. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29196. // Indices
  29197. var base = positions.length / 3;
  29198. var rowLength = precision.w + 1;
  29199. for (row = 0; row < precision.h; row++) {
  29200. for (col = 0; col < precision.w; col++) {
  29201. var square = [
  29202. base + col + row * rowLength,
  29203. base + (col + 1) + row * rowLength,
  29204. base + (col + 1) + (row + 1) * rowLength,
  29205. base + col + (row + 1) * rowLength
  29206. ];
  29207. indices.push(square[1]);
  29208. indices.push(square[2]);
  29209. indices.push(square[3]);
  29210. indices.push(square[0]);
  29211. indices.push(square[1]);
  29212. indices.push(square[3]);
  29213. }
  29214. }
  29215. // Position, normals and uvs
  29216. var position = BABYLON.Vector3.Zero();
  29217. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29218. for (row = 0; row <= precision.h; row++) {
  29219. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29220. for (col = 0; col <= precision.w; col++) {
  29221. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29222. position.y = 0;
  29223. positions.push(position.x, position.y, position.z);
  29224. normals.push(normal.x, normal.y, normal.z);
  29225. uvs.push(col / precision.w, row / precision.h);
  29226. }
  29227. }
  29228. }
  29229. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29230. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29231. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29232. }
  29233. }
  29234. // Result
  29235. var vertexData = new VertexData();
  29236. vertexData.indices = indices;
  29237. vertexData.positions = positions;
  29238. vertexData.normals = normals;
  29239. vertexData.uvs = uvs;
  29240. return vertexData;
  29241. };
  29242. VertexData.CreateGroundFromHeightMap = function (options) {
  29243. var indices = [];
  29244. var positions = [];
  29245. var normals = [];
  29246. var uvs = [];
  29247. var row, col;
  29248. // Vertices
  29249. for (row = 0; row <= options.subdivisions; row++) {
  29250. for (col = 0; col <= options.subdivisions; col++) {
  29251. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  29252. // Compute height
  29253. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29254. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29255. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29256. var r = options.buffer[pos] / 255.0;
  29257. var g = options.buffer[pos + 1] / 255.0;
  29258. var b = options.buffer[pos + 2] / 255.0;
  29259. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29260. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29261. // Add vertex
  29262. positions.push(position.x, position.y, position.z);
  29263. normals.push(0, 0, 0);
  29264. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29265. }
  29266. }
  29267. // Indices
  29268. for (row = 0; row < options.subdivisions; row++) {
  29269. for (col = 0; col < options.subdivisions; col++) {
  29270. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29271. indices.push(col + 1 + row * (options.subdivisions + 1));
  29272. indices.push(col + row * (options.subdivisions + 1));
  29273. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29274. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29275. indices.push(col + row * (options.subdivisions + 1));
  29276. }
  29277. }
  29278. // Normals
  29279. VertexData.ComputeNormals(positions, indices, normals);
  29280. // Result
  29281. var vertexData = new VertexData();
  29282. vertexData.indices = indices;
  29283. vertexData.positions = positions;
  29284. vertexData.normals = normals;
  29285. vertexData.uvs = uvs;
  29286. return vertexData;
  29287. };
  29288. VertexData.CreatePlane = function (options) {
  29289. var indices = [];
  29290. var positions = [];
  29291. var normals = [];
  29292. var uvs = [];
  29293. var width = options.width || options.size || 1;
  29294. var height = options.height || options.size || 1;
  29295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29296. // Vertices
  29297. var halfWidth = width / 2.0;
  29298. var halfHeight = height / 2.0;
  29299. positions.push(-halfWidth, -halfHeight, 0);
  29300. normals.push(0, 0, -1.0);
  29301. uvs.push(0.0, 0.0);
  29302. positions.push(halfWidth, -halfHeight, 0);
  29303. normals.push(0, 0, -1.0);
  29304. uvs.push(1.0, 0.0);
  29305. positions.push(halfWidth, halfHeight, 0);
  29306. normals.push(0, 0, -1.0);
  29307. uvs.push(1.0, 1.0);
  29308. positions.push(-halfWidth, halfHeight, 0);
  29309. normals.push(0, 0, -1.0);
  29310. uvs.push(0.0, 1.0);
  29311. // Indices
  29312. indices.push(0);
  29313. indices.push(1);
  29314. indices.push(2);
  29315. indices.push(0);
  29316. indices.push(2);
  29317. indices.push(3);
  29318. // Sides
  29319. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29320. // Result
  29321. var vertexData = new VertexData();
  29322. vertexData.indices = indices;
  29323. vertexData.positions = positions;
  29324. vertexData.normals = normals;
  29325. vertexData.uvs = uvs;
  29326. return vertexData;
  29327. };
  29328. VertexData.CreateDisc = function (options) {
  29329. var positions = [];
  29330. var indices = [];
  29331. var normals = [];
  29332. var uvs = [];
  29333. var radius = options.radius || 0.5;
  29334. var tessellation = options.tessellation || 64;
  29335. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29336. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29337. // positions and uvs
  29338. positions.push(0, 0, 0); // disc center first
  29339. uvs.push(0.5, 0.5);
  29340. var theta = Math.PI * 2 * arc;
  29341. var step = theta / tessellation;
  29342. for (var a = 0; a < theta; a += step) {
  29343. var x = Math.cos(a);
  29344. var y = Math.sin(a);
  29345. var u = (x + 1) / 2;
  29346. var v = (1 - y) / 2;
  29347. positions.push(radius * x, radius * y, 0);
  29348. uvs.push(u, v);
  29349. }
  29350. if (arc === 1) {
  29351. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29352. uvs.push(uvs[2], uvs[3]);
  29353. }
  29354. //indices
  29355. var vertexNb = positions.length / 3;
  29356. for (var i = 1; i < vertexNb - 1; i++) {
  29357. indices.push(i + 1, 0, i);
  29358. }
  29359. // result
  29360. VertexData.ComputeNormals(positions, indices, normals);
  29361. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29362. var vertexData = new VertexData();
  29363. vertexData.indices = indices;
  29364. vertexData.positions = positions;
  29365. vertexData.normals = normals;
  29366. vertexData.uvs = uvs;
  29367. return vertexData;
  29368. };
  29369. VertexData.CreateIcoSphere = function (options) {
  29370. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29371. var radius = options.radius || 1;
  29372. var flat = (options.flat === undefined) ? true : options.flat;
  29373. var subdivisions = options.subdivisions || 4;
  29374. var radiusX = options.radiusX || radius;
  29375. var radiusY = options.radiusY || radius;
  29376. var radiusZ = options.radiusZ || radius;
  29377. var t = (1 + Math.sqrt(5)) / 2;
  29378. // 12 vertex x,y,z
  29379. var ico_vertices = [
  29380. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29381. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29382. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29383. ];
  29384. // index of 3 vertex makes a face of icopshere
  29385. var ico_indices = [
  29386. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29387. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29388. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29389. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29390. ];
  29391. // vertex for uv have aliased position, not for UV
  29392. var vertices_unalias_id = [
  29393. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29394. // vertex alias
  29395. 0,
  29396. 2,
  29397. 3,
  29398. 3,
  29399. 3,
  29400. 4,
  29401. 7,
  29402. 8,
  29403. 9,
  29404. 9,
  29405. 10,
  29406. 11 // 23: B + 12
  29407. ];
  29408. // uv as integer step (not pixels !)
  29409. var ico_vertexuv = [
  29410. 5, 1, 3, 1, 6, 4, 0, 0,
  29411. 5, 3, 4, 2, 2, 2, 4, 0,
  29412. 2, 0, 1, 1, 6, 0, 6, 2,
  29413. // vertex alias (for same vertex on different faces)
  29414. 0, 4,
  29415. 3, 3,
  29416. 4, 4,
  29417. 3, 1,
  29418. 4, 2,
  29419. 4, 4,
  29420. 0, 2,
  29421. 1, 1,
  29422. 2, 2,
  29423. 3, 3,
  29424. 1, 3,
  29425. 2, 4 // 23: B + 12
  29426. ];
  29427. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29428. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29429. // First island of uv mapping
  29430. // v = 4h 3+ 2
  29431. // v = 3h 9+ 4
  29432. // v = 2h 9+ 5 B
  29433. // v = 1h 9 1 0
  29434. // v = 0h 3 8 7 A
  29435. // u = 0 1 2 3 4 5 6 *a
  29436. // Second island of uv mapping
  29437. // v = 4h 0+ B+ 4+
  29438. // v = 3h A+ 2+
  29439. // v = 2h 7+ 6 3+
  29440. // v = 1h 8+ 3+
  29441. // v = 0h
  29442. // u = 0 1 2 3 4 5 6 *a
  29443. // Face layout on texture UV mapping
  29444. // ============
  29445. // \ 4 /\ 16 / ======
  29446. // \ / \ / /\ 11 /
  29447. // \/ 7 \/ / \ /
  29448. // ======= / 10 \/
  29449. // /\ 17 /\ =======
  29450. // / \ / \ \ 15 /\
  29451. // / 8 \/ 12 \ \ / \
  29452. // ============ \/ 6 \
  29453. // \ 18 /\ ============
  29454. // \ / \ \ 5 /\ 0 /
  29455. // \/ 13 \ \ / \ /
  29456. // ======= \/ 1 \/
  29457. // =============
  29458. // /\ 19 /\ 2 /\
  29459. // / \ / \ / \
  29460. // / 14 \/ 9 \/ 3 \
  29461. // ===================
  29462. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29463. var ustep = 138 / 1024;
  29464. var vstep = 239 / 1024;
  29465. var uoffset = 60 / 1024;
  29466. var voffset = 26 / 1024;
  29467. // Second island should have margin, not to touch the first island
  29468. // avoid any borderline artefact in pixel rounding
  29469. var island_u_offset = -40 / 1024;
  29470. var island_v_offset = +20 / 1024;
  29471. // face is either island 0 or 1 :
  29472. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29473. var island = [
  29474. 0, 0, 0, 0, 1,
  29475. 0, 0, 1, 1, 0,
  29476. 0, 0, 1, 1, 0,
  29477. 0, 1, 1, 1, 0 // 15 - 19
  29478. ];
  29479. var indices = [];
  29480. var positions = [];
  29481. var normals = [];
  29482. var uvs = [];
  29483. var current_indice = 0;
  29484. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29485. var face_vertex_pos = new Array(3);
  29486. var face_vertex_uv = new Array(3);
  29487. var v012;
  29488. for (v012 = 0; v012 < 3; v012++) {
  29489. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29490. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29491. }
  29492. // create all with normals
  29493. for (var face = 0; face < 20; face++) {
  29494. // 3 vertex per face
  29495. for (v012 = 0; v012 < 3; v012++) {
  29496. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29497. var v_id = ico_indices[3 * face + v012];
  29498. // vertex have 3D position (x,y,z)
  29499. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  29500. // Normalize to get normal, then scale to radius
  29501. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29502. // uv Coordinates from vertex ID
  29503. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  29504. }
  29505. // Subdivide the face (interpolate pos, norm, uv)
  29506. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29507. // - norm is linear interpolation of vertex corner normal
  29508. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29509. // - uv is linear interpolation
  29510. //
  29511. // Topology is as below for sub-divide by 2
  29512. // vertex shown as v0,v1,v2
  29513. // interp index is i1 to progress in range [v0,v1[
  29514. // interp index is i2 to progress in range [v0,v2[
  29515. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29516. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29517. //
  29518. //
  29519. // i2 v2
  29520. // ^ ^
  29521. // / / \
  29522. // / / \
  29523. // / / \
  29524. // / / (0,1) \
  29525. // / #---------\
  29526. // / / \ (0,0)'/ \
  29527. // / / \ / \
  29528. // / / \ / \
  29529. // / / (0,0) \ / (1,0) \
  29530. // / #---------#---------\
  29531. // v0 v1
  29532. //
  29533. // --------------------> i1
  29534. //
  29535. // interp of (i1,i2):
  29536. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29537. // along i1 : lerp(x0,x1, i1/(S-i2))
  29538. //
  29539. // centroid of triangle is needed to get help normal computation
  29540. // (c1,c2) are used for centroid location
  29541. var interp_vertex = function (i1, i2, c1, c2) {
  29542. // vertex is interpolated from
  29543. // - face_vertex_pos[0..2]
  29544. // - face_vertex_uv[0..2]
  29545. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29546. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29547. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29548. pos_interp.normalize();
  29549. var vertex_normal;
  29550. if (flat) {
  29551. // in flat mode, recalculate normal as face centroid normal
  29552. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29553. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29554. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29555. }
  29556. else {
  29557. // in smooth mode, recalculate normal from each single vertex position
  29558. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29559. }
  29560. // Vertex normal need correction due to X,Y,Z radius scaling
  29561. vertex_normal.x /= radiusX;
  29562. vertex_normal.y /= radiusY;
  29563. vertex_normal.z /= radiusZ;
  29564. vertex_normal.normalize();
  29565. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29566. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29567. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29568. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29569. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29570. uvs.push(uv_interp.x, uv_interp.y);
  29571. // push each vertex has member of a face
  29572. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29573. indices.push(current_indice);
  29574. current_indice++;
  29575. };
  29576. for (var i2 = 0; i2 < subdivisions; i2++) {
  29577. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29578. // face : (i1,i2) for /\ :
  29579. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29580. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29581. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29582. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29583. if (i1 + i2 + 1 < subdivisions) {
  29584. // face : (i1,i2)' for \/ :
  29585. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29586. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29587. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29588. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29589. }
  29590. }
  29591. }
  29592. }
  29593. // Sides
  29594. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29595. // Result
  29596. var vertexData = new VertexData();
  29597. vertexData.indices = indices;
  29598. vertexData.positions = positions;
  29599. vertexData.normals = normals;
  29600. vertexData.uvs = uvs;
  29601. return vertexData;
  29602. };
  29603. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29604. VertexData.CreatePolyhedron = function (options) {
  29605. // provided polyhedron types :
  29606. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29607. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  29608. var polyhedra = [];
  29609. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  29610. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  29611. polyhedra[2] = {
  29612. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  29613. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  29614. };
  29615. polyhedra[3] = {
  29616. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  29617. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  29618. };
  29619. polyhedra[4] = {
  29620. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  29621. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  29622. };
  29623. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  29624. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  29625. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  29626. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  29627. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  29628. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  29629. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  29630. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  29631. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  29632. polyhedra[14] = {
  29633. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  29634. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  29635. };
  29636. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29637. var size = options.size;
  29638. var sizeX = options.sizeX || size || 1;
  29639. var sizeY = options.sizeY || size || 1;
  29640. var sizeZ = options.sizeZ || size || 1;
  29641. var data = options.custom || polyhedra[type];
  29642. var nbfaces = data.face.length;
  29643. var faceUV = options.faceUV || new Array(nbfaces);
  29644. var faceColors = options.faceColors;
  29645. var flat = (options.flat === undefined) ? true : options.flat;
  29646. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29647. var positions = [];
  29648. var indices = [];
  29649. var normals = [];
  29650. var uvs = [];
  29651. var colors = [];
  29652. var index = 0;
  29653. var faceIdx = 0; // face cursor in the array "indexes"
  29654. var indexes = [];
  29655. var i = 0;
  29656. var f = 0;
  29657. var u, v, ang, x, y, tmp;
  29658. // default face colors and UV if undefined
  29659. if (flat) {
  29660. for (f = 0; f < nbfaces; f++) {
  29661. if (faceColors && faceColors[f] === undefined) {
  29662. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29663. }
  29664. if (faceUV && faceUV[f] === undefined) {
  29665. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29666. }
  29667. }
  29668. }
  29669. if (!flat) {
  29670. for (i = 0; i < data.vertex.length; i++) {
  29671. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29672. uvs.push(0, 0);
  29673. }
  29674. for (f = 0; f < nbfaces; f++) {
  29675. for (i = 0; i < data.face[f].length - 2; i++) {
  29676. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29677. }
  29678. }
  29679. }
  29680. else {
  29681. for (f = 0; f < nbfaces; f++) {
  29682. var fl = data.face[f].length; // number of vertices of the current face
  29683. ang = 2 * Math.PI / fl;
  29684. x = 0.5 * Math.tan(ang / 2);
  29685. y = 0.5;
  29686. // positions, uvs, colors
  29687. for (i = 0; i < fl; i++) {
  29688. // positions
  29689. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  29690. indexes.push(index);
  29691. index++;
  29692. // uvs
  29693. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29694. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29695. uvs.push(u, v);
  29696. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29697. y = x * Math.sin(ang) + y * Math.cos(ang);
  29698. x = tmp;
  29699. // colors
  29700. if (faceColors) {
  29701. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29702. }
  29703. }
  29704. // indices from indexes
  29705. for (i = 0; i < fl - 2; i++) {
  29706. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29707. }
  29708. faceIdx += fl;
  29709. }
  29710. }
  29711. VertexData.ComputeNormals(positions, indices, normals);
  29712. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29713. var vertexData = new VertexData();
  29714. vertexData.positions = positions;
  29715. vertexData.indices = indices;
  29716. vertexData.normals = normals;
  29717. vertexData.uvs = uvs;
  29718. if (faceColors && flat) {
  29719. vertexData.colors = colors;
  29720. }
  29721. return vertexData;
  29722. };
  29723. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29724. VertexData.CreateTorusKnot = function (options) {
  29725. var indices = [];
  29726. var positions = [];
  29727. var normals = [];
  29728. var uvs = [];
  29729. var radius = options.radius || 2;
  29730. var tube = options.tube || 0.5;
  29731. var radialSegments = options.radialSegments || 32;
  29732. var tubularSegments = options.tubularSegments || 32;
  29733. var p = options.p || 2;
  29734. var q = options.q || 3;
  29735. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29736. // Helper
  29737. var getPos = function (angle) {
  29738. var cu = Math.cos(angle);
  29739. var su = Math.sin(angle);
  29740. var quOverP = q / p * angle;
  29741. var cs = Math.cos(quOverP);
  29742. var tx = radius * (2 + cs) * 0.5 * cu;
  29743. var ty = radius * (2 + cs) * su * 0.5;
  29744. var tz = radius * Math.sin(quOverP) * 0.5;
  29745. return new BABYLON.Vector3(tx, ty, tz);
  29746. };
  29747. // Vertices
  29748. var i;
  29749. var j;
  29750. for (i = 0; i <= radialSegments; i++) {
  29751. var modI = i % radialSegments;
  29752. var u = modI / radialSegments * 2 * p * Math.PI;
  29753. var p1 = getPos(u);
  29754. var p2 = getPos(u + 0.01);
  29755. var tang = p2.subtract(p1);
  29756. var n = p2.add(p1);
  29757. var bitan = BABYLON.Vector3.Cross(tang, n);
  29758. n = BABYLON.Vector3.Cross(bitan, tang);
  29759. bitan.normalize();
  29760. n.normalize();
  29761. for (j = 0; j < tubularSegments; j++) {
  29762. var modJ = j % tubularSegments;
  29763. var v = modJ / tubularSegments * 2 * Math.PI;
  29764. var cx = -tube * Math.cos(v);
  29765. var cy = tube * Math.sin(v);
  29766. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29767. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29768. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29769. uvs.push(i / radialSegments);
  29770. uvs.push(j / tubularSegments);
  29771. }
  29772. }
  29773. for (i = 0; i < radialSegments; i++) {
  29774. for (j = 0; j < tubularSegments; j++) {
  29775. var jNext = (j + 1) % tubularSegments;
  29776. var a = i * tubularSegments + j;
  29777. var b = (i + 1) * tubularSegments + j;
  29778. var c = (i + 1) * tubularSegments + jNext;
  29779. var d = i * tubularSegments + jNext;
  29780. indices.push(d);
  29781. indices.push(b);
  29782. indices.push(a);
  29783. indices.push(d);
  29784. indices.push(c);
  29785. indices.push(b);
  29786. }
  29787. }
  29788. // Normals
  29789. VertexData.ComputeNormals(positions, indices, normals);
  29790. // Sides
  29791. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29792. // Result
  29793. var vertexData = new VertexData();
  29794. vertexData.indices = indices;
  29795. vertexData.positions = positions;
  29796. vertexData.normals = normals;
  29797. vertexData.uvs = uvs;
  29798. return vertexData;
  29799. };
  29800. // Tools
  29801. /**
  29802. * @param {any} - positions (number[] or Float32Array)
  29803. * @param {any} - indices (number[] or Uint16Array)
  29804. * @param {any} - normals (number[] or Float32Array)
  29805. */
  29806. VertexData.ComputeNormals = function (positions, indices, normals) {
  29807. var index = 0;
  29808. var p1p2x = 0.0;
  29809. var p1p2y = 0.0;
  29810. var p1p2z = 0.0;
  29811. var p3p2x = 0.0;
  29812. var p3p2y = 0.0;
  29813. var p3p2z = 0.0;
  29814. var faceNormalx = 0.0;
  29815. var faceNormaly = 0.0;
  29816. var faceNormalz = 0.0;
  29817. var length = 0.0;
  29818. var i1 = 0;
  29819. var i2 = 0;
  29820. var i3 = 0;
  29821. for (index = 0; index < positions.length; index++) {
  29822. normals[index] = 0.0;
  29823. }
  29824. // indice triplet = 1 face
  29825. var nbFaces = indices.length / 3;
  29826. for (index = 0; index < nbFaces; index++) {
  29827. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  29828. i2 = indices[index * 3 + 1];
  29829. i3 = indices[index * 3 + 2];
  29830. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  29831. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  29832. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  29833. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  29834. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  29835. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  29836. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  29837. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  29838. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  29839. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29840. length = (length === 0) ? 1.0 : length;
  29841. faceNormalx /= length; // normalize this normal
  29842. faceNormaly /= length;
  29843. faceNormalz /= length;
  29844. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  29845. normals[i1 * 3 + 1] += faceNormaly;
  29846. normals[i1 * 3 + 2] += faceNormalz;
  29847. normals[i2 * 3] += faceNormalx;
  29848. normals[i2 * 3 + 1] += faceNormaly;
  29849. normals[i2 * 3 + 2] += faceNormalz;
  29850. normals[i3 * 3] += faceNormalx;
  29851. normals[i3 * 3 + 1] += faceNormaly;
  29852. normals[i3 * 3 + 2] += faceNormalz;
  29853. }
  29854. // last normalization of each normal
  29855. for (index = 0; index < normals.length / 3; index++) {
  29856. faceNormalx = normals[index * 3];
  29857. faceNormaly = normals[index * 3 + 1];
  29858. faceNormalz = normals[index * 3 + 2];
  29859. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29860. length = (length === 0) ? 1.0 : length;
  29861. faceNormalx /= length;
  29862. faceNormaly /= length;
  29863. faceNormalz /= length;
  29864. normals[index * 3] = faceNormalx;
  29865. normals[index * 3 + 1] = faceNormaly;
  29866. normals[index * 3 + 2] = faceNormalz;
  29867. }
  29868. };
  29869. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29870. var li = indices.length;
  29871. var ln = normals.length;
  29872. var i;
  29873. var n;
  29874. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29875. switch (sideOrientation) {
  29876. case BABYLON.Mesh.FRONTSIDE:
  29877. // nothing changed
  29878. break;
  29879. case BABYLON.Mesh.BACKSIDE:
  29880. var tmp;
  29881. // indices
  29882. for (i = 0; i < li; i += 3) {
  29883. tmp = indices[i];
  29884. indices[i] = indices[i + 2];
  29885. indices[i + 2] = tmp;
  29886. }
  29887. // normals
  29888. for (n = 0; n < ln; n++) {
  29889. normals[n] = -normals[n];
  29890. }
  29891. break;
  29892. case BABYLON.Mesh.DOUBLESIDE:
  29893. // positions
  29894. var lp = positions.length;
  29895. var l = lp / 3;
  29896. for (var p = 0; p < lp; p++) {
  29897. positions[lp + p] = positions[p];
  29898. }
  29899. // indices
  29900. for (i = 0; i < li; i += 3) {
  29901. indices[i + li] = indices[i + 2] + l;
  29902. indices[i + 1 + li] = indices[i + 1] + l;
  29903. indices[i + 2 + li] = indices[i] + l;
  29904. }
  29905. // normals
  29906. for (n = 0; n < ln; n++) {
  29907. normals[ln + n] = -normals[n];
  29908. }
  29909. // uvs
  29910. var lu = uvs.length;
  29911. for (var u = 0; u < lu; u++) {
  29912. uvs[u + lu] = uvs[u];
  29913. }
  29914. break;
  29915. }
  29916. };
  29917. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29918. var vertexData = new VertexData();
  29919. // positions
  29920. var positions = parsedVertexData.positions;
  29921. if (positions) {
  29922. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29923. }
  29924. // normals
  29925. var normals = parsedVertexData.normals;
  29926. if (normals) {
  29927. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29928. }
  29929. // uvs
  29930. var uvs = parsedVertexData.uvs;
  29931. if (uvs) {
  29932. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29933. }
  29934. // uv2s
  29935. var uv2s = parsedVertexData.uv2s;
  29936. if (uv2s) {
  29937. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29938. }
  29939. // uv3s
  29940. var uv3s = parsedVertexData.uv3s;
  29941. if (uv3s) {
  29942. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29943. }
  29944. // uv4s
  29945. var uv4s = parsedVertexData.uv4s;
  29946. if (uv4s) {
  29947. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29948. }
  29949. // uv5s
  29950. var uv5s = parsedVertexData.uv5s;
  29951. if (uv5s) {
  29952. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29953. }
  29954. // uv6s
  29955. var uv6s = parsedVertexData.uv6s;
  29956. if (uv6s) {
  29957. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29958. }
  29959. // colors
  29960. var colors = parsedVertexData.colors;
  29961. if (colors) {
  29962. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29963. }
  29964. // matricesIndices
  29965. var matricesIndices = parsedVertexData.matricesIndices;
  29966. if (matricesIndices) {
  29967. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29968. }
  29969. // matricesWeights
  29970. var matricesWeights = parsedVertexData.matricesWeights;
  29971. if (matricesWeights) {
  29972. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29973. }
  29974. // indices
  29975. var indices = parsedVertexData.indices;
  29976. if (indices) {
  29977. vertexData.indices = indices;
  29978. }
  29979. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29980. };
  29981. return VertexData;
  29982. })();
  29983. BABYLON.VertexData = VertexData;
  29984. })(BABYLON || (BABYLON = {}));
  29985. var BABYLON;
  29986. (function (BABYLON) {
  29987. var Tags = (function () {
  29988. function Tags() {
  29989. }
  29990. Tags.EnableFor = function (obj) {
  29991. obj._tags = obj._tags || {};
  29992. obj.hasTags = function () {
  29993. return Tags.HasTags(obj);
  29994. };
  29995. obj.addTags = function (tagsString) {
  29996. return Tags.AddTagsTo(obj, tagsString);
  29997. };
  29998. obj.removeTags = function (tagsString) {
  29999. return Tags.RemoveTagsFrom(obj, tagsString);
  30000. };
  30001. obj.matchesTagsQuery = function (tagsQuery) {
  30002. return Tags.MatchesQuery(obj, tagsQuery);
  30003. };
  30004. };
  30005. Tags.DisableFor = function (obj) {
  30006. delete obj._tags;
  30007. delete obj.hasTags;
  30008. delete obj.addTags;
  30009. delete obj.removeTags;
  30010. delete obj.matchesTagsQuery;
  30011. };
  30012. Tags.HasTags = function (obj) {
  30013. if (!obj._tags) {
  30014. return false;
  30015. }
  30016. return !BABYLON.Tools.IsEmpty(obj._tags);
  30017. };
  30018. Tags.GetTags = function (obj, asString) {
  30019. if (asString === void 0) { asString = true; }
  30020. if (!obj._tags) {
  30021. return null;
  30022. }
  30023. if (asString) {
  30024. var tagsArray = [];
  30025. for (var tag in obj._tags) {
  30026. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  30027. tagsArray.push(tag);
  30028. }
  30029. }
  30030. return tagsArray.join(" ");
  30031. }
  30032. else {
  30033. return obj._tags;
  30034. }
  30035. };
  30036. // the tags 'true' and 'false' are reserved and cannot be used as tags
  30037. // a tag cannot start with '||', '&&', and '!'
  30038. // it cannot contain whitespaces
  30039. Tags.AddTagsTo = function (obj, tagsString) {
  30040. if (!tagsString) {
  30041. return;
  30042. }
  30043. if (typeof tagsString !== "string") {
  30044. return;
  30045. }
  30046. var tags = tagsString.split(" ");
  30047. for (var t in tags) {
  30048. Tags._AddTagTo(obj, tags[t]);
  30049. }
  30050. };
  30051. Tags._AddTagTo = function (obj, tag) {
  30052. tag = tag.trim();
  30053. if (tag === "" || tag === "true" || tag === "false") {
  30054. return;
  30055. }
  30056. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  30057. return;
  30058. }
  30059. Tags.EnableFor(obj);
  30060. obj._tags[tag] = true;
  30061. };
  30062. Tags.RemoveTagsFrom = function (obj, tagsString) {
  30063. if (!Tags.HasTags(obj)) {
  30064. return;
  30065. }
  30066. var tags = tagsString.split(" ");
  30067. for (var t in tags) {
  30068. Tags._RemoveTagFrom(obj, tags[t]);
  30069. }
  30070. };
  30071. Tags._RemoveTagFrom = function (obj, tag) {
  30072. delete obj._tags[tag];
  30073. };
  30074. Tags.MatchesQuery = function (obj, tagsQuery) {
  30075. if (tagsQuery === undefined) {
  30076. return true;
  30077. }
  30078. if (tagsQuery === "") {
  30079. return Tags.HasTags(obj);
  30080. }
  30081. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  30082. };
  30083. return Tags;
  30084. })();
  30085. BABYLON.Tags = Tags;
  30086. })(BABYLON || (BABYLON = {}));
  30087. var BABYLON;
  30088. (function (BABYLON) {
  30089. var Internals;
  30090. (function (Internals) {
  30091. var AndOrNotEvaluator = (function () {
  30092. function AndOrNotEvaluator() {
  30093. }
  30094. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  30095. if (!query.match(/\([^\(\)]*\)/g)) {
  30096. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  30097. }
  30098. else {
  30099. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  30100. // remove parenthesis
  30101. r = r.slice(1, r.length - 1);
  30102. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  30103. });
  30104. }
  30105. if (query === "true") {
  30106. return true;
  30107. }
  30108. if (query === "false") {
  30109. return false;
  30110. }
  30111. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  30112. };
  30113. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  30114. evaluateCallback = evaluateCallback || (function (r) {
  30115. return r === "true" ? true : false;
  30116. });
  30117. var result;
  30118. var or = parenthesisContent.split("||");
  30119. for (var i in or) {
  30120. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  30121. var and = ori.split("&&");
  30122. if (and.length > 1) {
  30123. for (var j = 0; j < and.length; ++j) {
  30124. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  30125. if (andj !== "true" && andj !== "false") {
  30126. if (andj[0] === "!") {
  30127. result = !evaluateCallback(andj.substring(1));
  30128. }
  30129. else {
  30130. result = evaluateCallback(andj);
  30131. }
  30132. }
  30133. else {
  30134. result = andj === "true" ? true : false;
  30135. }
  30136. if (!result) {
  30137. ori = "false";
  30138. break;
  30139. }
  30140. }
  30141. }
  30142. if (result || ori === "true") {
  30143. result = true;
  30144. break;
  30145. }
  30146. // result equals false (or undefined)
  30147. if (ori !== "true" && ori !== "false") {
  30148. if (ori[0] === "!") {
  30149. result = !evaluateCallback(ori.substring(1));
  30150. }
  30151. else {
  30152. result = evaluateCallback(ori);
  30153. }
  30154. }
  30155. else {
  30156. result = ori === "true" ? true : false;
  30157. }
  30158. }
  30159. // the whole parenthesis scope is replaced by 'true' or 'false'
  30160. return result ? "true" : "false";
  30161. };
  30162. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  30163. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  30164. // remove whitespaces
  30165. r = r.replace(/[\s]/g, function () { return ""; });
  30166. return r.length % 2 ? "!" : "";
  30167. });
  30168. booleanString = booleanString.trim();
  30169. if (booleanString === "!true") {
  30170. booleanString = "false";
  30171. }
  30172. else if (booleanString === "!false") {
  30173. booleanString = "true";
  30174. }
  30175. return booleanString;
  30176. };
  30177. return AndOrNotEvaluator;
  30178. })();
  30179. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  30180. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30181. })(BABYLON || (BABYLON = {}));
  30182. var BABYLON;
  30183. (function (BABYLON) {
  30184. var PostProcessRenderPass = (function () {
  30185. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  30186. this._enabled = true;
  30187. this._refCount = 0;
  30188. this._name = name;
  30189. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  30190. this.setRenderList(renderList);
  30191. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  30192. this._renderTexture.onAfterRenderObservable.add(afterRender);
  30193. this._scene = scene;
  30194. this._renderList = renderList;
  30195. }
  30196. // private
  30197. PostProcessRenderPass.prototype._incRefCount = function () {
  30198. if (this._refCount === 0) {
  30199. this._scene.customRenderTargets.push(this._renderTexture);
  30200. }
  30201. return ++this._refCount;
  30202. };
  30203. PostProcessRenderPass.prototype._decRefCount = function () {
  30204. this._refCount--;
  30205. if (this._refCount <= 0) {
  30206. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  30207. }
  30208. return this._refCount;
  30209. };
  30210. PostProcessRenderPass.prototype._update = function () {
  30211. this.setRenderList(this._renderList);
  30212. };
  30213. // public
  30214. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  30215. this._renderTexture.renderList = renderList;
  30216. };
  30217. PostProcessRenderPass.prototype.getRenderTexture = function () {
  30218. return this._renderTexture;
  30219. };
  30220. return PostProcessRenderPass;
  30221. })();
  30222. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  30223. })(BABYLON || (BABYLON = {}));
  30224. var BABYLON;
  30225. (function (BABYLON) {
  30226. var PostProcessRenderEffect = (function () {
  30227. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  30228. this._engine = engine;
  30229. this._name = name;
  30230. this._singleInstance = singleInstance || true;
  30231. this._getPostProcess = getPostProcess;
  30232. this._cameras = [];
  30233. this._indicesForCamera = [];
  30234. this._postProcesses = {};
  30235. this._renderPasses = {};
  30236. this._renderEffectAsPasses = {};
  30237. }
  30238. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  30239. get: function () {
  30240. for (var index in this._postProcesses) {
  30241. if (!this._postProcesses[index].isSupported) {
  30242. return false;
  30243. }
  30244. }
  30245. return true;
  30246. },
  30247. enumerable: true,
  30248. configurable: true
  30249. });
  30250. PostProcessRenderEffect.prototype._update = function () {
  30251. for (var renderPassName in this._renderPasses) {
  30252. this._renderPasses[renderPassName]._update();
  30253. }
  30254. };
  30255. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  30256. this._renderPasses[renderPass._name] = renderPass;
  30257. this._linkParameters();
  30258. };
  30259. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  30260. delete this._renderPasses[renderPass._name];
  30261. this._linkParameters();
  30262. };
  30263. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  30264. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  30265. this._linkParameters();
  30266. };
  30267. PostProcessRenderEffect.prototype.getPass = function (passName) {
  30268. for (var renderPassName in this._renderPasses) {
  30269. if (renderPassName === passName) {
  30270. return this._renderPasses[passName];
  30271. }
  30272. }
  30273. };
  30274. PostProcessRenderEffect.prototype.emptyPasses = function () {
  30275. this._renderPasses = {};
  30276. this._linkParameters();
  30277. };
  30278. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  30279. var cameraKey;
  30280. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30281. for (var i = 0; i < _cam.length; i++) {
  30282. var camera = _cam[i];
  30283. var cameraName = camera.name;
  30284. if (this._singleInstance) {
  30285. cameraKey = 0;
  30286. }
  30287. else {
  30288. cameraKey = cameraName;
  30289. }
  30290. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  30291. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  30292. if (!this._indicesForCamera[cameraName]) {
  30293. this._indicesForCamera[cameraName] = [];
  30294. }
  30295. this._indicesForCamera[cameraName].push(index);
  30296. if (this._cameras.indexOf(camera) === -1) {
  30297. this._cameras[cameraName] = camera;
  30298. }
  30299. for (var passName in this._renderPasses) {
  30300. this._renderPasses[passName]._incRefCount();
  30301. }
  30302. }
  30303. this._linkParameters();
  30304. };
  30305. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  30306. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30307. for (var i = 0; i < _cam.length; i++) {
  30308. var camera = _cam[i];
  30309. var cameraName = camera.name;
  30310. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30311. var index = this._cameras.indexOf(cameraName);
  30312. this._indicesForCamera.splice(index, 1);
  30313. this._cameras.splice(index, 1);
  30314. for (var passName in this._renderPasses) {
  30315. this._renderPasses[passName]._decRefCount();
  30316. }
  30317. }
  30318. };
  30319. PostProcessRenderEffect.prototype._enable = function (cameras) {
  30320. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30321. for (var i = 0; i < _cam.length; i++) {
  30322. var camera = _cam[i];
  30323. var cameraName = camera.name;
  30324. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  30325. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  30326. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  30327. }
  30328. }
  30329. for (var passName in this._renderPasses) {
  30330. this._renderPasses[passName]._incRefCount();
  30331. }
  30332. }
  30333. };
  30334. PostProcessRenderEffect.prototype._disable = function (cameras) {
  30335. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30336. for (var i = 0; i < _cam.length; i++) {
  30337. var camera = _cam[i];
  30338. var cameraName = camera.Name;
  30339. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30340. for (var passName in this._renderPasses) {
  30341. this._renderPasses[passName]._decRefCount();
  30342. }
  30343. }
  30344. };
  30345. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  30346. if (this._singleInstance) {
  30347. return this._postProcesses[0];
  30348. }
  30349. else {
  30350. return this._postProcesses[camera.name];
  30351. }
  30352. };
  30353. PostProcessRenderEffect.prototype._linkParameters = function () {
  30354. var _this = this;
  30355. for (var index in this._postProcesses) {
  30356. if (this.applyParameters) {
  30357. this.applyParameters(this._postProcesses[index]);
  30358. }
  30359. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  30360. _this._linkTextures(effect);
  30361. });
  30362. }
  30363. };
  30364. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  30365. for (var renderPassName in this._renderPasses) {
  30366. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  30367. }
  30368. for (var renderEffectName in this._renderEffectAsPasses) {
  30369. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  30370. }
  30371. };
  30372. return PostProcessRenderEffect;
  30373. })();
  30374. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  30375. })(BABYLON || (BABYLON = {}));
  30376. var BABYLON;
  30377. (function (BABYLON) {
  30378. var PostProcessRenderPipeline = (function () {
  30379. function PostProcessRenderPipeline(engine, name) {
  30380. this._engine = engine;
  30381. this._name = name;
  30382. this._renderEffects = {};
  30383. this._renderEffectsForIsolatedPass = {};
  30384. this._cameras = [];
  30385. }
  30386. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  30387. get: function () {
  30388. for (var renderEffectName in this._renderEffects) {
  30389. if (!this._renderEffects[renderEffectName].isSupported) {
  30390. return false;
  30391. }
  30392. }
  30393. return true;
  30394. },
  30395. enumerable: true,
  30396. configurable: true
  30397. });
  30398. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  30399. this._renderEffects[renderEffect._name] = renderEffect;
  30400. };
  30401. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  30402. var renderEffects = this._renderEffects[renderEffectName];
  30403. if (!renderEffects) {
  30404. return;
  30405. }
  30406. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30407. };
  30408. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  30409. var renderEffects = this._renderEffects[renderEffectName];
  30410. if (!renderEffects) {
  30411. return;
  30412. }
  30413. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30414. };
  30415. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  30416. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30417. var indicesToDelete = [];
  30418. var i;
  30419. for (i = 0; i < _cam.length; i++) {
  30420. var camera = _cam[i];
  30421. var cameraName = camera.name;
  30422. if (this._cameras.indexOf(camera) === -1) {
  30423. this._cameras[cameraName] = camera;
  30424. }
  30425. else if (unique) {
  30426. indicesToDelete.push(i);
  30427. }
  30428. }
  30429. for (i = 0; i < indicesToDelete.length; i++) {
  30430. cameras.splice(indicesToDelete[i], 1);
  30431. }
  30432. for (var renderEffectName in this._renderEffects) {
  30433. this._renderEffects[renderEffectName]._attachCameras(_cam);
  30434. }
  30435. };
  30436. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  30437. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30438. for (var renderEffectName in this._renderEffects) {
  30439. this._renderEffects[renderEffectName]._detachCameras(_cam);
  30440. }
  30441. for (var i = 0; i < _cam.length; i++) {
  30442. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  30443. }
  30444. };
  30445. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  30446. var _this = this;
  30447. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30448. var pass = null;
  30449. var renderEffectName;
  30450. for (renderEffectName in this._renderEffects) {
  30451. pass = this._renderEffects[renderEffectName].getPass(passName);
  30452. if (pass != null) {
  30453. break;
  30454. }
  30455. }
  30456. if (pass === null) {
  30457. return;
  30458. }
  30459. for (renderEffectName in this._renderEffects) {
  30460. this._renderEffects[renderEffectName]._disable(_cam);
  30461. }
  30462. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  30463. for (var i = 0; i < _cam.length; i++) {
  30464. var camera = _cam[i];
  30465. var cameraName = camera.name;
  30466. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  30467. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  30468. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  30469. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  30470. }
  30471. };
  30472. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  30473. var _this = this;
  30474. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30475. for (var i = 0; i < _cam.length; i++) {
  30476. var camera = _cam[i];
  30477. var cameraName = camera.name;
  30478. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  30479. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  30480. }
  30481. for (var renderEffectName in this._renderEffects) {
  30482. this._renderEffects[renderEffectName]._enable(_cam);
  30483. }
  30484. };
  30485. PostProcessRenderPipeline.prototype._update = function () {
  30486. for (var renderEffectName in this._renderEffects) {
  30487. this._renderEffects[renderEffectName]._update();
  30488. }
  30489. for (var i = 0; i < this._cameras.length; i++) {
  30490. var cameraName = this._cameras[i].name;
  30491. if (this._renderEffectsForIsolatedPass[cameraName]) {
  30492. this._renderEffectsForIsolatedPass[cameraName]._update();
  30493. }
  30494. }
  30495. };
  30496. PostProcessRenderPipeline.prototype.dispose = function () {
  30497. // Must be implemented by children
  30498. };
  30499. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  30500. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  30501. return PostProcessRenderPipeline;
  30502. })();
  30503. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  30504. })(BABYLON || (BABYLON = {}));
  30505. var BABYLON;
  30506. (function (BABYLON) {
  30507. var PostProcessRenderPipelineManager = (function () {
  30508. function PostProcessRenderPipelineManager() {
  30509. this._renderPipelines = {};
  30510. }
  30511. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  30512. this._renderPipelines[renderPipeline._name] = renderPipeline;
  30513. };
  30514. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  30515. var renderPipeline = this._renderPipelines[renderPipelineName];
  30516. if (!renderPipeline) {
  30517. return;
  30518. }
  30519. renderPipeline._attachCameras(cameras, unique);
  30520. };
  30521. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  30522. var renderPipeline = this._renderPipelines[renderPipelineName];
  30523. if (!renderPipeline) {
  30524. return;
  30525. }
  30526. renderPipeline._detachCameras(cameras);
  30527. };
  30528. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30529. var renderPipeline = this._renderPipelines[renderPipelineName];
  30530. if (!renderPipeline) {
  30531. return;
  30532. }
  30533. renderPipeline._enableEffect(renderEffectName, cameras);
  30534. };
  30535. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30536. var renderPipeline = this._renderPipelines[renderPipelineName];
  30537. if (!renderPipeline) {
  30538. return;
  30539. }
  30540. renderPipeline._disableEffect(renderEffectName, cameras);
  30541. };
  30542. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  30543. var renderPipeline = this._renderPipelines[renderPipelineName];
  30544. if (!renderPipeline) {
  30545. return;
  30546. }
  30547. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  30548. };
  30549. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  30550. var renderPipeline = this._renderPipelines[renderPipelineName];
  30551. if (!renderPipeline) {
  30552. return;
  30553. }
  30554. renderPipeline._disableDisplayOnlyPass(cameras);
  30555. };
  30556. PostProcessRenderPipelineManager.prototype.update = function () {
  30557. for (var renderPipelineName in this._renderPipelines) {
  30558. var pipeline = this._renderPipelines[renderPipelineName];
  30559. if (!pipeline.isSupported) {
  30560. pipeline.dispose();
  30561. delete this._renderPipelines[renderPipelineName];
  30562. }
  30563. else {
  30564. pipeline._update();
  30565. }
  30566. }
  30567. };
  30568. return PostProcessRenderPipelineManager;
  30569. })();
  30570. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  30571. })(BABYLON || (BABYLON = {}));
  30572. var BABYLON;
  30573. (function (BABYLON) {
  30574. var BoundingBoxRenderer = (function () {
  30575. function BoundingBoxRenderer(scene) {
  30576. this.frontColor = new BABYLON.Color3(1, 1, 1);
  30577. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  30578. this.showBackLines = true;
  30579. this.renderList = new BABYLON.SmartArray(32);
  30580. this._scene = scene;
  30581. }
  30582. BoundingBoxRenderer.prototype._prepareRessources = function () {
  30583. if (this._colorShader) {
  30584. return;
  30585. }
  30586. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  30587. attributes: ["position"],
  30588. uniforms: ["worldViewProjection", "color"]
  30589. });
  30590. var engine = this._scene.getEngine();
  30591. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  30592. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  30593. this._ib = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  30594. };
  30595. BoundingBoxRenderer.prototype.reset = function () {
  30596. this.renderList.reset();
  30597. };
  30598. BoundingBoxRenderer.prototype.render = function () {
  30599. if (this.renderList.length === 0) {
  30600. return;
  30601. }
  30602. this._prepareRessources();
  30603. if (!this._colorShader.isReady()) {
  30604. return;
  30605. }
  30606. var engine = this._scene.getEngine();
  30607. engine.setDepthWrite(false);
  30608. this._colorShader._preBind();
  30609. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  30610. var boundingBox = this.renderList.data[boundingBoxIndex];
  30611. var min = boundingBox.minimum;
  30612. var max = boundingBox.maximum;
  30613. var diff = max.subtract(min);
  30614. var median = min.add(diff.scale(0.5));
  30615. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  30616. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  30617. .multiply(boundingBox.getWorldMatrix());
  30618. // VBOs
  30619. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  30620. if (this.showBackLines) {
  30621. // Back
  30622. engine.setDepthFunctionToGreaterOrEqual();
  30623. this._scene.resetCachedMaterial();
  30624. this._colorShader.setColor4("color", this.backColor.toColor4());
  30625. this._colorShader.bind(worldMatrix);
  30626. // Draw order
  30627. engine.draw(false, 0, 24);
  30628. }
  30629. // Front
  30630. engine.setDepthFunctionToLess();
  30631. this._scene.resetCachedMaterial();
  30632. this._colorShader.setColor4("color", this.frontColor.toColor4());
  30633. this._colorShader.bind(worldMatrix);
  30634. // Draw order
  30635. engine.draw(false, 0, 24);
  30636. }
  30637. this._colorShader.unbind();
  30638. engine.setDepthFunctionToLessOrEqual();
  30639. engine.setDepthWrite(true);
  30640. };
  30641. BoundingBoxRenderer.prototype.dispose = function () {
  30642. if (!this._colorShader) {
  30643. return;
  30644. }
  30645. this._colorShader.dispose();
  30646. this._vb.dispose();
  30647. this._scene.getEngine()._releaseBuffer(this._ib);
  30648. };
  30649. return BoundingBoxRenderer;
  30650. })();
  30651. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  30652. })(BABYLON || (BABYLON = {}));
  30653. var BABYLON;
  30654. (function (BABYLON) {
  30655. var Condition = (function () {
  30656. function Condition(actionManager) {
  30657. this._actionManager = actionManager;
  30658. }
  30659. Condition.prototype.isValid = function () {
  30660. return true;
  30661. };
  30662. Condition.prototype._getProperty = function (propertyPath) {
  30663. return this._actionManager._getProperty(propertyPath);
  30664. };
  30665. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  30666. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30667. };
  30668. Condition.prototype.serialize = function () {
  30669. };
  30670. Condition.prototype._serialize = function (serializedCondition) {
  30671. return {
  30672. type: 2,
  30673. children: [],
  30674. name: serializedCondition.name,
  30675. properties: serializedCondition.properties
  30676. };
  30677. };
  30678. return Condition;
  30679. })();
  30680. BABYLON.Condition = Condition;
  30681. var ValueCondition = (function (_super) {
  30682. __extends(ValueCondition, _super);
  30683. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  30684. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  30685. _super.call(this, actionManager);
  30686. this.propertyPath = propertyPath;
  30687. this.value = value;
  30688. this.operator = operator;
  30689. this._target = target;
  30690. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  30691. this._property = this._getProperty(this.propertyPath);
  30692. }
  30693. Object.defineProperty(ValueCondition, "IsEqual", {
  30694. get: function () {
  30695. return ValueCondition._IsEqual;
  30696. },
  30697. enumerable: true,
  30698. configurable: true
  30699. });
  30700. Object.defineProperty(ValueCondition, "IsDifferent", {
  30701. get: function () {
  30702. return ValueCondition._IsDifferent;
  30703. },
  30704. enumerable: true,
  30705. configurable: true
  30706. });
  30707. Object.defineProperty(ValueCondition, "IsGreater", {
  30708. get: function () {
  30709. return ValueCondition._IsGreater;
  30710. },
  30711. enumerable: true,
  30712. configurable: true
  30713. });
  30714. Object.defineProperty(ValueCondition, "IsLesser", {
  30715. get: function () {
  30716. return ValueCondition._IsLesser;
  30717. },
  30718. enumerable: true,
  30719. configurable: true
  30720. });
  30721. // Methods
  30722. ValueCondition.prototype.isValid = function () {
  30723. switch (this.operator) {
  30724. case ValueCondition.IsGreater:
  30725. return this._effectiveTarget[this._property] > this.value;
  30726. case ValueCondition.IsLesser:
  30727. return this._effectiveTarget[this._property] < this.value;
  30728. case ValueCondition.IsEqual:
  30729. case ValueCondition.IsDifferent:
  30730. var check;
  30731. if (this.value.equals) {
  30732. check = this.value.equals(this._effectiveTarget[this._property]);
  30733. }
  30734. else {
  30735. check = this.value === this._effectiveTarget[this._property];
  30736. }
  30737. return this.operator === ValueCondition.IsEqual ? check : !check;
  30738. }
  30739. return false;
  30740. };
  30741. ValueCondition.prototype.serialize = function () {
  30742. return this._serialize({
  30743. name: "ValueCondition",
  30744. properties: [
  30745. BABYLON.Action._GetTargetProperty(this._target),
  30746. { name: "propertyPath", value: this.propertyPath },
  30747. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  30748. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  30749. ]
  30750. });
  30751. };
  30752. ValueCondition.GetOperatorName = function (operator) {
  30753. switch (operator) {
  30754. case ValueCondition._IsEqual: return "IsEqual";
  30755. case ValueCondition._IsDifferent: return "IsDifferent";
  30756. case ValueCondition._IsGreater: return "IsGreater";
  30757. case ValueCondition._IsLesser: return "IsLesser";
  30758. default: return "";
  30759. }
  30760. };
  30761. // Statics
  30762. ValueCondition._IsEqual = 0;
  30763. ValueCondition._IsDifferent = 1;
  30764. ValueCondition._IsGreater = 2;
  30765. ValueCondition._IsLesser = 3;
  30766. return ValueCondition;
  30767. })(Condition);
  30768. BABYLON.ValueCondition = ValueCondition;
  30769. var PredicateCondition = (function (_super) {
  30770. __extends(PredicateCondition, _super);
  30771. function PredicateCondition(actionManager, predicate) {
  30772. _super.call(this, actionManager);
  30773. this.predicate = predicate;
  30774. }
  30775. PredicateCondition.prototype.isValid = function () {
  30776. return this.predicate();
  30777. };
  30778. return PredicateCondition;
  30779. })(Condition);
  30780. BABYLON.PredicateCondition = PredicateCondition;
  30781. var StateCondition = (function (_super) {
  30782. __extends(StateCondition, _super);
  30783. function StateCondition(actionManager, target, value) {
  30784. _super.call(this, actionManager);
  30785. this.value = value;
  30786. this._target = target;
  30787. }
  30788. // Methods
  30789. StateCondition.prototype.isValid = function () {
  30790. return this._target.state === this.value;
  30791. };
  30792. StateCondition.prototype.serialize = function () {
  30793. return this._serialize({
  30794. name: "StateCondition",
  30795. properties: [
  30796. BABYLON.Action._GetTargetProperty(this._target),
  30797. { name: "value", value: this.value }
  30798. ]
  30799. });
  30800. };
  30801. return StateCondition;
  30802. })(Condition);
  30803. BABYLON.StateCondition = StateCondition;
  30804. })(BABYLON || (BABYLON = {}));
  30805. var BABYLON;
  30806. (function (BABYLON) {
  30807. var Action = (function () {
  30808. function Action(triggerOptions, condition) {
  30809. this.triggerOptions = triggerOptions;
  30810. if (triggerOptions.parameter) {
  30811. this.trigger = triggerOptions.trigger;
  30812. this._triggerParameter = triggerOptions.parameter;
  30813. }
  30814. else {
  30815. this.trigger = triggerOptions;
  30816. }
  30817. this._nextActiveAction = this;
  30818. this._condition = condition;
  30819. }
  30820. // Methods
  30821. Action.prototype._prepare = function () {
  30822. };
  30823. Action.prototype.getTriggerParameter = function () {
  30824. return this._triggerParameter;
  30825. };
  30826. Action.prototype._executeCurrent = function (evt) {
  30827. if (this._nextActiveAction._condition) {
  30828. var condition = this._nextActiveAction._condition;
  30829. var currentRenderId = this._actionManager.getScene().getRenderId();
  30830. // We cache the current evaluation for the current frame
  30831. if (condition._evaluationId === currentRenderId) {
  30832. if (!condition._currentResult) {
  30833. return;
  30834. }
  30835. }
  30836. else {
  30837. condition._evaluationId = currentRenderId;
  30838. if (!condition.isValid()) {
  30839. condition._currentResult = false;
  30840. return;
  30841. }
  30842. condition._currentResult = true;
  30843. }
  30844. }
  30845. this._nextActiveAction.execute(evt);
  30846. this.skipToNextActiveAction();
  30847. };
  30848. Action.prototype.execute = function (evt) {
  30849. };
  30850. Action.prototype.skipToNextActiveAction = function () {
  30851. if (this._nextActiveAction._child) {
  30852. if (!this._nextActiveAction._child._actionManager) {
  30853. this._nextActiveAction._child._actionManager = this._actionManager;
  30854. }
  30855. this._nextActiveAction = this._nextActiveAction._child;
  30856. }
  30857. else {
  30858. this._nextActiveAction = this;
  30859. }
  30860. };
  30861. Action.prototype.then = function (action) {
  30862. this._child = action;
  30863. action._actionManager = this._actionManager;
  30864. action._prepare();
  30865. return action;
  30866. };
  30867. Action.prototype._getProperty = function (propertyPath) {
  30868. return this._actionManager._getProperty(propertyPath);
  30869. };
  30870. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  30871. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30872. };
  30873. Action.prototype.serialize = function (parent) {
  30874. };
  30875. // Called by BABYLON.Action objects in serialize(...). Internal use
  30876. Action.prototype._serialize = function (serializedAction, parent) {
  30877. var serializationObject = {
  30878. type: 1,
  30879. children: [],
  30880. name: serializedAction.name,
  30881. properties: serializedAction.properties || []
  30882. };
  30883. // Serialize child
  30884. if (this._child) {
  30885. this._child.serialize(serializationObject);
  30886. }
  30887. // Check if "this" has a condition
  30888. if (this._condition) {
  30889. var serializedCondition = this._condition.serialize();
  30890. serializedCondition.children.push(serializationObject);
  30891. if (parent) {
  30892. parent.children.push(serializedCondition);
  30893. }
  30894. return serializedCondition;
  30895. }
  30896. if (parent) {
  30897. parent.children.push(serializationObject);
  30898. }
  30899. return serializationObject;
  30900. };
  30901. Action._SerializeValueAsString = function (value) {
  30902. if (typeof value === "number") {
  30903. return value.toString();
  30904. }
  30905. if (typeof value === "boolean") {
  30906. return value ? "true" : "false";
  30907. }
  30908. if (value instanceof BABYLON.Vector2) {
  30909. return value.x + ", " + value.y;
  30910. }
  30911. if (value instanceof BABYLON.Vector3) {
  30912. return value.x + ", " + value.y + ", " + value.z;
  30913. }
  30914. if (value instanceof BABYLON.Color3) {
  30915. return value.r + ", " + value.g + ", " + value.b;
  30916. }
  30917. if (value instanceof BABYLON.Color4) {
  30918. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  30919. }
  30920. return value; // string
  30921. };
  30922. Action._GetTargetProperty = function (target) {
  30923. return {
  30924. name: "target",
  30925. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  30926. : target instanceof BABYLON.Light ? "LightProperties"
  30927. : target instanceof BABYLON.Camera ? "CameraProperties"
  30928. : "SceneProperties",
  30929. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  30930. };
  30931. };
  30932. return Action;
  30933. })();
  30934. BABYLON.Action = Action;
  30935. })(BABYLON || (BABYLON = {}));
  30936. var BABYLON;
  30937. (function (BABYLON) {
  30938. /**
  30939. * ActionEvent is the event beint sent when an action is triggered.
  30940. */
  30941. var ActionEvent = (function () {
  30942. /**
  30943. * @constructor
  30944. * @param source The mesh or sprite that triggered the action.
  30945. * @param pointerX The X mouse cursor position at the time of the event
  30946. * @param pointerY The Y mouse cursor position at the time of the event
  30947. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30948. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30949. */
  30950. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30951. this.source = source;
  30952. this.pointerX = pointerX;
  30953. this.pointerY = pointerY;
  30954. this.meshUnderPointer = meshUnderPointer;
  30955. this.sourceEvent = sourceEvent;
  30956. this.additionalData = additionalData;
  30957. }
  30958. /**
  30959. * Helper function to auto-create an ActionEvent from a source mesh.
  30960. * @param source The source mesh that triggered the event
  30961. * @param evt {Event} The original (browser) event
  30962. */
  30963. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30964. var scene = source.getScene();
  30965. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30966. };
  30967. /**
  30968. * Helper function to auto-create an ActionEvent from a source mesh.
  30969. * @param source The source sprite that triggered the event
  30970. * @param scene Scene associated with the sprite
  30971. * @param evt {Event} The original (browser) event
  30972. */
  30973. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30974. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30975. };
  30976. /**
  30977. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30978. * @param scene the scene where the event occurred
  30979. * @param evt {Event} The original (browser) event
  30980. */
  30981. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30982. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30983. };
  30984. return ActionEvent;
  30985. })();
  30986. BABYLON.ActionEvent = ActionEvent;
  30987. /**
  30988. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30989. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30990. */
  30991. var ActionManager = (function () {
  30992. function ActionManager(scene) {
  30993. // Members
  30994. this.actions = new Array();
  30995. this._scene = scene;
  30996. scene._actionManagers.push(this);
  30997. }
  30998. Object.defineProperty(ActionManager, "NothingTrigger", {
  30999. get: function () {
  31000. return ActionManager._NothingTrigger;
  31001. },
  31002. enumerable: true,
  31003. configurable: true
  31004. });
  31005. Object.defineProperty(ActionManager, "OnPickTrigger", {
  31006. get: function () {
  31007. return ActionManager._OnPickTrigger;
  31008. },
  31009. enumerable: true,
  31010. configurable: true
  31011. });
  31012. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  31013. get: function () {
  31014. return ActionManager._OnLeftPickTrigger;
  31015. },
  31016. enumerable: true,
  31017. configurable: true
  31018. });
  31019. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  31020. get: function () {
  31021. return ActionManager._OnRightPickTrigger;
  31022. },
  31023. enumerable: true,
  31024. configurable: true
  31025. });
  31026. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  31027. get: function () {
  31028. return ActionManager._OnCenterPickTrigger;
  31029. },
  31030. enumerable: true,
  31031. configurable: true
  31032. });
  31033. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  31034. get: function () {
  31035. return ActionManager._OnPickDownTrigger;
  31036. },
  31037. enumerable: true,
  31038. configurable: true
  31039. });
  31040. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  31041. get: function () {
  31042. return ActionManager._OnPickUpTrigger;
  31043. },
  31044. enumerable: true,
  31045. configurable: true
  31046. });
  31047. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  31048. /// This trigger will only be raised if you also declared a OnPickDown
  31049. get: function () {
  31050. return ActionManager._OnPickOutTrigger;
  31051. },
  31052. enumerable: true,
  31053. configurable: true
  31054. });
  31055. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  31056. get: function () {
  31057. return ActionManager._OnLongPressTrigger;
  31058. },
  31059. enumerable: true,
  31060. configurable: true
  31061. });
  31062. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  31063. get: function () {
  31064. return ActionManager._OnPointerOverTrigger;
  31065. },
  31066. enumerable: true,
  31067. configurable: true
  31068. });
  31069. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  31070. get: function () {
  31071. return ActionManager._OnPointerOutTrigger;
  31072. },
  31073. enumerable: true,
  31074. configurable: true
  31075. });
  31076. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  31077. get: function () {
  31078. return ActionManager._OnEveryFrameTrigger;
  31079. },
  31080. enumerable: true,
  31081. configurable: true
  31082. });
  31083. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  31084. get: function () {
  31085. return ActionManager._OnIntersectionEnterTrigger;
  31086. },
  31087. enumerable: true,
  31088. configurable: true
  31089. });
  31090. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  31091. get: function () {
  31092. return ActionManager._OnIntersectionExitTrigger;
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  31098. get: function () {
  31099. return ActionManager._OnKeyDownTrigger;
  31100. },
  31101. enumerable: true,
  31102. configurable: true
  31103. });
  31104. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  31105. get: function () {
  31106. return ActionManager._OnKeyUpTrigger;
  31107. },
  31108. enumerable: true,
  31109. configurable: true
  31110. });
  31111. // Methods
  31112. ActionManager.prototype.dispose = function () {
  31113. var index = this._scene._actionManagers.indexOf(this);
  31114. if (index > -1) {
  31115. this._scene._actionManagers.splice(index, 1);
  31116. }
  31117. };
  31118. ActionManager.prototype.getScene = function () {
  31119. return this._scene;
  31120. };
  31121. /**
  31122. * Does this action manager handles actions of any of the given triggers
  31123. * @param {number[]} triggers - the triggers to be tested
  31124. * @return {boolean} whether one (or more) of the triggers is handeled
  31125. */
  31126. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  31127. for (var index = 0; index < this.actions.length; index++) {
  31128. var action = this.actions[index];
  31129. if (triggers.indexOf(action.trigger) > -1) {
  31130. return true;
  31131. }
  31132. }
  31133. return false;
  31134. };
  31135. /**
  31136. * Does this action manager handles actions of a given trigger
  31137. * @param {number} trigger - the trigger to be tested
  31138. * @return {boolean} whether the trigger is handeled
  31139. */
  31140. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  31141. for (var index = 0; index < this.actions.length; index++) {
  31142. var action = this.actions[index];
  31143. if (action.trigger === trigger) {
  31144. return true;
  31145. }
  31146. }
  31147. return false;
  31148. };
  31149. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  31150. /**
  31151. * Does this action manager has pointer triggers
  31152. * @return {boolean} whether or not it has pointer triggers
  31153. */
  31154. get: function () {
  31155. for (var index = 0; index < this.actions.length; index++) {
  31156. var action = this.actions[index];
  31157. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  31158. return true;
  31159. }
  31160. }
  31161. return false;
  31162. },
  31163. enumerable: true,
  31164. configurable: true
  31165. });
  31166. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  31167. /**
  31168. * Does this action manager has pick triggers
  31169. * @return {boolean} whether or not it has pick triggers
  31170. */
  31171. get: function () {
  31172. for (var index = 0; index < this.actions.length; index++) {
  31173. var action = this.actions[index];
  31174. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  31175. return true;
  31176. }
  31177. }
  31178. return false;
  31179. },
  31180. enumerable: true,
  31181. configurable: true
  31182. });
  31183. /**
  31184. * Registers an action to this action manager
  31185. * @param {BABYLON.Action} action - the action to be registered
  31186. * @return {BABYLON.Action} the action amended (prepared) after registration
  31187. */
  31188. ActionManager.prototype.registerAction = function (action) {
  31189. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  31190. if (this.getScene().actionManager !== this) {
  31191. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  31192. return null;
  31193. }
  31194. }
  31195. this.actions.push(action);
  31196. action._actionManager = this;
  31197. action._prepare();
  31198. return action;
  31199. };
  31200. /**
  31201. * Process a specific trigger
  31202. * @param {number} trigger - the trigger to process
  31203. * @param evt {BABYLON.ActionEvent} the event details to be processed
  31204. */
  31205. ActionManager.prototype.processTrigger = function (trigger, evt) {
  31206. for (var index = 0; index < this.actions.length; index++) {
  31207. var action = this.actions[index];
  31208. if (action.trigger === trigger) {
  31209. if (trigger === ActionManager.OnKeyUpTrigger
  31210. || trigger === ActionManager.OnKeyDownTrigger) {
  31211. var parameter = action.getTriggerParameter();
  31212. if (parameter) {
  31213. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  31214. var actualkey = String.fromCharCode(unicode).toLowerCase();
  31215. if (actualkey !== parameter.toLowerCase()) {
  31216. continue;
  31217. }
  31218. }
  31219. }
  31220. action._executeCurrent(evt);
  31221. }
  31222. }
  31223. };
  31224. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  31225. var properties = propertyPath.split(".");
  31226. for (var index = 0; index < properties.length - 1; index++) {
  31227. target = target[properties[index]];
  31228. }
  31229. return target;
  31230. };
  31231. ActionManager.prototype._getProperty = function (propertyPath) {
  31232. var properties = propertyPath.split(".");
  31233. return properties[properties.length - 1];
  31234. };
  31235. ActionManager.prototype.serialize = function (name) {
  31236. var root = {
  31237. children: [],
  31238. name: name,
  31239. type: 3,
  31240. properties: [] // Empty for root but required
  31241. };
  31242. for (var i = 0; i < this.actions.length; i++) {
  31243. var triggerObject = {
  31244. type: 0,
  31245. children: [],
  31246. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  31247. properties: []
  31248. };
  31249. var triggerOptions = this.actions[i].triggerOptions;
  31250. if (triggerOptions && typeof triggerOptions !== "number") {
  31251. if (triggerOptions.parameter instanceof BABYLON.Node) {
  31252. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  31253. }
  31254. else {
  31255. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  31256. }
  31257. }
  31258. // Serialize child action, recursively
  31259. this.actions[i].serialize(triggerObject);
  31260. // Add serialized trigger
  31261. root.children.push(triggerObject);
  31262. }
  31263. return root;
  31264. };
  31265. ActionManager.Parse = function (parsedActions, object, scene) {
  31266. var actionManager = new BABYLON.ActionManager(scene);
  31267. if (object === null)
  31268. scene.actionManager = actionManager;
  31269. else
  31270. object.actionManager = actionManager;
  31271. // instanciate a new object
  31272. var instanciate = function (name, params) {
  31273. var newInstance = Object.create(BABYLON[name].prototype);
  31274. newInstance.constructor.apply(newInstance, params);
  31275. return newInstance;
  31276. };
  31277. var parseParameter = function (name, value, target, propertyPath) {
  31278. if (propertyPath === null) {
  31279. // String, boolean or float
  31280. var floatValue = parseFloat(value);
  31281. if (value === "true" || value === "false")
  31282. return value === "true";
  31283. else
  31284. return isNaN(floatValue) ? value : floatValue;
  31285. }
  31286. var effectiveTarget = propertyPath.split(".");
  31287. var values = value.split(",");
  31288. // Get effective Target
  31289. for (var i = 0; i < effectiveTarget.length; i++) {
  31290. target = target[effectiveTarget[i]];
  31291. }
  31292. // Return appropriate value with its type
  31293. if (typeof (target) === "boolean")
  31294. return values[0] === "true";
  31295. if (typeof (target) === "string")
  31296. return values[0];
  31297. // Parameters with multiple values such as Vector3 etc.
  31298. var split = new Array();
  31299. for (var i = 0; i < values.length; i++)
  31300. split.push(parseFloat(values[i]));
  31301. if (target instanceof BABYLON.Vector3)
  31302. return BABYLON.Vector3.FromArray(split);
  31303. if (target instanceof BABYLON.Vector4)
  31304. return BABYLON.Vector4.FromArray(split);
  31305. if (target instanceof BABYLON.Color3)
  31306. return BABYLON.Color3.FromArray(split);
  31307. if (target instanceof BABYLON.Color4)
  31308. return BABYLON.Color4.FromArray(split);
  31309. return parseFloat(values[0]);
  31310. };
  31311. // traverse graph per trigger
  31312. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  31313. if (combineArray === void 0) { combineArray = null; }
  31314. if (parsedAction.detached)
  31315. return;
  31316. var parameters = new Array();
  31317. var target = null;
  31318. var propertyPath = null;
  31319. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  31320. // Parameters
  31321. if (parsedAction.type === 2)
  31322. parameters.push(actionManager);
  31323. else
  31324. parameters.push(trigger);
  31325. if (combine) {
  31326. var actions = new Array();
  31327. for (var j = 0; j < parsedAction.combine.length; j++) {
  31328. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  31329. }
  31330. parameters.push(actions);
  31331. }
  31332. else {
  31333. for (var i = 0; i < parsedAction.properties.length; i++) {
  31334. var value = parsedAction.properties[i].value;
  31335. var name = parsedAction.properties[i].name;
  31336. var targetType = parsedAction.properties[i].targetType;
  31337. if (name === "target")
  31338. if (targetType !== null && targetType === "SceneProperties")
  31339. value = target = scene;
  31340. else
  31341. value = target = scene.getNodeByName(value);
  31342. else if (name === "parent")
  31343. value = scene.getNodeByName(value);
  31344. else if (name === "sound")
  31345. value = scene.getSoundByName(value);
  31346. else if (name !== "propertyPath") {
  31347. if (parsedAction.type === 2 && name === "operator")
  31348. value = BABYLON.ValueCondition[value];
  31349. else
  31350. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  31351. }
  31352. else {
  31353. propertyPath = value;
  31354. }
  31355. parameters.push(value);
  31356. }
  31357. }
  31358. if (combineArray === null) {
  31359. parameters.push(condition);
  31360. }
  31361. else {
  31362. parameters.push(null);
  31363. }
  31364. // If interpolate value action
  31365. if (parsedAction.name === "InterpolateValueAction") {
  31366. var param = parameters[parameters.length - 2];
  31367. parameters[parameters.length - 1] = param;
  31368. parameters[parameters.length - 2] = condition;
  31369. }
  31370. // Action or condition(s) and not CombineAction
  31371. var newAction = instanciate(parsedAction.name, parameters);
  31372. if (newAction instanceof BABYLON.Condition && condition !== null) {
  31373. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  31374. if (action)
  31375. action.then(nothing);
  31376. else
  31377. actionManager.registerAction(nothing);
  31378. action = nothing;
  31379. }
  31380. if (combineArray === null) {
  31381. if (newAction instanceof BABYLON.Condition) {
  31382. condition = newAction;
  31383. newAction = action;
  31384. }
  31385. else {
  31386. condition = null;
  31387. if (action)
  31388. action.then(newAction);
  31389. else
  31390. actionManager.registerAction(newAction);
  31391. }
  31392. }
  31393. else {
  31394. combineArray.push(newAction);
  31395. }
  31396. for (var i = 0; i < parsedAction.children.length; i++)
  31397. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  31398. };
  31399. // triggers
  31400. for (var i = 0; i < parsedActions.children.length; i++) {
  31401. var triggerParams;
  31402. var trigger = parsedActions.children[i];
  31403. if (trigger.properties.length > 0) {
  31404. var param = trigger.properties[0].value;
  31405. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  31406. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  31407. }
  31408. else
  31409. triggerParams = BABYLON.ActionManager[trigger.name];
  31410. for (var j = 0; j < trigger.children.length; j++) {
  31411. if (!trigger.detached)
  31412. traverse(trigger.children[j], triggerParams, null, null);
  31413. }
  31414. }
  31415. };
  31416. ActionManager.GetTriggerName = function (trigger) {
  31417. switch (trigger) {
  31418. case 0: return "NothingTrigger";
  31419. case 1: return "OnPickTrigger";
  31420. case 2: return "OnLeftPickTrigger";
  31421. case 3: return "OnRightPickTrigger";
  31422. case 4: return "OnCenterPickTrigger";
  31423. case 5: return "OnPickDownTrigger";
  31424. case 6: return "OnPickUpTrigger";
  31425. case 7: return "OnLongPressTrigger";
  31426. case 8: return "OnPointerOverTrigger";
  31427. case 9: return "OnPointerOutTrigger";
  31428. case 10: return "OnEveryFrameTrigger";
  31429. case 11: return "OnIntersectionEnterTrigger";
  31430. case 12: return "OnIntersectionExitTrigger";
  31431. case 13: return "OnKeyDownTrigger";
  31432. case 14: return "OnKeyUpTrigger";
  31433. case 15: return "OnPickOutTrigger";
  31434. default: return "";
  31435. }
  31436. };
  31437. // Statics
  31438. ActionManager._NothingTrigger = 0;
  31439. ActionManager._OnPickTrigger = 1;
  31440. ActionManager._OnLeftPickTrigger = 2;
  31441. ActionManager._OnRightPickTrigger = 3;
  31442. ActionManager._OnCenterPickTrigger = 4;
  31443. ActionManager._OnPickDownTrigger = 5;
  31444. ActionManager._OnPickUpTrigger = 6;
  31445. ActionManager._OnLongPressTrigger = 7;
  31446. ActionManager._OnPointerOverTrigger = 8;
  31447. ActionManager._OnPointerOutTrigger = 9;
  31448. ActionManager._OnEveryFrameTrigger = 10;
  31449. ActionManager._OnIntersectionEnterTrigger = 11;
  31450. ActionManager._OnIntersectionExitTrigger = 12;
  31451. ActionManager._OnKeyDownTrigger = 13;
  31452. ActionManager._OnKeyUpTrigger = 14;
  31453. ActionManager._OnPickOutTrigger = 15;
  31454. ActionManager.DragMovementThreshold = 10; // in pixels
  31455. ActionManager.LongPressDelay = 500; // in milliseconds
  31456. return ActionManager;
  31457. })();
  31458. BABYLON.ActionManager = ActionManager;
  31459. })(BABYLON || (BABYLON = {}));
  31460. var BABYLON;
  31461. (function (BABYLON) {
  31462. var InterpolateValueAction = (function (_super) {
  31463. __extends(InterpolateValueAction, _super);
  31464. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  31465. if (duration === void 0) { duration = 1000; }
  31466. _super.call(this, triggerOptions, condition);
  31467. this.propertyPath = propertyPath;
  31468. this.value = value;
  31469. this.duration = duration;
  31470. this.stopOtherAnimations = stopOtherAnimations;
  31471. this.onInterpolationDone = onInterpolationDone;
  31472. this._target = this._effectiveTarget = target;
  31473. }
  31474. InterpolateValueAction.prototype._prepare = function () {
  31475. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31476. this._property = this._getProperty(this.propertyPath);
  31477. };
  31478. InterpolateValueAction.prototype.execute = function () {
  31479. var scene = this._actionManager.getScene();
  31480. var keys = [
  31481. {
  31482. frame: 0,
  31483. value: this._effectiveTarget[this._property]
  31484. }, {
  31485. frame: 100,
  31486. value: this.value
  31487. }
  31488. ];
  31489. var dataType;
  31490. if (typeof this.value === "number") {
  31491. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  31492. }
  31493. else if (this.value instanceof BABYLON.Color3) {
  31494. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  31495. }
  31496. else if (this.value instanceof BABYLON.Vector3) {
  31497. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  31498. }
  31499. else if (this.value instanceof BABYLON.Matrix) {
  31500. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  31501. }
  31502. else if (this.value instanceof BABYLON.Quaternion) {
  31503. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  31504. }
  31505. else {
  31506. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  31507. return;
  31508. }
  31509. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  31510. animation.setKeys(keys);
  31511. if (this.stopOtherAnimations) {
  31512. scene.stopAnimation(this._effectiveTarget);
  31513. }
  31514. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  31515. };
  31516. InterpolateValueAction.prototype.serialize = function (parent) {
  31517. return _super.prototype._serialize.call(this, {
  31518. name: "InterpolateValueAction",
  31519. properties: [
  31520. BABYLON.Action._GetTargetProperty(this._target),
  31521. { name: "propertyPath", value: this.propertyPath },
  31522. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31523. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  31524. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  31525. ]
  31526. }, parent);
  31527. };
  31528. return InterpolateValueAction;
  31529. })(BABYLON.Action);
  31530. BABYLON.InterpolateValueAction = InterpolateValueAction;
  31531. })(BABYLON || (BABYLON = {}));
  31532. var BABYLON;
  31533. (function (BABYLON) {
  31534. var SwitchBooleanAction = (function (_super) {
  31535. __extends(SwitchBooleanAction, _super);
  31536. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  31537. _super.call(this, triggerOptions, condition);
  31538. this.propertyPath = propertyPath;
  31539. this._target = this._effectiveTarget = target;
  31540. }
  31541. SwitchBooleanAction.prototype._prepare = function () {
  31542. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31543. this._property = this._getProperty(this.propertyPath);
  31544. };
  31545. SwitchBooleanAction.prototype.execute = function () {
  31546. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  31547. };
  31548. SwitchBooleanAction.prototype.serialize = function (parent) {
  31549. return _super.prototype._serialize.call(this, {
  31550. name: "SwitchBooleanAction",
  31551. properties: [
  31552. BABYLON.Action._GetTargetProperty(this._target),
  31553. { name: "propertyPath", value: this.propertyPath }
  31554. ]
  31555. }, parent);
  31556. };
  31557. return SwitchBooleanAction;
  31558. })(BABYLON.Action);
  31559. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  31560. var SetStateAction = (function (_super) {
  31561. __extends(SetStateAction, _super);
  31562. function SetStateAction(triggerOptions, target, value, condition) {
  31563. _super.call(this, triggerOptions, condition);
  31564. this.value = value;
  31565. this._target = target;
  31566. }
  31567. SetStateAction.prototype.execute = function () {
  31568. this._target.state = this.value;
  31569. };
  31570. SetStateAction.prototype.serialize = function (parent) {
  31571. return _super.prototype._serialize.call(this, {
  31572. name: "SetStateAction",
  31573. properties: [
  31574. BABYLON.Action._GetTargetProperty(this._target),
  31575. { name: "value", value: this.value }
  31576. ]
  31577. }, parent);
  31578. };
  31579. return SetStateAction;
  31580. })(BABYLON.Action);
  31581. BABYLON.SetStateAction = SetStateAction;
  31582. var SetValueAction = (function (_super) {
  31583. __extends(SetValueAction, _super);
  31584. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  31585. _super.call(this, triggerOptions, condition);
  31586. this.propertyPath = propertyPath;
  31587. this.value = value;
  31588. this._target = this._effectiveTarget = target;
  31589. }
  31590. SetValueAction.prototype._prepare = function () {
  31591. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31592. this._property = this._getProperty(this.propertyPath);
  31593. };
  31594. SetValueAction.prototype.execute = function () {
  31595. this._effectiveTarget[this._property] = this.value;
  31596. };
  31597. SetValueAction.prototype.serialize = function (parent) {
  31598. return _super.prototype._serialize.call(this, {
  31599. name: "SetValueAction",
  31600. properties: [
  31601. BABYLON.Action._GetTargetProperty(this._target),
  31602. { name: "propertyPath", value: this.propertyPath },
  31603. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31604. ]
  31605. }, parent);
  31606. };
  31607. return SetValueAction;
  31608. })(BABYLON.Action);
  31609. BABYLON.SetValueAction = SetValueAction;
  31610. var IncrementValueAction = (function (_super) {
  31611. __extends(IncrementValueAction, _super);
  31612. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  31613. _super.call(this, triggerOptions, condition);
  31614. this.propertyPath = propertyPath;
  31615. this.value = value;
  31616. this._target = this._effectiveTarget = target;
  31617. }
  31618. IncrementValueAction.prototype._prepare = function () {
  31619. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31620. this._property = this._getProperty(this.propertyPath);
  31621. if (typeof this._effectiveTarget[this._property] !== "number") {
  31622. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  31623. }
  31624. };
  31625. IncrementValueAction.prototype.execute = function () {
  31626. this._effectiveTarget[this._property] += this.value;
  31627. };
  31628. IncrementValueAction.prototype.serialize = function (parent) {
  31629. return _super.prototype._serialize.call(this, {
  31630. name: "IncrementValueAction",
  31631. properties: [
  31632. BABYLON.Action._GetTargetProperty(this._target),
  31633. { name: "propertyPath", value: this.propertyPath },
  31634. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31635. ]
  31636. }, parent);
  31637. };
  31638. return IncrementValueAction;
  31639. })(BABYLON.Action);
  31640. BABYLON.IncrementValueAction = IncrementValueAction;
  31641. var PlayAnimationAction = (function (_super) {
  31642. __extends(PlayAnimationAction, _super);
  31643. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  31644. _super.call(this, triggerOptions, condition);
  31645. this.from = from;
  31646. this.to = to;
  31647. this.loop = loop;
  31648. this._target = target;
  31649. }
  31650. PlayAnimationAction.prototype._prepare = function () {
  31651. };
  31652. PlayAnimationAction.prototype.execute = function () {
  31653. var scene = this._actionManager.getScene();
  31654. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  31655. };
  31656. PlayAnimationAction.prototype.serialize = function (parent) {
  31657. return _super.prototype._serialize.call(this, {
  31658. name: "PlayAnimationAction",
  31659. properties: [
  31660. BABYLON.Action._GetTargetProperty(this._target),
  31661. { name: "from", value: String(this.from) },
  31662. { name: "to", value: String(this.to) },
  31663. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  31664. ]
  31665. }, parent);
  31666. };
  31667. return PlayAnimationAction;
  31668. })(BABYLON.Action);
  31669. BABYLON.PlayAnimationAction = PlayAnimationAction;
  31670. var StopAnimationAction = (function (_super) {
  31671. __extends(StopAnimationAction, _super);
  31672. function StopAnimationAction(triggerOptions, target, condition) {
  31673. _super.call(this, triggerOptions, condition);
  31674. this._target = target;
  31675. }
  31676. StopAnimationAction.prototype._prepare = function () {
  31677. };
  31678. StopAnimationAction.prototype.execute = function () {
  31679. var scene = this._actionManager.getScene();
  31680. scene.stopAnimation(this._target);
  31681. };
  31682. StopAnimationAction.prototype.serialize = function (parent) {
  31683. return _super.prototype._serialize.call(this, {
  31684. name: "StopAnimationAction",
  31685. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  31686. }, parent);
  31687. };
  31688. return StopAnimationAction;
  31689. })(BABYLON.Action);
  31690. BABYLON.StopAnimationAction = StopAnimationAction;
  31691. var DoNothingAction = (function (_super) {
  31692. __extends(DoNothingAction, _super);
  31693. function DoNothingAction(triggerOptions, condition) {
  31694. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  31695. _super.call(this, triggerOptions, condition);
  31696. }
  31697. DoNothingAction.prototype.execute = function () {
  31698. };
  31699. DoNothingAction.prototype.serialize = function (parent) {
  31700. return _super.prototype._serialize.call(this, {
  31701. name: "DoNothingAction",
  31702. properties: []
  31703. }, parent);
  31704. };
  31705. return DoNothingAction;
  31706. })(BABYLON.Action);
  31707. BABYLON.DoNothingAction = DoNothingAction;
  31708. var CombineAction = (function (_super) {
  31709. __extends(CombineAction, _super);
  31710. function CombineAction(triggerOptions, children, condition) {
  31711. _super.call(this, triggerOptions, condition);
  31712. this.children = children;
  31713. }
  31714. CombineAction.prototype._prepare = function () {
  31715. for (var index = 0; index < this.children.length; index++) {
  31716. this.children[index]._actionManager = this._actionManager;
  31717. this.children[index]._prepare();
  31718. }
  31719. };
  31720. CombineAction.prototype.execute = function (evt) {
  31721. for (var index = 0; index < this.children.length; index++) {
  31722. this.children[index].execute(evt);
  31723. }
  31724. };
  31725. CombineAction.prototype.serialize = function (parent) {
  31726. var serializationObject = _super.prototype._serialize.call(this, {
  31727. name: "CombineAction",
  31728. properties: [],
  31729. combine: []
  31730. }, parent);
  31731. for (var i = 0; i < this.children.length; i++) {
  31732. serializationObject.combine.push(this.children[i].serialize(null));
  31733. }
  31734. return serializationObject;
  31735. };
  31736. return CombineAction;
  31737. })(BABYLON.Action);
  31738. BABYLON.CombineAction = CombineAction;
  31739. var ExecuteCodeAction = (function (_super) {
  31740. __extends(ExecuteCodeAction, _super);
  31741. function ExecuteCodeAction(triggerOptions, func, condition) {
  31742. _super.call(this, triggerOptions, condition);
  31743. this.func = func;
  31744. }
  31745. ExecuteCodeAction.prototype.execute = function (evt) {
  31746. this.func(evt);
  31747. };
  31748. return ExecuteCodeAction;
  31749. })(BABYLON.Action);
  31750. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  31751. var SetParentAction = (function (_super) {
  31752. __extends(SetParentAction, _super);
  31753. function SetParentAction(triggerOptions, target, parent, condition) {
  31754. _super.call(this, triggerOptions, condition);
  31755. this._target = target;
  31756. this._parent = parent;
  31757. }
  31758. SetParentAction.prototype._prepare = function () {
  31759. };
  31760. SetParentAction.prototype.execute = function () {
  31761. if (this._target.parent === this._parent) {
  31762. return;
  31763. }
  31764. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  31765. invertParentWorldMatrix.invert();
  31766. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  31767. this._target.parent = this._parent;
  31768. };
  31769. SetParentAction.prototype.serialize = function (parent) {
  31770. return _super.prototype._serialize.call(this, {
  31771. name: "SetParentAction",
  31772. properties: [
  31773. BABYLON.Action._GetTargetProperty(this._target),
  31774. BABYLON.Action._GetTargetProperty(this._parent),
  31775. ]
  31776. }, parent);
  31777. };
  31778. return SetParentAction;
  31779. })(BABYLON.Action);
  31780. BABYLON.SetParentAction = SetParentAction;
  31781. var PlaySoundAction = (function (_super) {
  31782. __extends(PlaySoundAction, _super);
  31783. function PlaySoundAction(triggerOptions, sound, condition) {
  31784. _super.call(this, triggerOptions, condition);
  31785. this._sound = sound;
  31786. }
  31787. PlaySoundAction.prototype._prepare = function () {
  31788. };
  31789. PlaySoundAction.prototype.execute = function () {
  31790. if (this._sound !== undefined)
  31791. this._sound.play();
  31792. };
  31793. PlaySoundAction.prototype.serialize = function (parent) {
  31794. return _super.prototype._serialize.call(this, {
  31795. name: "PlaySoundAction",
  31796. properties: [{ name: "sound", value: this._sound.name }]
  31797. }, parent);
  31798. };
  31799. return PlaySoundAction;
  31800. })(BABYLON.Action);
  31801. BABYLON.PlaySoundAction = PlaySoundAction;
  31802. var StopSoundAction = (function (_super) {
  31803. __extends(StopSoundAction, _super);
  31804. function StopSoundAction(triggerOptions, sound, condition) {
  31805. _super.call(this, triggerOptions, condition);
  31806. this._sound = sound;
  31807. }
  31808. StopSoundAction.prototype._prepare = function () {
  31809. };
  31810. StopSoundAction.prototype.execute = function () {
  31811. if (this._sound !== undefined)
  31812. this._sound.stop();
  31813. };
  31814. StopSoundAction.prototype.serialize = function (parent) {
  31815. return _super.prototype._serialize.call(this, {
  31816. name: "StopSoundAction",
  31817. properties: [{ name: "sound", value: this._sound.name }]
  31818. }, parent);
  31819. };
  31820. return StopSoundAction;
  31821. })(BABYLON.Action);
  31822. BABYLON.StopSoundAction = StopSoundAction;
  31823. })(BABYLON || (BABYLON = {}));
  31824. var BABYLON;
  31825. (function (BABYLON) {
  31826. var Geometry = (function () {
  31827. function Geometry(id, scene, vertexData, updatable, mesh) {
  31828. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31829. this._totalVertices = 0;
  31830. this._isDisposed = false;
  31831. this.id = id;
  31832. this._engine = scene.getEngine();
  31833. this._meshes = [];
  31834. this._scene = scene;
  31835. //Init vertex buffer cache
  31836. this._vertexBuffers = {};
  31837. this._indices = [];
  31838. // vertexData
  31839. if (vertexData) {
  31840. this.setAllVerticesData(vertexData, updatable);
  31841. }
  31842. else {
  31843. this._totalVertices = 0;
  31844. this._indices = [];
  31845. }
  31846. // applyToMesh
  31847. if (mesh) {
  31848. if (mesh instanceof BABYLON.LinesMesh) {
  31849. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31850. this.updateExtend();
  31851. }
  31852. this.applyToMesh(mesh);
  31853. mesh.computeWorldMatrix(true);
  31854. }
  31855. }
  31856. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31857. /**
  31858. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  31859. * @returns The Bias Vector
  31860. */
  31861. get: function () {
  31862. return this._boundingBias;
  31863. },
  31864. set: function (value) {
  31865. if (this._boundingBias && this._boundingBias.equals(value)) {
  31866. return;
  31867. }
  31868. this._boundingBias = value.clone();
  31869. this.updateBoundingInfo(true, null);
  31870. },
  31871. enumerable: true,
  31872. configurable: true
  31873. });
  31874. Object.defineProperty(Geometry.prototype, "extend", {
  31875. get: function () {
  31876. return this._extend;
  31877. },
  31878. enumerable: true,
  31879. configurable: true
  31880. });
  31881. Geometry.prototype.getScene = function () {
  31882. return this._scene;
  31883. };
  31884. Geometry.prototype.getEngine = function () {
  31885. return this._engine;
  31886. };
  31887. Geometry.prototype.isReady = function () {
  31888. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31889. };
  31890. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31891. vertexData.applyToGeometry(this, updatable);
  31892. this.notifyUpdate();
  31893. };
  31894. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31895. if (this._vertexBuffers[kind]) {
  31896. this._vertexBuffers[kind].dispose();
  31897. }
  31898. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31899. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31900. stride = this._vertexBuffers[kind].getStrideSize();
  31901. this._totalVertices = data.length / stride;
  31902. this.updateExtend(data);
  31903. var meshes = this._meshes;
  31904. var numOfMeshes = meshes.length;
  31905. for (var index = 0; index < numOfMeshes; index++) {
  31906. var mesh = meshes[index];
  31907. mesh._resetPointsArrayCache();
  31908. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31909. mesh._createGlobalSubMesh();
  31910. mesh.computeWorldMatrix(true);
  31911. }
  31912. }
  31913. this.notifyUpdate(kind);
  31914. };
  31915. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31916. var vertexBuffer = this.getVertexBuffer(kind);
  31917. if (!vertexBuffer) {
  31918. return;
  31919. }
  31920. vertexBuffer.updateDirectly(data, offset);
  31921. this.notifyUpdate(kind);
  31922. };
  31923. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31924. var vertexBuffer = this.getVertexBuffer(kind);
  31925. if (!vertexBuffer) {
  31926. return;
  31927. }
  31928. vertexBuffer.update(data);
  31929. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31930. var stride = vertexBuffer.getStrideSize();
  31931. this._totalVertices = data.length / stride;
  31932. this.updateBoundingInfo(updateExtends, data);
  31933. }
  31934. this.notifyUpdate(kind);
  31935. };
  31936. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31937. if (updateExtends) {
  31938. this.updateExtend(data);
  31939. }
  31940. var meshes = this._meshes;
  31941. var numOfMeshes = meshes.length;
  31942. for (var index = 0; index < numOfMeshes; index++) {
  31943. var mesh = meshes[index];
  31944. mesh._resetPointsArrayCache();
  31945. if (updateExtends) {
  31946. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31947. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31948. var subMesh = mesh.subMeshes[subIndex];
  31949. subMesh.refreshBoundingInfo();
  31950. }
  31951. }
  31952. }
  31953. };
  31954. Geometry.prototype.getTotalVertices = function () {
  31955. if (!this.isReady()) {
  31956. return 0;
  31957. }
  31958. return this._totalVertices;
  31959. };
  31960. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  31961. var vertexBuffer = this.getVertexBuffer(kind);
  31962. if (!vertexBuffer) {
  31963. return null;
  31964. }
  31965. var orig = vertexBuffer.getData();
  31966. if (!copyWhenShared || this._meshes.length === 1) {
  31967. return orig;
  31968. }
  31969. else {
  31970. var len = orig.length;
  31971. var copy = [];
  31972. for (var i = 0; i < len; i++) {
  31973. copy.push(orig[i]);
  31974. }
  31975. return copy;
  31976. }
  31977. };
  31978. Geometry.prototype.getVertexBuffer = function (kind) {
  31979. if (!this.isReady()) {
  31980. return null;
  31981. }
  31982. return this._vertexBuffers[kind];
  31983. };
  31984. Geometry.prototype.getVertexBuffers = function () {
  31985. if (!this.isReady()) {
  31986. return null;
  31987. }
  31988. return this._vertexBuffers;
  31989. };
  31990. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31991. if (!this._vertexBuffers) {
  31992. if (this._delayInfo) {
  31993. return this._delayInfo.indexOf(kind) !== -1;
  31994. }
  31995. return false;
  31996. }
  31997. return this._vertexBuffers[kind] !== undefined;
  31998. };
  31999. Geometry.prototype.getVerticesDataKinds = function () {
  32000. var result = [];
  32001. var kind;
  32002. if (!this._vertexBuffers && this._delayInfo) {
  32003. for (kind in this._delayInfo) {
  32004. result.push(kind);
  32005. }
  32006. }
  32007. else {
  32008. for (kind in this._vertexBuffers) {
  32009. result.push(kind);
  32010. }
  32011. }
  32012. return result;
  32013. };
  32014. Geometry.prototype.setIndices = function (indices, totalVertices) {
  32015. if (this._indexBuffer) {
  32016. this._engine._releaseBuffer(this._indexBuffer);
  32017. }
  32018. this._indices = indices;
  32019. if (this._meshes.length !== 0 && this._indices) {
  32020. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32021. }
  32022. if (totalVertices !== undefined) {
  32023. this._totalVertices = totalVertices;
  32024. }
  32025. var meshes = this._meshes;
  32026. var numOfMeshes = meshes.length;
  32027. for (var index = 0; index < numOfMeshes; index++) {
  32028. meshes[index]._createGlobalSubMesh();
  32029. }
  32030. this.notifyUpdate();
  32031. };
  32032. Geometry.prototype.getTotalIndices = function () {
  32033. if (!this.isReady()) {
  32034. return 0;
  32035. }
  32036. return this._indices.length;
  32037. };
  32038. Geometry.prototype.getIndices = function (copyWhenShared) {
  32039. if (!this.isReady()) {
  32040. return null;
  32041. }
  32042. var orig = this._indices;
  32043. if (!copyWhenShared || this._meshes.length === 1) {
  32044. return orig;
  32045. }
  32046. else {
  32047. var len = orig.length;
  32048. var copy = [];
  32049. for (var i = 0; i < len; i++) {
  32050. copy.push(orig[i]);
  32051. }
  32052. return copy;
  32053. }
  32054. };
  32055. Geometry.prototype.getIndexBuffer = function () {
  32056. if (!this.isReady()) {
  32057. return null;
  32058. }
  32059. return this._indexBuffer;
  32060. };
  32061. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32062. var meshes = this._meshes;
  32063. var index = meshes.indexOf(mesh);
  32064. if (index === -1) {
  32065. return;
  32066. }
  32067. for (var kind in this._vertexBuffers) {
  32068. this._vertexBuffers[kind].dispose();
  32069. }
  32070. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  32071. this._indexBuffer = null;
  32072. }
  32073. meshes.splice(index, 1);
  32074. mesh._geometry = null;
  32075. if (meshes.length === 0 && shouldDispose) {
  32076. this.dispose();
  32077. }
  32078. };
  32079. Geometry.prototype.applyToMesh = function (mesh) {
  32080. if (mesh._geometry === this) {
  32081. return;
  32082. }
  32083. var previousGeometry = mesh._geometry;
  32084. if (previousGeometry) {
  32085. previousGeometry.releaseForMesh(mesh);
  32086. }
  32087. var meshes = this._meshes;
  32088. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32089. mesh._geometry = this;
  32090. this._scene.pushGeometry(this);
  32091. meshes.push(mesh);
  32092. if (this.isReady()) {
  32093. this._applyToMesh(mesh);
  32094. }
  32095. else {
  32096. mesh._boundingInfo = this._boundingInfo;
  32097. }
  32098. };
  32099. Geometry.prototype.updateExtend = function (data) {
  32100. if (data === void 0) { data = null; }
  32101. if (!data) {
  32102. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32103. }
  32104. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  32105. };
  32106. Geometry.prototype._applyToMesh = function (mesh) {
  32107. var numOfMeshes = this._meshes.length;
  32108. // vertexBuffers
  32109. for (var kind in this._vertexBuffers) {
  32110. if (numOfMeshes === 1) {
  32111. this._vertexBuffers[kind].create();
  32112. }
  32113. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  32114. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32115. mesh._resetPointsArrayCache();
  32116. if (!this._extend) {
  32117. this.updateExtend(this._vertexBuffers[kind].getData());
  32118. }
  32119. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32120. mesh._createGlobalSubMesh();
  32121. //bounding info was just created again, world matrix should be applied again.
  32122. mesh._updateBoundingInfo();
  32123. }
  32124. }
  32125. // indexBuffer
  32126. if (numOfMeshes === 1 && this._indices) {
  32127. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32128. }
  32129. if (this._indexBuffer) {
  32130. this._indexBuffer.references = numOfMeshes;
  32131. }
  32132. };
  32133. Geometry.prototype.notifyUpdate = function (kind) {
  32134. if (this.onGeometryUpdated) {
  32135. this.onGeometryUpdated(this, kind);
  32136. }
  32137. };
  32138. Geometry.prototype.load = function (scene, onLoaded) {
  32139. var _this = this;
  32140. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32141. return;
  32142. }
  32143. if (this.isReady()) {
  32144. if (onLoaded) {
  32145. onLoaded();
  32146. }
  32147. return;
  32148. }
  32149. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32150. scene._addPendingData(this);
  32151. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32152. _this._delayLoadingFunction(JSON.parse(data), _this);
  32153. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32154. _this._delayInfo = [];
  32155. scene._removePendingData(_this);
  32156. var meshes = _this._meshes;
  32157. var numOfMeshes = meshes.length;
  32158. for (var index = 0; index < numOfMeshes; index++) {
  32159. _this._applyToMesh(meshes[index]);
  32160. }
  32161. if (onLoaded) {
  32162. onLoaded();
  32163. }
  32164. }, function () { }, scene.database);
  32165. };
  32166. Geometry.prototype.isDisposed = function () {
  32167. return this._isDisposed;
  32168. };
  32169. Geometry.prototype.dispose = function () {
  32170. var meshes = this._meshes;
  32171. var numOfMeshes = meshes.length;
  32172. var index;
  32173. for (index = 0; index < numOfMeshes; index++) {
  32174. this.releaseForMesh(meshes[index]);
  32175. }
  32176. this._meshes = [];
  32177. for (var kind in this._vertexBuffers) {
  32178. this._vertexBuffers[kind].dispose();
  32179. }
  32180. this._vertexBuffers = [];
  32181. this._totalVertices = 0;
  32182. if (this._indexBuffer) {
  32183. this._engine._releaseBuffer(this._indexBuffer);
  32184. }
  32185. this._indexBuffer = null;
  32186. this._indices = [];
  32187. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32188. this.delayLoadingFile = null;
  32189. this._delayLoadingFunction = null;
  32190. this._delayInfo = [];
  32191. this._boundingInfo = null;
  32192. this._scene.removeGeometry(this);
  32193. this._isDisposed = true;
  32194. };
  32195. Geometry.prototype.copy = function (id) {
  32196. var vertexData = new BABYLON.VertexData();
  32197. vertexData.indices = [];
  32198. var indices = this.getIndices();
  32199. for (var index = 0; index < indices.length; index++) {
  32200. vertexData.indices.push(indices[index]);
  32201. }
  32202. var updatable = false;
  32203. var stopChecking = false;
  32204. var kind;
  32205. for (kind in this._vertexBuffers) {
  32206. // using slice() to make a copy of the array and not just reference it
  32207. var data = this.getVerticesData(kind);
  32208. if (data instanceof Float32Array) {
  32209. vertexData.set(new Float32Array(data), kind);
  32210. }
  32211. else {
  32212. vertexData.set(data.slice(0), kind);
  32213. }
  32214. if (!stopChecking) {
  32215. updatable = this.getVertexBuffer(kind).isUpdatable();
  32216. stopChecking = !updatable;
  32217. }
  32218. }
  32219. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  32220. geometry.delayLoadState = this.delayLoadState;
  32221. geometry.delayLoadingFile = this.delayLoadingFile;
  32222. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32223. for (kind in this._delayInfo) {
  32224. geometry._delayInfo = geometry._delayInfo || [];
  32225. geometry._delayInfo.push(kind);
  32226. }
  32227. // Bounding info
  32228. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32229. return geometry;
  32230. };
  32231. Geometry.prototype.serialize = function () {
  32232. var serializationObject = {};
  32233. serializationObject.id = this.id;
  32234. if (BABYLON.Tags.HasTags(this)) {
  32235. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32236. }
  32237. return serializationObject;
  32238. };
  32239. Geometry.prototype.serializeVerticeData = function () {
  32240. var serializationObject = this.serialize();
  32241. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32242. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32243. }
  32244. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32245. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32246. }
  32247. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32248. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32249. }
  32250. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32251. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  32252. }
  32253. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32254. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  32255. }
  32256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32257. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  32258. }
  32259. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32260. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  32261. }
  32262. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32263. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  32264. }
  32265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32266. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32267. }
  32268. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32269. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32270. serializationObject.matricesIndices._isExpanded = true;
  32271. }
  32272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32273. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32274. }
  32275. serializationObject.indices = this.getIndices();
  32276. return serializationObject;
  32277. };
  32278. // Statics
  32279. Geometry.ExtractFromMesh = function (mesh, id) {
  32280. var geometry = mesh._geometry;
  32281. if (!geometry) {
  32282. return null;
  32283. }
  32284. return geometry.copy(id);
  32285. };
  32286. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32287. // be aware Math.random() could cause collisions
  32288. Geometry.RandomId = function () {
  32289. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  32290. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  32291. return v.toString(16);
  32292. });
  32293. };
  32294. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32295. var scene = mesh.getScene();
  32296. // Geometry
  32297. var geometryId = parsedGeometry.geometryId;
  32298. if (geometryId) {
  32299. var geometry = scene.getGeometryByID(geometryId);
  32300. if (geometry) {
  32301. geometry.applyToMesh(mesh);
  32302. }
  32303. }
  32304. else if (parsedGeometry instanceof ArrayBuffer) {
  32305. var binaryInfo = mesh._binaryInfo;
  32306. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32307. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32308. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32309. }
  32310. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32311. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32312. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32313. }
  32314. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32315. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32316. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32317. }
  32318. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32319. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32320. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32321. }
  32322. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32323. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32324. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32325. }
  32326. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32327. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32328. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32329. }
  32330. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32331. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32332. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32333. }
  32334. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32335. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32336. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32337. }
  32338. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32339. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32340. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32341. }
  32342. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32343. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32344. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32345. }
  32346. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32347. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32348. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32349. }
  32350. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32351. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32352. mesh.setIndices(indicesData);
  32353. }
  32354. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32355. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32356. mesh.subMeshes = [];
  32357. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32358. var materialIndex = subMeshesData[(i * 5) + 0];
  32359. var verticesStart = subMeshesData[(i * 5) + 1];
  32360. var verticesCount = subMeshesData[(i * 5) + 2];
  32361. var indexStart = subMeshesData[(i * 5) + 3];
  32362. var indexCount = subMeshesData[(i * 5) + 4];
  32363. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32364. }
  32365. }
  32366. }
  32367. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32368. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  32369. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  32370. if (parsedGeometry.uvs) {
  32371. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  32372. }
  32373. if (parsedGeometry.uvs2) {
  32374. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  32375. }
  32376. if (parsedGeometry.uvs3) {
  32377. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  32378. }
  32379. if (parsedGeometry.uvs4) {
  32380. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  32381. }
  32382. if (parsedGeometry.uvs5) {
  32383. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  32384. }
  32385. if (parsedGeometry.uvs6) {
  32386. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  32387. }
  32388. if (parsedGeometry.colors) {
  32389. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  32390. }
  32391. if (parsedGeometry.matricesIndices) {
  32392. if (!parsedGeometry.matricesIndices._isExpanded) {
  32393. var floatIndices = [];
  32394. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32395. var matricesIndex = parsedGeometry.matricesIndices[i];
  32396. floatIndices.push(matricesIndex & 0x000000FF);
  32397. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32398. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32399. floatIndices.push(matricesIndex >> 24);
  32400. }
  32401. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  32402. }
  32403. else {
  32404. delete parsedGeometry.matricesIndices._isExpanded;
  32405. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  32406. }
  32407. }
  32408. if (parsedGeometry.matricesIndicesExtra) {
  32409. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32410. var floatIndices = [];
  32411. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32412. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32413. floatIndices.push(matricesIndex & 0x000000FF);
  32414. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32415. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32416. floatIndices.push(matricesIndex >> 24);
  32417. }
  32418. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  32419. }
  32420. else {
  32421. delete parsedGeometry.matricesIndices._isExpanded;
  32422. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  32423. }
  32424. }
  32425. if (parsedGeometry.matricesWeights) {
  32426. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  32427. }
  32428. if (parsedGeometry.matricesWeightsExtra) {
  32429. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  32430. }
  32431. mesh.setIndices(parsedGeometry.indices);
  32432. }
  32433. // SubMeshes
  32434. if (parsedGeometry.subMeshes) {
  32435. mesh.subMeshes = [];
  32436. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32437. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32438. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32439. }
  32440. }
  32441. // Flat shading
  32442. if (mesh._shouldGenerateFlatShading) {
  32443. mesh.convertToFlatShadedMesh();
  32444. delete mesh._shouldGenerateFlatShading;
  32445. }
  32446. // Update
  32447. mesh.computeWorldMatrix(true);
  32448. // Octree
  32449. if (scene['_selectionOctree']) {
  32450. scene['_selectionOctree'].addMesh(mesh);
  32451. }
  32452. };
  32453. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32454. if (scene.getGeometryByID(parsedVertexData.id)) {
  32455. return null; // null since geometry could be something else than a box...
  32456. }
  32457. var geometry = new Geometry(parsedVertexData.id, scene);
  32458. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32459. if (parsedVertexData.delayLoadingFile) {
  32460. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32461. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32462. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32463. geometry._delayInfo = [];
  32464. if (parsedVertexData.hasUVs) {
  32465. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32466. }
  32467. if (parsedVertexData.hasUVs2) {
  32468. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32469. }
  32470. if (parsedVertexData.hasUVs3) {
  32471. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32472. }
  32473. if (parsedVertexData.hasUVs4) {
  32474. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32475. }
  32476. if (parsedVertexData.hasUVs5) {
  32477. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32478. }
  32479. if (parsedVertexData.hasUVs6) {
  32480. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32481. }
  32482. if (parsedVertexData.hasColors) {
  32483. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32484. }
  32485. if (parsedVertexData.hasMatricesIndices) {
  32486. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32487. }
  32488. if (parsedVertexData.hasMatricesWeights) {
  32489. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32490. }
  32491. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32492. }
  32493. else {
  32494. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32495. }
  32496. scene.pushGeometry(geometry, true);
  32497. return geometry;
  32498. };
  32499. return Geometry;
  32500. })();
  32501. BABYLON.Geometry = Geometry;
  32502. /////// Primitives //////////////////////////////////////////////
  32503. var Geometry;
  32504. (function (Geometry) {
  32505. var Primitives;
  32506. (function (Primitives) {
  32507. /// Abstract class
  32508. var _Primitive = (function (_super) {
  32509. __extends(_Primitive, _super);
  32510. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  32511. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  32512. this._canBeRegenerated = _canBeRegenerated;
  32513. this._beingRegenerated = true;
  32514. this.regenerate();
  32515. this._beingRegenerated = false;
  32516. }
  32517. _Primitive.prototype.canBeRegenerated = function () {
  32518. return this._canBeRegenerated;
  32519. };
  32520. _Primitive.prototype.regenerate = function () {
  32521. if (!this._canBeRegenerated) {
  32522. return;
  32523. }
  32524. this._beingRegenerated = true;
  32525. this.setAllVerticesData(this._regenerateVertexData(), false);
  32526. this._beingRegenerated = false;
  32527. };
  32528. _Primitive.prototype.asNewGeometry = function (id) {
  32529. return _super.prototype.copy.call(this, id);
  32530. };
  32531. // overrides
  32532. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  32533. if (!this._beingRegenerated) {
  32534. return;
  32535. }
  32536. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32537. };
  32538. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  32539. if (!this._beingRegenerated) {
  32540. return;
  32541. }
  32542. _super.prototype.setVerticesData.call(this, kind, data, false);
  32543. };
  32544. // to override
  32545. // protected
  32546. _Primitive.prototype._regenerateVertexData = function () {
  32547. throw new Error("Abstract method");
  32548. };
  32549. _Primitive.prototype.copy = function (id) {
  32550. throw new Error("Must be overriden in sub-classes.");
  32551. };
  32552. _Primitive.prototype.serialize = function () {
  32553. var serializationObject = _super.prototype.serialize.call(this);
  32554. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32555. return serializationObject;
  32556. };
  32557. return _Primitive;
  32558. })(Geometry);
  32559. Primitives._Primitive = _Primitive;
  32560. var Ribbon = (function (_super) {
  32561. __extends(Ribbon, _super);
  32562. // Members
  32563. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32564. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32565. _super.call(this, id, scene, canBeRegenerated, mesh);
  32566. this.pathArray = pathArray;
  32567. this.closeArray = closeArray;
  32568. this.closePath = closePath;
  32569. this.offset = offset;
  32570. this.side = side;
  32571. }
  32572. Ribbon.prototype._regenerateVertexData = function () {
  32573. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32574. };
  32575. Ribbon.prototype.copy = function (id) {
  32576. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  32577. };
  32578. return Ribbon;
  32579. })(_Primitive);
  32580. Primitives.Ribbon = Ribbon;
  32581. var Box = (function (_super) {
  32582. __extends(Box, _super);
  32583. // Members
  32584. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32585. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32586. _super.call(this, id, scene, canBeRegenerated, mesh);
  32587. this.size = size;
  32588. this.side = side;
  32589. }
  32590. Box.prototype._regenerateVertexData = function () {
  32591. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32592. };
  32593. Box.prototype.copy = function (id) {
  32594. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32595. };
  32596. Box.prototype.serialize = function () {
  32597. var serializationObject = _super.prototype.serialize.call(this);
  32598. serializationObject.size = this.size;
  32599. return serializationObject;
  32600. };
  32601. Box.Parse = function (parsedBox, scene) {
  32602. if (scene.getGeometryByID(parsedBox.id)) {
  32603. return null; // null since geometry could be something else than a box...
  32604. }
  32605. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32606. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32607. scene.pushGeometry(box, true);
  32608. return box;
  32609. };
  32610. return Box;
  32611. })(_Primitive);
  32612. Primitives.Box = Box;
  32613. var Sphere = (function (_super) {
  32614. __extends(Sphere, _super);
  32615. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32616. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32617. _super.call(this, id, scene, canBeRegenerated, mesh);
  32618. this.segments = segments;
  32619. this.diameter = diameter;
  32620. this.side = side;
  32621. }
  32622. Sphere.prototype._regenerateVertexData = function () {
  32623. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32624. };
  32625. Sphere.prototype.copy = function (id) {
  32626. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32627. };
  32628. Sphere.prototype.serialize = function () {
  32629. var serializationObject = _super.prototype.serialize.call(this);
  32630. serializationObject.segments = this.segments;
  32631. serializationObject.diameter = this.diameter;
  32632. return serializationObject;
  32633. };
  32634. Sphere.Parse = function (parsedSphere, scene) {
  32635. if (scene.getGeometryByID(parsedSphere.id)) {
  32636. return null; // null since geometry could be something else than a sphere...
  32637. }
  32638. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32639. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32640. scene.pushGeometry(sphere, true);
  32641. return sphere;
  32642. };
  32643. return Sphere;
  32644. })(_Primitive);
  32645. Primitives.Sphere = Sphere;
  32646. var Disc = (function (_super) {
  32647. __extends(Disc, _super);
  32648. // Members
  32649. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32650. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32651. _super.call(this, id, scene, canBeRegenerated, mesh);
  32652. this.radius = radius;
  32653. this.tessellation = tessellation;
  32654. this.side = side;
  32655. }
  32656. Disc.prototype._regenerateVertexData = function () {
  32657. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32658. };
  32659. Disc.prototype.copy = function (id) {
  32660. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32661. };
  32662. return Disc;
  32663. })(_Primitive);
  32664. Primitives.Disc = Disc;
  32665. var Cylinder = (function (_super) {
  32666. __extends(Cylinder, _super);
  32667. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32668. if (subdivisions === void 0) { subdivisions = 1; }
  32669. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32670. _super.call(this, id, scene, canBeRegenerated, mesh);
  32671. this.height = height;
  32672. this.diameterTop = diameterTop;
  32673. this.diameterBottom = diameterBottom;
  32674. this.tessellation = tessellation;
  32675. this.subdivisions = subdivisions;
  32676. this.side = side;
  32677. }
  32678. Cylinder.prototype._regenerateVertexData = function () {
  32679. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32680. };
  32681. Cylinder.prototype.copy = function (id) {
  32682. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32683. };
  32684. Cylinder.prototype.serialize = function () {
  32685. var serializationObject = _super.prototype.serialize.call(this);
  32686. serializationObject.height = this.height;
  32687. serializationObject.diameterTop = this.diameterTop;
  32688. serializationObject.diameterBottom = this.diameterBottom;
  32689. serializationObject.tessellation = this.tessellation;
  32690. return serializationObject;
  32691. };
  32692. Cylinder.Parse = function (parsedCylinder, scene) {
  32693. if (scene.getGeometryByID(parsedCylinder.id)) {
  32694. return null; // null since geometry could be something else than a cylinder...
  32695. }
  32696. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32697. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32698. scene.pushGeometry(cylinder, true);
  32699. return cylinder;
  32700. };
  32701. return Cylinder;
  32702. })(_Primitive);
  32703. Primitives.Cylinder = Cylinder;
  32704. var Torus = (function (_super) {
  32705. __extends(Torus, _super);
  32706. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32707. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32708. _super.call(this, id, scene, canBeRegenerated, mesh);
  32709. this.diameter = diameter;
  32710. this.thickness = thickness;
  32711. this.tessellation = tessellation;
  32712. this.side = side;
  32713. }
  32714. Torus.prototype._regenerateVertexData = function () {
  32715. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32716. };
  32717. Torus.prototype.copy = function (id) {
  32718. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32719. };
  32720. Torus.prototype.serialize = function () {
  32721. var serializationObject = _super.prototype.serialize.call(this);
  32722. serializationObject.diameter = this.diameter;
  32723. serializationObject.thickness = this.thickness;
  32724. serializationObject.tessellation = this.tessellation;
  32725. return serializationObject;
  32726. };
  32727. Torus.Parse = function (parsedTorus, scene) {
  32728. if (scene.getGeometryByID(parsedTorus.id)) {
  32729. return null; // null since geometry could be something else than a torus...
  32730. }
  32731. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32732. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32733. scene.pushGeometry(torus, true);
  32734. return torus;
  32735. };
  32736. return Torus;
  32737. })(_Primitive);
  32738. Primitives.Torus = Torus;
  32739. var Ground = (function (_super) {
  32740. __extends(Ground, _super);
  32741. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32742. _super.call(this, id, scene, canBeRegenerated, mesh);
  32743. this.width = width;
  32744. this.height = height;
  32745. this.subdivisions = subdivisions;
  32746. }
  32747. Ground.prototype._regenerateVertexData = function () {
  32748. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32749. };
  32750. Ground.prototype.copy = function (id) {
  32751. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32752. };
  32753. Ground.prototype.serialize = function () {
  32754. var serializationObject = _super.prototype.serialize.call(this);
  32755. serializationObject.width = this.width;
  32756. serializationObject.height = this.height;
  32757. serializationObject.subdivisions = this.subdivisions;
  32758. return serializationObject;
  32759. };
  32760. Ground.Parse = function (parsedGround, scene) {
  32761. if (scene.getGeometryByID(parsedGround.id)) {
  32762. return null; // null since geometry could be something else than a ground...
  32763. }
  32764. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32765. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32766. scene.pushGeometry(ground, true);
  32767. return ground;
  32768. };
  32769. return Ground;
  32770. })(_Primitive);
  32771. Primitives.Ground = Ground;
  32772. var TiledGround = (function (_super) {
  32773. __extends(TiledGround, _super);
  32774. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32775. _super.call(this, id, scene, canBeRegenerated, mesh);
  32776. this.xmin = xmin;
  32777. this.zmin = zmin;
  32778. this.xmax = xmax;
  32779. this.zmax = zmax;
  32780. this.subdivisions = subdivisions;
  32781. this.precision = precision;
  32782. }
  32783. TiledGround.prototype._regenerateVertexData = function () {
  32784. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32785. };
  32786. TiledGround.prototype.copy = function (id) {
  32787. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32788. };
  32789. return TiledGround;
  32790. })(_Primitive);
  32791. Primitives.TiledGround = TiledGround;
  32792. var Plane = (function (_super) {
  32793. __extends(Plane, _super);
  32794. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32795. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32796. _super.call(this, id, scene, canBeRegenerated, mesh);
  32797. this.size = size;
  32798. this.side = side;
  32799. }
  32800. Plane.prototype._regenerateVertexData = function () {
  32801. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32802. };
  32803. Plane.prototype.copy = function (id) {
  32804. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32805. };
  32806. Plane.prototype.serialize = function () {
  32807. var serializationObject = _super.prototype.serialize.call(this);
  32808. serializationObject.size = this.size;
  32809. return serializationObject;
  32810. };
  32811. Plane.Parse = function (parsedPlane, scene) {
  32812. if (scene.getGeometryByID(parsedPlane.id)) {
  32813. return null; // null since geometry could be something else than a ground...
  32814. }
  32815. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32816. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32817. scene.pushGeometry(plane, true);
  32818. return plane;
  32819. };
  32820. return Plane;
  32821. })(_Primitive);
  32822. Primitives.Plane = Plane;
  32823. var TorusKnot = (function (_super) {
  32824. __extends(TorusKnot, _super);
  32825. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32826. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32827. _super.call(this, id, scene, canBeRegenerated, mesh);
  32828. this.radius = radius;
  32829. this.tube = tube;
  32830. this.radialSegments = radialSegments;
  32831. this.tubularSegments = tubularSegments;
  32832. this.p = p;
  32833. this.q = q;
  32834. this.side = side;
  32835. }
  32836. TorusKnot.prototype._regenerateVertexData = function () {
  32837. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  32838. };
  32839. TorusKnot.prototype.copy = function (id) {
  32840. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32841. };
  32842. TorusKnot.prototype.serialize = function () {
  32843. var serializationObject = _super.prototype.serialize.call(this);
  32844. serializationObject.radius = this.radius;
  32845. serializationObject.tube = this.tube;
  32846. serializationObject.radialSegments = this.radialSegments;
  32847. serializationObject.tubularSegments = this.tubularSegments;
  32848. serializationObject.p = this.p;
  32849. serializationObject.q = this.q;
  32850. return serializationObject;
  32851. };
  32852. ;
  32853. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32854. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32855. return null; // null since geometry could be something else than a ground...
  32856. }
  32857. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32858. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32859. scene.pushGeometry(torusKnot, true);
  32860. return torusKnot;
  32861. };
  32862. return TorusKnot;
  32863. })(_Primitive);
  32864. Primitives.TorusKnot = TorusKnot;
  32865. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32866. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32867. })(BABYLON || (BABYLON = {}));
  32868. var BABYLON;
  32869. (function (BABYLON) {
  32870. var GroundMesh = (function (_super) {
  32871. __extends(GroundMesh, _super);
  32872. function GroundMesh(name, scene) {
  32873. _super.call(this, name, scene);
  32874. this.generateOctree = false;
  32875. this._worldInverse = new BABYLON.Matrix();
  32876. }
  32877. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  32878. get: function () {
  32879. return this._subdivisions;
  32880. },
  32881. enumerable: true,
  32882. configurable: true
  32883. });
  32884. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  32885. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  32886. this._subdivisions = chunksCount;
  32887. this.subdivide(this._subdivisions);
  32888. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  32889. };
  32890. /**
  32891. * Returns a height (y) value in the Worl system :
  32892. * the ground altitude at the coordinates (x, z) expressed in the World system.
  32893. * Returns the ground y position if (x, z) are outside the ground surface.
  32894. * Not pertinent if the ground is rotated.
  32895. */
  32896. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  32897. // express x and y in the ground local system
  32898. x -= this.position.x;
  32899. z -= this.position.z;
  32900. x /= this.scaling.x;
  32901. z /= this.scaling.z;
  32902. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  32903. return this.position.y;
  32904. }
  32905. if (!this._heightQuads || this._heightQuads.length == 0) {
  32906. this._initHeightQuads();
  32907. this._computeHeightQuads();
  32908. }
  32909. var facet = this._getFacetAt(x, z);
  32910. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  32911. // return y in the World system
  32912. return y * this.scaling.y + this.position.y;
  32913. };
  32914. /**
  32915. * Returns a normalized vector (Vector3) orthogonal to the ground
  32916. * at the ground coordinates (x, z) expressed in the World system.
  32917. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  32918. * Not pertinent if the ground is rotated.
  32919. */
  32920. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  32921. var normal = new BABYLON.Vector3(0, 1, 0);
  32922. this.getNormalAtCoordinatesToRef(x, z, normal);
  32923. return normal;
  32924. };
  32925. /**
  32926. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  32927. * at the ground coordinates (x, z) expressed in the World system.
  32928. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  32929. * Not pertinent if the ground is rotated.
  32930. */
  32931. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  32932. // express x and y in the ground local system
  32933. x -= this.position.x;
  32934. z -= this.position.z;
  32935. x /= this.scaling.x;
  32936. z /= this.scaling.z;
  32937. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  32938. return;
  32939. }
  32940. if (!this._heightQuads || this._heightQuads.length == 0) {
  32941. this._initHeightQuads();
  32942. this._computeHeightQuads();
  32943. }
  32944. var facet = this._getFacetAt(x, z);
  32945. ref.x = facet.x;
  32946. ref.y = facet.y;
  32947. ref.z = facet.z;
  32948. };
  32949. /**
  32950. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  32951. * if the ground has been updated.
  32952. * This can be used in the render loop
  32953. */
  32954. GroundMesh.prototype.updateCoordinateHeights = function () {
  32955. if (!this._heightQuads || this._heightQuads.length == 0) {
  32956. this._initHeightQuads();
  32957. }
  32958. this._computeHeightQuads();
  32959. };
  32960. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  32961. GroundMesh.prototype._getFacetAt = function (x, z) {
  32962. // retrieve col and row from x, z coordinates in the ground local system
  32963. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  32964. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  32965. var quad = this._heightQuads[row * this._subdivisions + col];
  32966. var facet;
  32967. if (z < quad.slope.x * x + quad.slope.y) {
  32968. facet = quad.facet1;
  32969. }
  32970. else {
  32971. facet = quad.facet2;
  32972. }
  32973. return facet;
  32974. };
  32975. // Creates and populates the heightMap array with "facet" elements :
  32976. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  32977. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32978. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32979. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32980. GroundMesh.prototype._initHeightQuads = function () {
  32981. this._heightQuads = new Array();
  32982. for (var row = 0; row < this._subdivisions; row++) {
  32983. for (var col = 0; col < this._subdivisions; col++) {
  32984. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  32985. this._heightQuads[row * this._subdivisions + col] = quad;
  32986. }
  32987. }
  32988. };
  32989. // Compute each quad element values and update the the heightMap array :
  32990. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32991. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32992. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32993. GroundMesh.prototype._computeHeightQuads = function () {
  32994. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32995. var v1 = BABYLON.Tmp.Vector3[0];
  32996. var v2 = BABYLON.Tmp.Vector3[1];
  32997. var v3 = BABYLON.Tmp.Vector3[2];
  32998. var v4 = BABYLON.Tmp.Vector3[3];
  32999. var v1v2 = BABYLON.Tmp.Vector3[4];
  33000. var v1v3 = BABYLON.Tmp.Vector3[5];
  33001. var v1v4 = BABYLON.Tmp.Vector3[6];
  33002. var norm1 = BABYLON.Tmp.Vector3[7];
  33003. var norm2 = BABYLON.Tmp.Vector3[8];
  33004. var i = 0;
  33005. var j = 0;
  33006. var k = 0;
  33007. var cd = 0; // 2D slope coefficient : z = cd * x + h
  33008. var h = 0;
  33009. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  33010. var d2 = 0;
  33011. for (var row = 0; row < this._subdivisions; row++) {
  33012. for (var col = 0; col < this._subdivisions; col++) {
  33013. i = col * 3;
  33014. j = row * (this._subdivisions + 1) * 3;
  33015. k = (row + 1) * (this._subdivisions + 1) * 3;
  33016. v1.x = positions[j + i];
  33017. v1.y = positions[j + i + 1];
  33018. v1.z = positions[j + i + 2];
  33019. v2.x = positions[j + i + 3];
  33020. v2.y = positions[j + i + 4];
  33021. v2.z = positions[j + i + 5];
  33022. v3.x = positions[k + i];
  33023. v3.y = positions[k + i + 1];
  33024. v3.z = positions[k + i + 2];
  33025. v4.x = positions[k + i + 3];
  33026. v4.y = positions[k + i + 4];
  33027. v4.z = positions[k + i + 5];
  33028. // 2D slope V1V4
  33029. cd = (v4.z - v1.z) / (v4.x - v1.x);
  33030. h = v1.z - cd * v1.x; // v1 belongs to the slope
  33031. // facet equations :
  33032. // we compute each facet normal vector
  33033. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  33034. // we compute the value d by applying the equation to v1 which belongs to the plane
  33035. // then we store the facet equation in a Vector4
  33036. v2.subtractToRef(v1, v1v2);
  33037. v3.subtractToRef(v1, v1v3);
  33038. v4.subtractToRef(v1, v1v4);
  33039. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  33040. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  33041. norm1.normalize();
  33042. norm2.normalize();
  33043. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  33044. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  33045. var quad = this._heightQuads[row * this._subdivisions + col];
  33046. quad.slope.copyFromFloats(cd, h);
  33047. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  33048. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  33049. }
  33050. }
  33051. };
  33052. return GroundMesh;
  33053. })(BABYLON.Mesh);
  33054. BABYLON.GroundMesh = GroundMesh;
  33055. })(BABYLON || (BABYLON = {}));
  33056. var BABYLON;
  33057. (function (BABYLON) {
  33058. var LinesMesh = (function (_super) {
  33059. __extends(LinesMesh, _super);
  33060. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  33061. if (parent === void 0) { parent = null; }
  33062. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  33063. this.color = new BABYLON.Color3(1, 1, 1);
  33064. this.alpha = 1;
  33065. if (source) {
  33066. this.color = source.color.clone();
  33067. this.alpha = source.alpha;
  33068. }
  33069. this._intersectionThreshold = 0.1;
  33070. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  33071. attributes: ["position"],
  33072. uniforms: ["worldViewProjection", "color"],
  33073. needAlphaBlending: true
  33074. });
  33075. }
  33076. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  33077. /**
  33078. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33079. * This margin is expressed in world space coordinates, so its value may vary.
  33080. * Default value is 0.1
  33081. * @returns the intersection Threshold value.
  33082. */
  33083. get: function () {
  33084. return this._intersectionThreshold;
  33085. },
  33086. /**
  33087. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33088. * This margin is expressed in world space coordinates, so its value may vary.
  33089. * @param value the new threshold to apply
  33090. */
  33091. set: function (value) {
  33092. if (this._intersectionThreshold === value) {
  33093. return;
  33094. }
  33095. this._intersectionThreshold = value;
  33096. if (this.geometry) {
  33097. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  33098. }
  33099. },
  33100. enumerable: true,
  33101. configurable: true
  33102. });
  33103. Object.defineProperty(LinesMesh.prototype, "material", {
  33104. get: function () {
  33105. return this._colorShader;
  33106. },
  33107. enumerable: true,
  33108. configurable: true
  33109. });
  33110. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  33111. get: function () {
  33112. return false;
  33113. },
  33114. enumerable: true,
  33115. configurable: true
  33116. });
  33117. LinesMesh.prototype.createInstance = function (name) {
  33118. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  33119. return null;
  33120. };
  33121. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  33122. var engine = this.getScene().getEngine();
  33123. var indexToBind = this._geometry.getIndexBuffer();
  33124. // VBOs
  33125. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  33126. // Color
  33127. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  33128. };
  33129. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  33130. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  33131. return;
  33132. }
  33133. var engine = this.getScene().getEngine();
  33134. // Draw order
  33135. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  33136. };
  33137. LinesMesh.prototype.dispose = function (doNotRecurse) {
  33138. this._colorShader.dispose();
  33139. _super.prototype.dispose.call(this, doNotRecurse);
  33140. };
  33141. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  33142. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  33143. };
  33144. return LinesMesh;
  33145. })(BABYLON.Mesh);
  33146. BABYLON.LinesMesh = LinesMesh;
  33147. })(BABYLON || (BABYLON = {}));
  33148. var BABYLON;
  33149. (function (BABYLON) {
  33150. var DefaultLoadingScreen = (function () {
  33151. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33152. var _this = this;
  33153. if (_loadingText === void 0) { _loadingText = ""; }
  33154. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33155. this._renderingCanvas = _renderingCanvas;
  33156. this._loadingText = _loadingText;
  33157. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33158. // Resize
  33159. this._resizeLoadingUI = function () {
  33160. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33161. _this._loadingDiv.style.position = "absolute";
  33162. _this._loadingDiv.style.left = canvasRect.left + "px";
  33163. _this._loadingDiv.style.top = canvasRect.top + "px";
  33164. _this._loadingDiv.style.width = canvasRect.width + "px";
  33165. _this._loadingDiv.style.height = canvasRect.height + "px";
  33166. };
  33167. }
  33168. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33169. var _this = this;
  33170. if (this._loadingDiv) {
  33171. // Do not add a loading screen if there is already one
  33172. return;
  33173. }
  33174. this._loadingDiv = document.createElement("div");
  33175. this._loadingDiv.id = "babylonjsLoadingDiv";
  33176. this._loadingDiv.style.opacity = "0";
  33177. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33178. // Loading text
  33179. this._loadingTextDiv = document.createElement("div");
  33180. this._loadingTextDiv.style.position = "absolute";
  33181. this._loadingTextDiv.style.left = "0";
  33182. this._loadingTextDiv.style.top = "50%";
  33183. this._loadingTextDiv.style.marginTop = "80px";
  33184. this._loadingTextDiv.style.width = "100%";
  33185. this._loadingTextDiv.style.height = "20px";
  33186. this._loadingTextDiv.style.fontFamily = "Arial";
  33187. this._loadingTextDiv.style.fontSize = "14px";
  33188. this._loadingTextDiv.style.color = "white";
  33189. this._loadingTextDiv.style.textAlign = "center";
  33190. this._loadingTextDiv.innerHTML = "Loading";
  33191. this._loadingDiv.appendChild(this._loadingTextDiv);
  33192. //set the predefined text
  33193. this._loadingTextDiv.innerHTML = this._loadingText;
  33194. // Loading img
  33195. var imgBack = new Image();
  33196. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  33197. imgBack.style.position = "absolute";
  33198. imgBack.style.left = "50%";
  33199. imgBack.style.top = "50%";
  33200. imgBack.style.marginLeft = "-50px";
  33201. imgBack.style.marginTop = "-50px";
  33202. imgBack.style.transition = "transform 1.0s ease";
  33203. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33204. var deg = 360;
  33205. var onTransitionEnd = function () {
  33206. deg += 360;
  33207. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33208. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33209. };
  33210. imgBack.addEventListener("transitionend", onTransitionEnd);
  33211. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33212. this._loadingDiv.appendChild(imgBack);
  33213. // front image
  33214. var imgFront = new Image();
  33215. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  33216. imgFront.style.position = "absolute";
  33217. imgFront.style.left = "50%";
  33218. imgFront.style.top = "50%";
  33219. imgFront.style.marginLeft = "-50px";
  33220. imgFront.style.marginTop = "-50px";
  33221. this._loadingDiv.appendChild(imgFront);
  33222. this._resizeLoadingUI();
  33223. window.addEventListener("resize", this._resizeLoadingUI);
  33224. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33225. document.body.appendChild(this._loadingDiv);
  33226. setTimeout(function () {
  33227. _this._loadingDiv.style.opacity = "1";
  33228. imgBack.style.transform = "rotateZ(360deg)";
  33229. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33230. }, 0);
  33231. };
  33232. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33233. var _this = this;
  33234. if (!this._loadingDiv) {
  33235. return;
  33236. }
  33237. var onTransitionEnd = function () {
  33238. if (!_this._loadingDiv) {
  33239. return;
  33240. }
  33241. document.body.removeChild(_this._loadingDiv);
  33242. window.removeEventListener("resize", _this._resizeLoadingUI);
  33243. _this._loadingDiv = null;
  33244. };
  33245. this._loadingDiv.style.opacity = "0";
  33246. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33247. };
  33248. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33249. set: function (text) {
  33250. this._loadingText = text;
  33251. if (this._loadingTextDiv) {
  33252. this._loadingTextDiv.innerHTML = this._loadingText;
  33253. }
  33254. },
  33255. enumerable: true,
  33256. configurable: true
  33257. });
  33258. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33259. get: function () {
  33260. return this._loadingDivBackgroundColor;
  33261. },
  33262. set: function (color) {
  33263. this._loadingDivBackgroundColor = color;
  33264. if (!this._loadingDiv) {
  33265. return;
  33266. }
  33267. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33268. },
  33269. enumerable: true,
  33270. configurable: true
  33271. });
  33272. return DefaultLoadingScreen;
  33273. })();
  33274. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33275. })(BABYLON || (BABYLON = {}));
  33276. var BABYLON;
  33277. (function (BABYLON) {
  33278. var AudioEngine = (function () {
  33279. function AudioEngine() {
  33280. this._audioContext = null;
  33281. this._audioContextInitialized = false;
  33282. this.canUseWebAudio = false;
  33283. this.WarnedWebAudioUnsupported = false;
  33284. this.unlocked = false;
  33285. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33286. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33287. this.canUseWebAudio = true;
  33288. }
  33289. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33290. this._unlockiOSaudio();
  33291. }
  33292. else {
  33293. this.unlocked = true;
  33294. }
  33295. }
  33296. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33297. get: function () {
  33298. if (!this._audioContextInitialized) {
  33299. this._initializeAudioContext();
  33300. }
  33301. return this._audioContext;
  33302. },
  33303. enumerable: true,
  33304. configurable: true
  33305. });
  33306. AudioEngine.prototype._unlockiOSaudio = function () {
  33307. var _this = this;
  33308. var unlockaudio = function () {
  33309. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33310. var source = _this.audioContext.createBufferSource();
  33311. source.buffer = buffer;
  33312. source.connect(_this.audioContext.destination);
  33313. source.start(0);
  33314. setTimeout(function () {
  33315. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33316. _this.unlocked = true;
  33317. window.removeEventListener('touchend', unlockaudio, false);
  33318. if (_this.onAudioUnlocked) {
  33319. _this.onAudioUnlocked();
  33320. }
  33321. }
  33322. }, 0);
  33323. };
  33324. window.addEventListener('touchend', unlockaudio, false);
  33325. };
  33326. AudioEngine.prototype._initializeAudioContext = function () {
  33327. try {
  33328. if (this.canUseWebAudio) {
  33329. this._audioContext = new AudioContext();
  33330. // create a global volume gain node
  33331. this.masterGain = this._audioContext.createGain();
  33332. this.masterGain.gain.value = 1;
  33333. this.masterGain.connect(this._audioContext.destination);
  33334. this._audioContextInitialized = true;
  33335. }
  33336. }
  33337. catch (e) {
  33338. this.canUseWebAudio = false;
  33339. BABYLON.Tools.Error("Web Audio: " + e.message);
  33340. }
  33341. };
  33342. AudioEngine.prototype.dispose = function () {
  33343. if (this.canUseWebAudio && this._audioContextInitialized) {
  33344. if (this._connectedAnalyser) {
  33345. this._connectedAnalyser.stopDebugCanvas();
  33346. this._connectedAnalyser.dispose();
  33347. this.masterGain.disconnect();
  33348. this.masterGain.connect(this._audioContext.destination);
  33349. this._connectedAnalyser = null;
  33350. }
  33351. this.masterGain.gain.value = 1;
  33352. }
  33353. this.WarnedWebAudioUnsupported = false;
  33354. };
  33355. AudioEngine.prototype.getGlobalVolume = function () {
  33356. if (this.canUseWebAudio && this._audioContextInitialized) {
  33357. return this.masterGain.gain.value;
  33358. }
  33359. else {
  33360. return -1;
  33361. }
  33362. };
  33363. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33364. if (this.canUseWebAudio && this._audioContextInitialized) {
  33365. this.masterGain.gain.value = newVolume;
  33366. }
  33367. };
  33368. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33369. if (this._connectedAnalyser) {
  33370. this._connectedAnalyser.stopDebugCanvas();
  33371. }
  33372. if (this.canUseWebAudio && this._audioContextInitialized) {
  33373. this._connectedAnalyser = analyser;
  33374. this.masterGain.disconnect();
  33375. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33376. }
  33377. };
  33378. return AudioEngine;
  33379. })();
  33380. BABYLON.AudioEngine = AudioEngine;
  33381. })(BABYLON || (BABYLON = {}));
  33382. var BABYLON;
  33383. (function (BABYLON) {
  33384. var Sound = (function () {
  33385. /**
  33386. * Create a sound and attach it to a scene
  33387. * @param name Name of your sound
  33388. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33389. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33390. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33391. */
  33392. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33393. var _this = this;
  33394. this.autoplay = false;
  33395. this.loop = false;
  33396. this.useCustomAttenuation = false;
  33397. this.spatialSound = false;
  33398. this.refDistance = 1;
  33399. this.rolloffFactor = 1;
  33400. this.maxDistance = 100;
  33401. this.distanceModel = "linear";
  33402. this._panningModel = "equalpower";
  33403. this._playbackRate = 1;
  33404. this._streaming = false;
  33405. this._startTime = 0;
  33406. this._startOffset = 0;
  33407. this._position = BABYLON.Vector3.Zero();
  33408. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33409. this._volume = 1;
  33410. this._isLoaded = false;
  33411. this._isReadyToPlay = false;
  33412. this.isPlaying = false;
  33413. this.isPaused = false;
  33414. this._isDirectional = false;
  33415. // Used if you'd like to create a directional sound.
  33416. // If not set, the sound will be omnidirectional
  33417. this._coneInnerAngle = 360;
  33418. this._coneOuterAngle = 360;
  33419. this._coneOuterGain = 0;
  33420. this._isOutputConnected = false;
  33421. this.name = name;
  33422. this._scene = scene;
  33423. this._readyToPlayCallback = readyToPlayCallback;
  33424. // Default custom attenuation function is a linear attenuation
  33425. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33426. if (currentDistance < maxDistance) {
  33427. return currentVolume * (1 - currentDistance / maxDistance);
  33428. }
  33429. else {
  33430. return 0;
  33431. }
  33432. };
  33433. if (options) {
  33434. this.autoplay = options.autoplay || false;
  33435. this.loop = options.loop || false;
  33436. // if volume === 0, we need another way to check this option
  33437. if (options.volume !== undefined) {
  33438. this._volume = options.volume;
  33439. }
  33440. this.spatialSound = options.spatialSound || false;
  33441. this.maxDistance = options.maxDistance || 100;
  33442. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33443. this.rolloffFactor = options.rolloffFactor || 1;
  33444. this.refDistance = options.refDistance || 1;
  33445. this.distanceModel = options.distanceModel || "linear";
  33446. this._playbackRate = options.playbackRate || 1;
  33447. this._streaming = options.streaming || false;
  33448. }
  33449. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33450. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33451. this._soundGain.gain.value = this._volume;
  33452. this._inputAudioNode = this._soundGain;
  33453. this._ouputAudioNode = this._soundGain;
  33454. if (this.spatialSound) {
  33455. this._createSpatialParameters();
  33456. }
  33457. this._scene.mainSoundTrack.AddSound(this);
  33458. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33459. if (urlOrArrayBuffer) {
  33460. // If it's an URL
  33461. if (typeof (urlOrArrayBuffer) === "string") {
  33462. // Loading sound using XHR2
  33463. if (!this._streaming) {
  33464. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33465. }
  33466. else {
  33467. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33468. this._htmlAudioElement.controls = false;
  33469. this._htmlAudioElement.loop = this.loop;
  33470. this._htmlAudioElement.crossOrigin = "anonymous";
  33471. this._htmlAudioElement.preload = "auto";
  33472. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33473. _this._isReadyToPlay = true;
  33474. if (_this.autoplay) {
  33475. _this.play();
  33476. }
  33477. if (_this._readyToPlayCallback) {
  33478. _this._readyToPlayCallback();
  33479. }
  33480. });
  33481. document.body.appendChild(this._htmlAudioElement);
  33482. }
  33483. }
  33484. else {
  33485. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33486. if (urlOrArrayBuffer.byteLength > 0) {
  33487. this._soundLoaded(urlOrArrayBuffer);
  33488. }
  33489. }
  33490. else {
  33491. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33492. }
  33493. }
  33494. }
  33495. }
  33496. else {
  33497. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33498. this._scene.mainSoundTrack.AddSound(this);
  33499. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33500. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33501. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33502. }
  33503. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33504. if (this._readyToPlayCallback) {
  33505. window.setTimeout(function () {
  33506. _this._readyToPlayCallback();
  33507. }, 1000);
  33508. }
  33509. }
  33510. }
  33511. Sound.prototype.dispose = function () {
  33512. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33513. if (this.isPlaying) {
  33514. this.stop();
  33515. }
  33516. this._isReadyToPlay = false;
  33517. if (this.soundTrackId === -1) {
  33518. this._scene.mainSoundTrack.RemoveSound(this);
  33519. }
  33520. else {
  33521. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33522. }
  33523. if (this._soundGain) {
  33524. this._soundGain.disconnect();
  33525. this._soundGain = null;
  33526. }
  33527. if (this._soundPanner) {
  33528. this._soundPanner.disconnect();
  33529. this._soundPanner = null;
  33530. }
  33531. if (this._soundSource) {
  33532. this._soundSource.disconnect();
  33533. this._soundSource = null;
  33534. }
  33535. this._audioBuffer = null;
  33536. if (this._htmlAudioElement) {
  33537. this._htmlAudioElement.pause();
  33538. this._htmlAudioElement.src = "";
  33539. document.body.removeChild(this._htmlAudioElement);
  33540. }
  33541. if (this._connectedMesh) {
  33542. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33543. this._connectedMesh = null;
  33544. }
  33545. }
  33546. };
  33547. Sound.prototype._soundLoaded = function (audioData) {
  33548. var _this = this;
  33549. this._isLoaded = true;
  33550. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33551. _this._audioBuffer = buffer;
  33552. _this._isReadyToPlay = true;
  33553. if (_this.autoplay) {
  33554. _this.play();
  33555. }
  33556. if (_this._readyToPlayCallback) {
  33557. _this._readyToPlayCallback();
  33558. }
  33559. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33560. };
  33561. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33562. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33563. this._audioBuffer = audioBuffer;
  33564. this._isReadyToPlay = true;
  33565. }
  33566. };
  33567. Sound.prototype.updateOptions = function (options) {
  33568. if (options) {
  33569. this.loop = options.loop || this.loop;
  33570. this.maxDistance = options.maxDistance || this.maxDistance;
  33571. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33572. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33573. this.refDistance = options.refDistance || this.refDistance;
  33574. this.distanceModel = options.distanceModel || this.distanceModel;
  33575. this._playbackRate = options.playbackRate || this._playbackRate;
  33576. this._updateSpatialParameters();
  33577. if (this.isPlaying) {
  33578. if (this._streaming) {
  33579. this._htmlAudioElement.playbackRate = this._playbackRate;
  33580. }
  33581. else {
  33582. this._soundSource.playbackRate.value = this._playbackRate;
  33583. }
  33584. }
  33585. }
  33586. };
  33587. Sound.prototype._createSpatialParameters = function () {
  33588. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33589. if (this._scene.headphone) {
  33590. this._panningModel = "HRTF";
  33591. }
  33592. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33593. this._updateSpatialParameters();
  33594. this._soundPanner.connect(this._ouputAudioNode);
  33595. this._inputAudioNode = this._soundPanner;
  33596. }
  33597. };
  33598. Sound.prototype._updateSpatialParameters = function () {
  33599. if (this.spatialSound) {
  33600. if (this.useCustomAttenuation) {
  33601. // Tricks to disable in a way embedded Web Audio attenuation
  33602. this._soundPanner.distanceModel = "linear";
  33603. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33604. this._soundPanner.refDistance = 1;
  33605. this._soundPanner.rolloffFactor = 1;
  33606. this._soundPanner.panningModel = this._panningModel;
  33607. }
  33608. else {
  33609. this._soundPanner.distanceModel = this.distanceModel;
  33610. this._soundPanner.maxDistance = this.maxDistance;
  33611. this._soundPanner.refDistance = this.refDistance;
  33612. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33613. this._soundPanner.panningModel = this._panningModel;
  33614. }
  33615. }
  33616. };
  33617. Sound.prototype.switchPanningModelToHRTF = function () {
  33618. this._panningModel = "HRTF";
  33619. this._switchPanningModel();
  33620. };
  33621. Sound.prototype.switchPanningModelToEqualPower = function () {
  33622. this._panningModel = "equalpower";
  33623. this._switchPanningModel();
  33624. };
  33625. Sound.prototype._switchPanningModel = function () {
  33626. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33627. this._soundPanner.panningModel = this._panningModel;
  33628. }
  33629. };
  33630. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33631. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33632. if (this._isOutputConnected) {
  33633. this._ouputAudioNode.disconnect();
  33634. }
  33635. this._ouputAudioNode.connect(soundTrackAudioNode);
  33636. this._isOutputConnected = true;
  33637. }
  33638. };
  33639. /**
  33640. * Transform this sound into a directional source
  33641. * @param coneInnerAngle Size of the inner cone in degree
  33642. * @param coneOuterAngle Size of the outer cone in degree
  33643. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33644. */
  33645. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33646. if (coneOuterAngle < coneInnerAngle) {
  33647. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33648. return;
  33649. }
  33650. this._coneInnerAngle = coneInnerAngle;
  33651. this._coneOuterAngle = coneOuterAngle;
  33652. this._coneOuterGain = coneOuterGain;
  33653. this._isDirectional = true;
  33654. if (this.isPlaying && this.loop) {
  33655. this.stop();
  33656. this.play();
  33657. }
  33658. };
  33659. Sound.prototype.setPosition = function (newPosition) {
  33660. this._position = newPosition;
  33661. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33662. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33663. }
  33664. };
  33665. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33666. this._localDirection = newLocalDirection;
  33667. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33668. this._updateDirection();
  33669. }
  33670. };
  33671. Sound.prototype._updateDirection = function () {
  33672. var mat = this._connectedMesh.getWorldMatrix();
  33673. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33674. direction.normalize();
  33675. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33676. };
  33677. Sound.prototype.updateDistanceFromListener = function () {
  33678. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33679. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33680. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33681. }
  33682. };
  33683. Sound.prototype.setAttenuationFunction = function (callback) {
  33684. this._customAttenuationFunction = callback;
  33685. };
  33686. /**
  33687. * Play the sound
  33688. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33689. */
  33690. Sound.prototype.play = function (time) {
  33691. var _this = this;
  33692. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33693. try {
  33694. if (this._startOffset < 0) {
  33695. time = -this._startOffset;
  33696. this._startOffset = 0;
  33697. }
  33698. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33699. if (!this._soundSource || !this._streamingSource) {
  33700. if (this.spatialSound) {
  33701. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33702. if (this._isDirectional) {
  33703. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33704. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33705. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33706. if (this._connectedMesh) {
  33707. this._updateDirection();
  33708. }
  33709. else {
  33710. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33711. }
  33712. }
  33713. }
  33714. }
  33715. if (this._streaming) {
  33716. if (!this._streamingSource) {
  33717. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33718. this._htmlAudioElement.onended = function () { _this._onended(); };
  33719. this._htmlAudioElement.playbackRate = this._playbackRate;
  33720. }
  33721. this._streamingSource.disconnect();
  33722. this._streamingSource.connect(this._inputAudioNode);
  33723. this._htmlAudioElement.play();
  33724. }
  33725. else {
  33726. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33727. this._soundSource.buffer = this._audioBuffer;
  33728. this._soundSource.connect(this._inputAudioNode);
  33729. this._soundSource.loop = this.loop;
  33730. this._soundSource.playbackRate.value = this._playbackRate;
  33731. this._soundSource.onended = function () { _this._onended(); };
  33732. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33733. }
  33734. this._startTime = startTime;
  33735. this.isPlaying = true;
  33736. this.isPaused = false;
  33737. }
  33738. catch (ex) {
  33739. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33740. }
  33741. }
  33742. };
  33743. Sound.prototype._onended = function () {
  33744. this.isPlaying = false;
  33745. if (this.onended) {
  33746. this.onended();
  33747. }
  33748. };
  33749. /**
  33750. * Stop the sound
  33751. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33752. */
  33753. Sound.prototype.stop = function (time) {
  33754. if (this.isPlaying) {
  33755. if (this._streaming) {
  33756. this._htmlAudioElement.pause();
  33757. // Test needed for Firefox or it will generate an Invalid State Error
  33758. if (this._htmlAudioElement.currentTime > 0) {
  33759. this._htmlAudioElement.currentTime = 0;
  33760. }
  33761. }
  33762. else {
  33763. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33764. this._soundSource.stop(stopTime);
  33765. if (!this.isPaused) {
  33766. this._startOffset = 0;
  33767. }
  33768. }
  33769. this.isPlaying = false;
  33770. }
  33771. };
  33772. Sound.prototype.pause = function () {
  33773. if (this.isPlaying) {
  33774. this.isPaused = true;
  33775. if (this._streaming) {
  33776. this._htmlAudioElement.pause();
  33777. }
  33778. else {
  33779. this.stop(0);
  33780. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33781. }
  33782. }
  33783. };
  33784. Sound.prototype.setVolume = function (newVolume, time) {
  33785. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33786. if (time) {
  33787. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  33788. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33789. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  33790. }
  33791. else {
  33792. this._soundGain.gain.value = newVolume;
  33793. }
  33794. }
  33795. this._volume = newVolume;
  33796. };
  33797. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33798. this._playbackRate = newPlaybackRate;
  33799. if (this.isPlaying) {
  33800. if (this._streaming) {
  33801. this._htmlAudioElement.playbackRate = this._playbackRate;
  33802. }
  33803. else {
  33804. this._soundSource.playbackRate.value = this._playbackRate;
  33805. }
  33806. }
  33807. };
  33808. Sound.prototype.getVolume = function () {
  33809. return this._volume;
  33810. };
  33811. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33812. var _this = this;
  33813. if (this._connectedMesh) {
  33814. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33815. this._registerFunc = null;
  33816. }
  33817. this._connectedMesh = meshToConnectTo;
  33818. if (!this.spatialSound) {
  33819. this.spatialSound = true;
  33820. this._createSpatialParameters();
  33821. if (this.isPlaying && this.loop) {
  33822. this.stop();
  33823. this.play();
  33824. }
  33825. }
  33826. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33827. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33828. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33829. };
  33830. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33831. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33832. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33833. this._updateDirection();
  33834. }
  33835. };
  33836. Sound.prototype.clone = function () {
  33837. var _this = this;
  33838. if (!this._streaming) {
  33839. var setBufferAndRun = function () {
  33840. if (_this._isReadyToPlay) {
  33841. clonedSound._audioBuffer = _this.getAudioBuffer();
  33842. clonedSound._isReadyToPlay = true;
  33843. if (clonedSound.autoplay) {
  33844. clonedSound.play();
  33845. }
  33846. }
  33847. else {
  33848. window.setTimeout(setBufferAndRun, 300);
  33849. }
  33850. };
  33851. var currentOptions = {
  33852. autoplay: this.autoplay, loop: this.loop,
  33853. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  33854. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  33855. refDistance: this.refDistance, distanceModel: this.distanceModel
  33856. };
  33857. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  33858. if (this.useCustomAttenuation) {
  33859. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  33860. }
  33861. clonedSound.setPosition(this._position);
  33862. clonedSound.setPlaybackRate(this._playbackRate);
  33863. setBufferAndRun();
  33864. return clonedSound;
  33865. }
  33866. else {
  33867. return null;
  33868. }
  33869. };
  33870. Sound.prototype.getAudioBuffer = function () {
  33871. return this._audioBuffer;
  33872. };
  33873. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  33874. var soundName = parsedSound.name;
  33875. var soundUrl;
  33876. if (parsedSound.url) {
  33877. soundUrl = rootUrl + parsedSound.url;
  33878. }
  33879. else {
  33880. soundUrl = rootUrl + soundName;
  33881. }
  33882. var options = {
  33883. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33884. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33885. rolloffFactor: parsedSound.rolloffFactor,
  33886. refDistance: parsedSound.refDistance,
  33887. distanceModel: parsedSound.distanceModel,
  33888. playbackRate: parsedSound.playbackRate
  33889. };
  33890. var newSound;
  33891. if (!sourceSound) {
  33892. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33893. scene._addPendingData(newSound);
  33894. }
  33895. else {
  33896. var setBufferAndRun = function () {
  33897. if (sourceSound._isReadyToPlay) {
  33898. newSound._audioBuffer = sourceSound.getAudioBuffer();
  33899. newSound._isReadyToPlay = true;
  33900. if (newSound.autoplay) {
  33901. newSound.play();
  33902. }
  33903. }
  33904. else {
  33905. window.setTimeout(setBufferAndRun, 300);
  33906. }
  33907. };
  33908. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  33909. setBufferAndRun();
  33910. }
  33911. if (parsedSound.position) {
  33912. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33913. newSound.setPosition(soundPosition);
  33914. }
  33915. if (parsedSound.isDirectional) {
  33916. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33917. if (parsedSound.localDirectionToMesh) {
  33918. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33919. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33920. }
  33921. }
  33922. if (parsedSound.connectedMeshId) {
  33923. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33924. if (connectedMesh) {
  33925. newSound.attachToMesh(connectedMesh);
  33926. }
  33927. }
  33928. return newSound;
  33929. };
  33930. return Sound;
  33931. })();
  33932. BABYLON.Sound = Sound;
  33933. })(BABYLON || (BABYLON = {}));
  33934. var BABYLON;
  33935. (function (BABYLON) {
  33936. var SoundTrack = (function () {
  33937. function SoundTrack(scene, options) {
  33938. this.id = -1;
  33939. this._isMainTrack = false;
  33940. this._isInitialized = false;
  33941. this._scene = scene;
  33942. this.soundCollection = new Array();
  33943. this._options = options;
  33944. if (!this._isMainTrack) {
  33945. this._scene.soundTracks.push(this);
  33946. this.id = this._scene.soundTracks.length - 1;
  33947. }
  33948. }
  33949. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33950. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33951. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33952. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33953. if (this._options) {
  33954. if (this._options.volume) {
  33955. this._outputAudioNode.gain.value = this._options.volume;
  33956. }
  33957. if (this._options.mainTrack) {
  33958. this._isMainTrack = this._options.mainTrack;
  33959. }
  33960. }
  33961. this._isInitialized = true;
  33962. }
  33963. };
  33964. SoundTrack.prototype.dispose = function () {
  33965. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33966. if (this._connectedAnalyser) {
  33967. this._connectedAnalyser.stopDebugCanvas();
  33968. }
  33969. while (this.soundCollection.length) {
  33970. this.soundCollection[0].dispose();
  33971. }
  33972. if (this._outputAudioNode) {
  33973. this._outputAudioNode.disconnect();
  33974. }
  33975. this._outputAudioNode = null;
  33976. }
  33977. };
  33978. SoundTrack.prototype.AddSound = function (sound) {
  33979. if (!this._isInitialized) {
  33980. this._initializeSoundTrackAudioGraph();
  33981. }
  33982. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33983. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33984. }
  33985. if (sound.soundTrackId) {
  33986. if (sound.soundTrackId === -1) {
  33987. this._scene.mainSoundTrack.RemoveSound(sound);
  33988. }
  33989. else {
  33990. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33991. }
  33992. }
  33993. this.soundCollection.push(sound);
  33994. sound.soundTrackId = this.id;
  33995. };
  33996. SoundTrack.prototype.RemoveSound = function (sound) {
  33997. var index = this.soundCollection.indexOf(sound);
  33998. if (index !== -1) {
  33999. this.soundCollection.splice(index, 1);
  34000. }
  34001. };
  34002. SoundTrack.prototype.setVolume = function (newVolume) {
  34003. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34004. this._outputAudioNode.gain.value = newVolume;
  34005. }
  34006. };
  34007. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34008. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34009. for (var i = 0; i < this.soundCollection.length; i++) {
  34010. this.soundCollection[i].switchPanningModelToHRTF();
  34011. }
  34012. }
  34013. };
  34014. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34015. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34016. for (var i = 0; i < this.soundCollection.length; i++) {
  34017. this.soundCollection[i].switchPanningModelToEqualPower();
  34018. }
  34019. }
  34020. };
  34021. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34022. if (this._connectedAnalyser) {
  34023. this._connectedAnalyser.stopDebugCanvas();
  34024. }
  34025. this._connectedAnalyser = analyser;
  34026. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34027. this._outputAudioNode.disconnect();
  34028. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34029. }
  34030. };
  34031. return SoundTrack;
  34032. })();
  34033. BABYLON.SoundTrack = SoundTrack;
  34034. })(BABYLON || (BABYLON = {}));
  34035. var BABYLON;
  34036. (function (BABYLON) {
  34037. var SIMDVector3 = (function () {
  34038. function SIMDVector3() {
  34039. }
  34040. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  34041. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  34042. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34043. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34044. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34045. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34046. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  34047. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34048. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34049. };
  34050. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  34051. var v0 = SIMD.float32x4.splat(x);
  34052. var v1 = SIMD.float32x4.splat(y);
  34053. var v2 = SIMD.float32x4.splat(z);
  34054. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34055. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34056. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34057. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34058. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  34059. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34060. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34061. };
  34062. return SIMDVector3;
  34063. })();
  34064. BABYLON.SIMDVector3 = SIMDVector3;
  34065. var SIMDMatrix = (function () {
  34066. function SIMDMatrix() {
  34067. }
  34068. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  34069. if (offset === void 0) { offset = 0; }
  34070. var tm = this.m;
  34071. var om = other.m;
  34072. var om0 = SIMD.float32x4.load(om, 0);
  34073. var om1 = SIMD.float32x4.load(om, 4);
  34074. var om2 = SIMD.float32x4.load(om, 8);
  34075. var om3 = SIMD.float32x4.load(om, 12);
  34076. var tm0 = SIMD.float32x4.load(tm, 0);
  34077. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  34078. var tm1 = SIMD.float32x4.load(tm, 4);
  34079. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  34080. var tm2 = SIMD.float32x4.load(tm, 8);
  34081. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  34082. var tm3 = SIMD.float32x4.load(tm, 12);
  34083. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  34084. };
  34085. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  34086. var src = this.m;
  34087. var dest = other.m;
  34088. var row0, row1, row2, row3;
  34089. var tmp1;
  34090. var minor0, minor1, minor2, minor3;
  34091. var det;
  34092. // Load the 4 rows
  34093. var src0 = SIMD.float32x4.load(src, 0);
  34094. var src1 = SIMD.float32x4.load(src, 4);
  34095. var src2 = SIMD.float32x4.load(src, 8);
  34096. var src3 = SIMD.float32x4.load(src, 12);
  34097. // Transpose the source matrix. Sort of. Not a true transpose operation
  34098. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34099. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34100. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  34101. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  34102. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34103. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34104. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  34105. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  34106. // This is a true transposition, but it will lead to an incorrect result
  34107. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34108. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34109. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34110. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34111. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34112. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34113. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34114. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34115. // ----
  34116. tmp1 = SIMD.float32x4.mul(row2, row3);
  34117. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34118. minor0 = SIMD.float32x4.mul(row1, tmp1);
  34119. minor1 = SIMD.float32x4.mul(row0, tmp1);
  34120. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34121. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  34122. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  34123. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  34124. // ----
  34125. tmp1 = SIMD.float32x4.mul(row1, row2);
  34126. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34127. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  34128. minor3 = SIMD.float32x4.mul(row0, tmp1);
  34129. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34130. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  34131. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  34132. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  34133. // ----
  34134. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  34135. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34136. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  34137. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  34138. minor2 = SIMD.float32x4.mul(row0, tmp1);
  34139. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34140. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  34141. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  34142. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  34143. // ----
  34144. tmp1 = SIMD.float32x4.mul(row0, row1);
  34145. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34146. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  34147. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  34148. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34149. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  34150. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  34151. // ----
  34152. tmp1 = SIMD.float32x4.mul(row0, row3);
  34153. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34154. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  34155. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  34156. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34157. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  34158. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  34159. // ----
  34160. tmp1 = SIMD.float32x4.mul(row0, row2);
  34161. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34162. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  34163. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  34164. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34165. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  34166. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  34167. // Compute determinant
  34168. det = SIMD.float32x4.mul(row0, minor0);
  34169. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  34170. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  34171. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  34172. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  34173. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  34174. // These shuffles aren't necessary if the faulty transposition is done
  34175. // up at the top of this function.
  34176. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  34177. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  34178. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  34179. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  34180. // Compute final values by multiplying with 1/det
  34181. minor0 = SIMD.float32x4.mul(det, minor0);
  34182. minor1 = SIMD.float32x4.mul(det, minor1);
  34183. minor2 = SIMD.float32x4.mul(det, minor2);
  34184. minor3 = SIMD.float32x4.mul(det, minor3);
  34185. SIMD.float32x4.store(dest, 0, minor0);
  34186. SIMD.float32x4.store(dest, 4, minor1);
  34187. SIMD.float32x4.store(dest, 8, minor2);
  34188. SIMD.float32x4.store(dest, 12, minor3);
  34189. return this;
  34190. };
  34191. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  34192. var out = result.m;
  34193. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  34194. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  34195. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  34196. // cc.kmVec3Subtract(f, pCenter, pEye);
  34197. var f = SIMD.float32x4.sub(center, eye);
  34198. // cc.kmVec3Normalize(f, f);
  34199. var tmp = SIMD.float32x4.mul(f, f);
  34200. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34201. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34202. // cc.kmVec3Assign(up, pUp);
  34203. // cc.kmVec3Normalize(up, up);
  34204. tmp = SIMD.float32x4.mul(up, up);
  34205. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34206. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34207. // cc.kmVec3Cross(s, f, up);
  34208. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  34209. // cc.kmVec3Normalize(s, s);
  34210. tmp = SIMD.float32x4.mul(s, s);
  34211. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34212. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34213. // cc.kmVec3Cross(u, s, f);
  34214. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  34215. // cc.kmVec3Normalize(s, s);
  34216. tmp = SIMD.float32x4.mul(s, s);
  34217. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34218. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34219. var zero = SIMD.float32x4.splat(0.0);
  34220. s = SIMD.float32x4.neg(s);
  34221. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  34222. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  34223. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34224. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  34225. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  34226. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  34227. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34228. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  34229. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  34230. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  34231. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  34232. var b3 = SIMD.float32x4.neg(eye);
  34233. b3 = SIMD.float32x4.withW(b3, 1.0);
  34234. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  34235. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  34236. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  34237. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  34238. };
  34239. return SIMDMatrix;
  34240. })();
  34241. BABYLON.SIMDMatrix = SIMDMatrix;
  34242. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  34243. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  34244. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  34245. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  34246. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  34247. var SIMDHelper = (function () {
  34248. function SIMDHelper() {
  34249. }
  34250. Object.defineProperty(SIMDHelper, "IsEnabled", {
  34251. get: function () {
  34252. return SIMDHelper._isEnabled;
  34253. },
  34254. enumerable: true,
  34255. configurable: true
  34256. });
  34257. SIMDHelper.DisableSIMD = function () {
  34258. // Replace functions
  34259. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  34260. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  34261. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  34262. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  34263. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  34264. SIMDHelper._isEnabled = false;
  34265. };
  34266. SIMDHelper.EnableSIMD = function () {
  34267. if (window.SIMD === undefined) {
  34268. return;
  34269. }
  34270. // Replace functions
  34271. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34272. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34273. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34274. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34275. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34276. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34277. get: function () { return this._data[0]; },
  34278. set: function (value) {
  34279. if (!this._data) {
  34280. this._data = new Float32Array(3);
  34281. }
  34282. this._data[0] = value;
  34283. }
  34284. });
  34285. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34286. get: function () { return this._data[1]; },
  34287. set: function (value) {
  34288. this._data[1] = value;
  34289. }
  34290. });
  34291. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34292. get: function () { return this._data[2]; },
  34293. set: function (value) {
  34294. this._data[2] = value;
  34295. }
  34296. });
  34297. SIMDHelper._isEnabled = true;
  34298. };
  34299. SIMDHelper._isEnabled = false;
  34300. return SIMDHelper;
  34301. })();
  34302. BABYLON.SIMDHelper = SIMDHelper;
  34303. })(BABYLON || (BABYLON = {}));
  34304. var BABYLON;
  34305. (function (BABYLON) {
  34306. /**
  34307. * This class describe a rectangle that were added to the map.
  34308. * You have access to its coordinates either in pixel or normalized (UV)
  34309. */
  34310. var PackedRect = (function () {
  34311. function PackedRect(root, parent, pos, size) {
  34312. this._pos = pos;
  34313. this._size = size;
  34314. this._root = root;
  34315. this._parent = parent;
  34316. }
  34317. Object.defineProperty(PackedRect.prototype, "pos", {
  34318. /**
  34319. * @returns the position of this node into the map
  34320. */
  34321. get: function () {
  34322. return this._pos;
  34323. },
  34324. enumerable: true,
  34325. configurable: true
  34326. });
  34327. Object.defineProperty(PackedRect.prototype, "contentSize", {
  34328. /**
  34329. * @returns the size of the rectangle this node handles
  34330. */
  34331. get: function () {
  34332. return this._contentSize;
  34333. },
  34334. enumerable: true,
  34335. configurable: true
  34336. });
  34337. Object.defineProperty(PackedRect.prototype, "UVs", {
  34338. /**
  34339. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  34340. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  34341. */
  34342. get: function () {
  34343. var mainWidth = this._root._size.width;
  34344. var mainHeight = this._root._size.height;
  34345. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  34346. var rightBottom = new BABYLON.Vector2((this._pos.x + this._contentSize.width - 1) / mainWidth, (this._pos.y + this._contentSize.height - 1) / mainHeight);
  34347. var uvs = new Array();
  34348. uvs.push(topLeft);
  34349. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  34350. uvs.push(rightBottom);
  34351. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  34352. return uvs;
  34353. },
  34354. enumerable: true,
  34355. configurable: true
  34356. });
  34357. /**
  34358. * Free this rectangle from the map.
  34359. * Call this method when you no longer need the rectangle to be in the map.
  34360. */
  34361. PackedRect.prototype.freeContent = function () {
  34362. if (!this.contentSize) {
  34363. return;
  34364. }
  34365. this._contentSize = null;
  34366. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  34367. this.attemptDefrag();
  34368. };
  34369. Object.defineProperty(PackedRect.prototype, "isUsed", {
  34370. get: function () {
  34371. return this._contentSize != null || this._leftNode != null;
  34372. },
  34373. enumerable: true,
  34374. configurable: true
  34375. });
  34376. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  34377. var node = this.findNode(contentSize);
  34378. // Not enough space...
  34379. if (!node) {
  34380. return null;
  34381. }
  34382. node.splitNode(contentSize);
  34383. return node;
  34384. };
  34385. PackedRect.prototype.findNode = function (size) {
  34386. var resNode = null;
  34387. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  34388. if (this.isUsed) {
  34389. if (this._leftNode) {
  34390. resNode = this._leftNode.findNode(size);
  34391. }
  34392. if (!resNode && this._rightNode) {
  34393. resNode = this._rightNode.findNode(size);
  34394. }
  34395. if (!resNode && this._bottomNode) {
  34396. resNode = this._bottomNode.findNode(size);
  34397. }
  34398. }
  34399. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  34400. resNode = this;
  34401. }
  34402. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  34403. resNode = this;
  34404. }
  34405. return resNode;
  34406. };
  34407. PackedRect.prototype.splitNode = function (contentSize) {
  34408. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  34409. if (!this._contentSize && this._initialSize) {
  34410. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  34411. return this._leftNode.splitNode(contentSize);
  34412. }
  34413. else {
  34414. this._contentSize = contentSize.clone();
  34415. this._initialSize = contentSize.clone();
  34416. if (contentSize.width !== this._size.width) {
  34417. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  34418. }
  34419. if (contentSize.height !== this._size.height) {
  34420. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  34421. }
  34422. return this;
  34423. }
  34424. };
  34425. PackedRect.prototype.attemptDefrag = function () {
  34426. if (!this.isUsed && this.isRecursiveFree) {
  34427. this.clearNode();
  34428. if (this._parent) {
  34429. this._parent.attemptDefrag();
  34430. }
  34431. }
  34432. };
  34433. PackedRect.prototype.clearNode = function () {
  34434. this._initialSize = null;
  34435. this._rightNode = null;
  34436. this._bottomNode = null;
  34437. };
  34438. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  34439. get: function () {
  34440. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  34441. },
  34442. enumerable: true,
  34443. configurable: true
  34444. });
  34445. PackedRect.prototype.evalFreeSize = function (size) {
  34446. var levelSize = 0;
  34447. if (!this.isUsed) {
  34448. if (this._initialSize) {
  34449. levelSize = this._initialSize.surface;
  34450. }
  34451. else {
  34452. levelSize = this._size.surface;
  34453. }
  34454. }
  34455. if (this._rightNode) {
  34456. levelSize += this._rightNode.evalFreeSize(0);
  34457. }
  34458. if (this._bottomNode) {
  34459. levelSize += this._bottomNode.evalFreeSize(0);
  34460. }
  34461. return levelSize + size;
  34462. };
  34463. return PackedRect;
  34464. })();
  34465. BABYLON.PackedRect = PackedRect;
  34466. /**
  34467. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  34468. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  34469. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  34470. */
  34471. var RectPackingMap = (function (_super) {
  34472. __extends(RectPackingMap, _super);
  34473. /**
  34474. * Create an instance of the object with a dimension using the given size
  34475. * @param size The dimension of the rectangle that will contain all the sub ones.
  34476. */
  34477. function RectPackingMap(size) {
  34478. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  34479. this._root = this;
  34480. }
  34481. /**
  34482. * Add a rectangle, finding the best location to store it into the map
  34483. * @param size the dimension of the rectangle to store
  34484. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  34485. */
  34486. RectPackingMap.prototype.addRect = function (size) {
  34487. var node = this.findAndSplitNode(size);
  34488. return node;
  34489. };
  34490. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  34491. /**
  34492. * Return the current space free normalized between [0;1]
  34493. * @returns {}
  34494. */
  34495. get: function () {
  34496. var freeSize = 0;
  34497. freeSize = this.evalFreeSize(freeSize);
  34498. return freeSize / (this._size.width * this._size.height);
  34499. },
  34500. enumerable: true,
  34501. configurable: true
  34502. });
  34503. return RectPackingMap;
  34504. })(PackedRect);
  34505. BABYLON.RectPackingMap = RectPackingMap;
  34506. })(BABYLON || (BABYLON = {}));
  34507. var BABYLON;
  34508. (function (BABYLON) {
  34509. var DynamicFloatArrayElementInfo = (function () {
  34510. function DynamicFloatArrayElementInfo() {
  34511. }
  34512. return DynamicFloatArrayElementInfo;
  34513. })();
  34514. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  34515. /**
  34516. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  34517. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  34518. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  34519. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  34520. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  34521. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  34522. */
  34523. var DynamicFloatArray = (function () {
  34524. /**
  34525. * Construct an instance of the dynamic float array
  34526. * @param stride size of one element in float (i.e. not bytes!)
  34527. * @param initialElementCount the number of available entries at construction
  34528. */
  34529. function DynamicFloatArray(stride, initialElementCount) {
  34530. this._stride = stride;
  34531. this.buffer = new Float32Array(stride * initialElementCount);
  34532. this._lastUsed = 0;
  34533. this._firstFree = 0;
  34534. this._allEntries = new Array(initialElementCount);
  34535. this._freeEntries = new Array(initialElementCount);
  34536. for (var i = 0; i < initialElementCount; i++) {
  34537. var element = new DynamicFloatArrayElementInfo();
  34538. element.offset = i * stride;
  34539. this._allEntries[i] = element;
  34540. this._freeEntries[initialElementCount - i - 1] = element;
  34541. }
  34542. }
  34543. /**
  34544. * Allocate an element in the array.
  34545. * @return the element info instance that contains the offset into the main buffer of the element's location.
  34546. * Beware, this offset may change when you call pack()
  34547. */
  34548. DynamicFloatArray.prototype.allocElement = function () {
  34549. if (this._freeEntries.length === 0) {
  34550. this._growBuffer();
  34551. }
  34552. var el = this._freeEntries.pop();
  34553. this._lastUsed = Math.max(el.offset, this._lastUsed);
  34554. if (el.offset === this._firstFree) {
  34555. if (this._freeEntries.length > 0) {
  34556. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  34557. }
  34558. else {
  34559. this._firstFree += this._stride;
  34560. }
  34561. }
  34562. return el;
  34563. };
  34564. /**
  34565. * Free the element corresponding to the given element info
  34566. * @param elInfo the element that describe the allocated element
  34567. */
  34568. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  34569. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  34570. this._freeEntries.push(elInfo);
  34571. };
  34572. /**
  34573. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  34574. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  34575. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  34576. */
  34577. DynamicFloatArray.prototype.pack = function () {
  34578. // no free slot? no need to pack
  34579. if (this._freeEntries.length === 0) {
  34580. return this.buffer;
  34581. }
  34582. // If the buffer is already packed the last used will always be lower than the first free
  34583. if (this._lastUsed < this._firstFree) {
  34584. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  34585. return elementsBuffer_1;
  34586. }
  34587. var s = this._stride;
  34588. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  34589. var lastFree = new DynamicFloatArrayElementInfo();
  34590. lastFree.offset = this.totalElementCount * s;
  34591. this._freeEntries.push(lastFree);
  34592. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  34593. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  34594. var firstFreeSlotOffset = sortedFree[0].offset;
  34595. var freeZoneSize = 1;
  34596. var occupiedZoneSize = this.usedElementCount * s;
  34597. var prevOffset = sortedFree[0].offset;
  34598. for (var i = 1; i < sortedFree.length; i++) {
  34599. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  34600. if (firstFreeSlotOffset >= occupiedZoneSize) {
  34601. break;
  34602. }
  34603. var curFree = sortedFree[i];
  34604. var curOffset = curFree.offset;
  34605. // Compute the distance between this offset and the previous
  34606. var distance = curOffset - prevOffset;
  34607. // If the distance is the stride size, they are adjacent, it good, move to the next
  34608. if (distance === s) {
  34609. // Free zone is one element bigger
  34610. ++freeZoneSize;
  34611. // as we're about to iterate to the next, the cur becomes the previous...
  34612. prevOffset = curOffset;
  34613. continue;
  34614. }
  34615. // Distance is bigger, which means there's x element between the previous free and this one
  34616. var usedRange = (distance / s) - 1;
  34617. // Two cases the free zone is smaller than the data to move or bigger
  34618. // Copy what can fit in the free zone
  34619. var curMoveOffset = curOffset - s;
  34620. var copyCount = Math.min(freeZoneSize, usedRange);
  34621. for (var j = 0; j < copyCount; j++) {
  34622. var freeI = firstFreeSlotOffset / s;
  34623. var curI = curMoveOffset / s;
  34624. var moveEl = sortedAll[curI];
  34625. this._moveElement(moveEl, firstFreeSlotOffset);
  34626. var replacedEl = sortedAll[freeI];
  34627. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  34628. replacedEl.offset = curMoveOffset;
  34629. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  34630. sortedAll[freeI] = moveEl;
  34631. sortedAll[curI] = replacedEl;
  34632. curMoveOffset -= s;
  34633. firstFreeSlotOffset += s;
  34634. }
  34635. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  34636. if (freeZoneSize <= usedRange) {
  34637. firstFreeSlotOffset = curMoveOffset + s;
  34638. freeZoneSize = 1;
  34639. }
  34640. else {
  34641. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  34642. }
  34643. // as we're about to iterate to the next, the cur becomes the previous...
  34644. prevOffset = curOffset;
  34645. }
  34646. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  34647. this._lastUsed = firstFreeSlotOffset - s;
  34648. this._firstFree = firstFreeSlotOffset;
  34649. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  34650. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  34651. this._allEntries = sortedAll;
  34652. return elementsBuffer;
  34653. };
  34654. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  34655. for (var i = 0; i < this._stride; i++) {
  34656. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  34657. }
  34658. element.offset = destOffset;
  34659. };
  34660. DynamicFloatArray.prototype._growBuffer = function () {
  34661. // Allocate the new buffer with 50% more entries, copy the content of the current one
  34662. var newElCount = Math.floor(this.totalElementCount * 1.5);
  34663. var newBuffer = new Float32Array(newElCount * this._stride);
  34664. newBuffer.set(this.buffer);
  34665. var curCount = this.totalElementCount;
  34666. var addedCount = newElCount - this.totalElementCount;
  34667. for (var i = 0; i < addedCount; i++) {
  34668. var element = new DynamicFloatArrayElementInfo();
  34669. element.offset = (curCount + i) * this.stride;
  34670. this._allEntries.push(element);
  34671. this._freeEntries[addedCount - i - 1] = element;
  34672. }
  34673. this._firstFree = curCount * this.stride;
  34674. this.buffer = newBuffer;
  34675. };
  34676. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  34677. /**
  34678. * Get the total count of entries that can fit in the current buffer
  34679. * @returns the elements count
  34680. */
  34681. get: function () {
  34682. return this._allEntries.length;
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  34688. /**
  34689. * Get the count of free entries that can still be allocated without resizing the buffer
  34690. * @returns the free elements count
  34691. */
  34692. get: function () {
  34693. return this._freeEntries.length;
  34694. },
  34695. enumerable: true,
  34696. configurable: true
  34697. });
  34698. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  34699. /**
  34700. * Get the count of allocated elements
  34701. * @returns the allocated elements count
  34702. */
  34703. get: function () {
  34704. return this._allEntries.length - this._freeEntries.length;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  34710. /**
  34711. * Return the size of one element in float
  34712. * @returns the size in float
  34713. */
  34714. get: function () {
  34715. return this._stride;
  34716. },
  34717. enumerable: true,
  34718. configurable: true
  34719. });
  34720. return DynamicFloatArray;
  34721. })();
  34722. BABYLON.DynamicFloatArray = DynamicFloatArray;
  34723. })(BABYLON || (BABYLON = {}));
  34724. var BABYLON;
  34725. (function (BABYLON) {
  34726. /**
  34727. * This class given information about a given character.
  34728. */
  34729. var CharInfo = (function () {
  34730. function CharInfo() {
  34731. }
  34732. return CharInfo;
  34733. })();
  34734. BABYLON.CharInfo = CharInfo;
  34735. var FontTexture = (function (_super) {
  34736. __extends(FontTexture, _super);
  34737. /**
  34738. * Create a new instance of the FontTexture class
  34739. * @param name the name of the texture
  34740. * @param font the font to use, use the W3C CSS notation
  34741. * @param scene the scene that owns the texture
  34742. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  34743. * @param samplingMode the texture sampling mode
  34744. */
  34745. function FontTexture(name, font, scene, maxCharCount, samplingMode) {
  34746. if (maxCharCount === void 0) { maxCharCount = 200; }
  34747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34748. _super.call(this, null, scene, true, false, samplingMode);
  34749. this._charInfos = {};
  34750. this._curCharCount = 0;
  34751. this._lastUpdateCharCount = -1;
  34752. this._usedCounter = 1;
  34753. this.name = name;
  34754. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34755. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34756. // First canvas creation to determine the size of the texture to create
  34757. this._canvas = document.createElement("canvas");
  34758. this._context = this._canvas.getContext("2d");
  34759. this._context.font = font;
  34760. this._context.fillStyle = "white";
  34761. var res = this.getFontHeight(font);
  34762. this._lineHeight = res.height;
  34763. this._offset = res.offset - 1;
  34764. var maxCharWidth = this._context.measureText("W").width;
  34765. this._spaceWidth = this._context.measureText(" ").width;
  34766. // This is an approximate size, but should always be able to fit at least the maxCharCount
  34767. var totalEstSurface = this._lineHeight * maxCharWidth * maxCharCount;
  34768. var edge = Math.sqrt(totalEstSurface);
  34769. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  34770. // Create the texture that will store the font characters
  34771. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  34772. var textureSize = this.getSize();
  34773. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  34774. this._canvas = document.createElement("canvas");
  34775. this._canvas.width = textureSize.width;
  34776. this._canvas.height = textureSize.height;
  34777. this._context = this._canvas.getContext("2d");
  34778. this._context.textBaseline = "top";
  34779. this._context.font = font;
  34780. this._context.fillStyle = "white";
  34781. this._context.imageSmoothingEnabled = false;
  34782. this._currentFreePosition = BABYLON.Vector2.Zero();
  34783. // Add the basic ASCII based characters
  34784. for (var i = 0x20; i < 0x7F; i++) {
  34785. var c = String.fromCharCode(i);
  34786. this.getChar(c);
  34787. }
  34788. this.update();
  34789. }
  34790. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  34791. get: function () {
  34792. return this._spaceWidth;
  34793. },
  34794. enumerable: true,
  34795. configurable: true
  34796. });
  34797. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  34798. get: function () {
  34799. return this._lineHeight;
  34800. },
  34801. enumerable: true,
  34802. configurable: true
  34803. });
  34804. FontTexture.GetCachedFontTexture = function (scene, fontName) {
  34805. var s = scene;
  34806. if (!s.__fontTextureCache__) {
  34807. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  34808. }
  34809. var dic = s.__fontTextureCache__;
  34810. var lfn = fontName.toLocaleLowerCase();
  34811. var ft = dic.get(lfn);
  34812. if (ft) {
  34813. ++ft._usedCounter;
  34814. return ft;
  34815. }
  34816. ft = new FontTexture(null, lfn, scene);
  34817. dic.add(lfn, ft);
  34818. return ft;
  34819. };
  34820. FontTexture.ReleaseCachedFontTexture = function (scene, fontName) {
  34821. var s = scene;
  34822. var dic = s.__fontTextureCache__;
  34823. if (!dic) {
  34824. return;
  34825. }
  34826. var lfn = fontName.toLocaleLowerCase();
  34827. var font = dic.get(lfn);
  34828. if (--font._usedCounter === 0) {
  34829. dic.remove(lfn);
  34830. font.dispose();
  34831. }
  34832. };
  34833. /**
  34834. * Make sure the given char is present in the font map.
  34835. * @param char the character to get or add
  34836. * @return the CharInfo instance corresponding to the given character
  34837. */
  34838. FontTexture.prototype.getChar = function (char) {
  34839. if (char.length !== 1) {
  34840. return null;
  34841. }
  34842. var info = this._charInfos[char];
  34843. if (info) {
  34844. return info;
  34845. }
  34846. info = new CharInfo();
  34847. var measure = this._context.measureText(char);
  34848. var textureSize = this.getSize();
  34849. // we reached the end of the current line?
  34850. var xMargin = 2;
  34851. var yMargin = 2;
  34852. var width = measure.width;
  34853. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  34854. this._currentFreePosition.x = 0;
  34855. this._currentFreePosition.y += this._lineHeight + yMargin; // +2 for safety margin
  34856. // No more room?
  34857. if (this._currentFreePosition.y > textureSize.height) {
  34858. return this.getChar("!");
  34859. }
  34860. }
  34861. // Draw the character in the texture
  34862. this._context.fillText(char, this._currentFreePosition.x - 0.5, this._currentFreePosition.y - this._offset - 0.5);
  34863. // Fill the CharInfo object
  34864. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  34865. info.bottomRightUV = new BABYLON.Vector2(info.topLeftUV.x + (width / textureSize.width), info.topLeftUV.y + ((this._lineHeight + 1) / textureSize.height));
  34866. info.charWidth = width;
  34867. // Add the info structure
  34868. this._charInfos[char] = info;
  34869. this._curCharCount++;
  34870. // Set the next position
  34871. this._currentFreePosition.x += width + xMargin;
  34872. return info;
  34873. };
  34874. FontTexture.prototype.measureText = function (text, tabulationSize) {
  34875. if (tabulationSize === void 0) { tabulationSize = 4; }
  34876. var maxWidth = 0;
  34877. var curWidth = 0;
  34878. var lineCount = 1;
  34879. var charxpos = 0;
  34880. // Parse each char of the string
  34881. for (var _i = 0; _i < text.length; _i++) {
  34882. var char = text[_i];
  34883. // Next line feed?
  34884. if (char === "\n") {
  34885. maxWidth = Math.max(maxWidth, curWidth);
  34886. charxpos = 0;
  34887. curWidth = 0;
  34888. ++lineCount;
  34889. continue;
  34890. }
  34891. // Tabulation ?
  34892. if (char === "\t") {
  34893. var nextPos = charxpos + tabulationSize;
  34894. nextPos = nextPos - (nextPos % tabulationSize);
  34895. curWidth += (nextPos - charxpos) * this.spaceWidth;
  34896. charxpos = nextPos;
  34897. continue;
  34898. }
  34899. if (char < " ") {
  34900. continue;
  34901. }
  34902. curWidth += this.getChar(char).charWidth;
  34903. ++charxpos;
  34904. }
  34905. maxWidth = Math.max(maxWidth, curWidth);
  34906. return new BABYLON.Size(maxWidth, lineCount * this._lineHeight);
  34907. };
  34908. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  34909. FontTexture.prototype.getFontHeight = function (font) {
  34910. var fontDraw = document.createElement("canvas");
  34911. var ctx = fontDraw.getContext('2d');
  34912. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  34913. ctx.textBaseline = 'top';
  34914. ctx.fillStyle = 'white';
  34915. ctx.font = font;
  34916. ctx.fillText('jH|', 0, 0);
  34917. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  34918. var start = -1;
  34919. var end = -1;
  34920. for (var row = 0; row < fontDraw.height; row++) {
  34921. for (var column = 0; column < fontDraw.width; column++) {
  34922. var index = (row * fontDraw.width + column) * 4;
  34923. if (pixels[index] === 0) {
  34924. if (column === fontDraw.width - 1 && start !== -1) {
  34925. end = row;
  34926. row = fontDraw.height;
  34927. break;
  34928. }
  34929. continue;
  34930. }
  34931. else {
  34932. if (start === -1) {
  34933. start = row;
  34934. }
  34935. break;
  34936. }
  34937. }
  34938. }
  34939. return { height: end - start, offset: start - 1 };
  34940. };
  34941. Object.defineProperty(FontTexture.prototype, "canRescale", {
  34942. get: function () {
  34943. return false;
  34944. },
  34945. enumerable: true,
  34946. configurable: true
  34947. });
  34948. FontTexture.prototype.getContext = function () {
  34949. return this._context;
  34950. };
  34951. /**
  34952. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  34953. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  34954. */
  34955. FontTexture.prototype.update = function () {
  34956. // Update only if there's new char added since the previous update
  34957. if (this._lastUpdateCharCount < this._curCharCount) {
  34958. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  34959. this._lastUpdateCharCount = this._curCharCount;
  34960. }
  34961. };
  34962. // cloning should be prohibited, there's no point to duplicate this texture at all
  34963. FontTexture.prototype.clone = function () {
  34964. return null;
  34965. };
  34966. return FontTexture;
  34967. })(BABYLON.Texture);
  34968. BABYLON.FontTexture = FontTexture;
  34969. })(BABYLON || (BABYLON = {}));
  34970. var BABYLON;
  34971. (function (BABYLON) {
  34972. var MapTexture = (function (_super) {
  34973. __extends(MapTexture, _super);
  34974. function MapTexture(name, scene, size, samplingMode) {
  34975. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34976. _super.call(this, null, scene, true, false, samplingMode);
  34977. this.name = name;
  34978. this._size = size;
  34979. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34980. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34981. // Create the rectPackMap that will allocate portion of the texture
  34982. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  34983. // Create the texture that will store the content
  34984. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  34985. }
  34986. /**
  34987. * Allocate a rectangle of a given size in the texture map
  34988. * @param size the size of the rectangle to allocation
  34989. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  34990. */
  34991. MapTexture.prototype.allocateRect = function (size) {
  34992. return this._rectPackingMap.addRect(size);
  34993. };
  34994. /**
  34995. * Free a given rectangle from the texture map
  34996. * @param rectInfo the instance corresponding to the rect to free.
  34997. */
  34998. MapTexture.prototype.freeRect = function (rectInfo) {
  34999. if (rectInfo) {
  35000. rectInfo.freeContent();
  35001. }
  35002. };
  35003. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  35004. /**
  35005. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  35006. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  35007. * @returns {}
  35008. */
  35009. get: function () {
  35010. return this._rectPackingMap.freeSpace;
  35011. },
  35012. enumerable: true,
  35013. configurable: true
  35014. });
  35015. /**
  35016. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  35017. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  35018. * Don't forget to call unbindTexture when you're done rendering
  35019. * @param rect the zone to render to
  35020. * @param clear true to clear the portion's color/depth data
  35021. */
  35022. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  35023. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  35024. };
  35025. /**
  35026. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  35027. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  35028. * Don't forget to call unbindTexture when you're done rendering
  35029. * @param pos the position into the texture
  35030. * @param size the portion to fit the clip space to
  35031. * @param clear true to clear the portion's color/depth data
  35032. */
  35033. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  35034. var engine = this.getScene().getEngine();
  35035. engine.bindFramebuffer(this._texture);
  35036. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  35037. if (clear) {
  35038. var gl = engine._gl;
  35039. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  35040. // Save state
  35041. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  35042. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  35043. // Change state
  35044. gl.enable(gl.SCISSOR_TEST);
  35045. gl.scissor(pos.x, pos.y, size.width, size.height);
  35046. // Clear
  35047. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  35048. // Restore state
  35049. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  35050. if (curScissor === true) {
  35051. gl.enable(gl.SCISSOR_TEST);
  35052. }
  35053. else {
  35054. gl.disable(gl.SCISSOR_TEST);
  35055. }
  35056. }
  35057. };
  35058. /**
  35059. * Unbind the texture map from the rendering engine.
  35060. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  35061. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  35062. */
  35063. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  35064. // Dump ?
  35065. if (dumpForDebug) {
  35066. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  35067. }
  35068. var engine = this.getScene().getEngine();
  35069. if (this._replacedViewport) {
  35070. engine.setViewport(this._replacedViewport);
  35071. this._replacedViewport = null;
  35072. }
  35073. engine.unBindFramebuffer(this._texture);
  35074. };
  35075. Object.defineProperty(MapTexture.prototype, "canRescale", {
  35076. get: function () {
  35077. return false;
  35078. },
  35079. enumerable: true,
  35080. configurable: true
  35081. });
  35082. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  35083. // Anyway, there's not much point to use this method for this kind of texture I guess
  35084. MapTexture.prototype.clone = function () {
  35085. return null;
  35086. };
  35087. return MapTexture;
  35088. })(BABYLON.Texture);
  35089. BABYLON.MapTexture = MapTexture;
  35090. })(BABYLON || (BABYLON = {}));
  35091. var BABYLON;
  35092. (function (BABYLON) {
  35093. /**
  35094. * Stores 2D Bounding Information.
  35095. * This class handles a circle area and a bounding rectangle one.
  35096. */
  35097. var BoundingInfo2D = (function () {
  35098. function BoundingInfo2D() {
  35099. this.radius = 0;
  35100. this.center = BABYLON.Vector2.Zero();
  35101. this.extent = BABYLON.Vector2.Zero();
  35102. }
  35103. BoundingInfo2D.CreateFromSize = function (size, origin) {
  35104. var r = new BoundingInfo2D();
  35105. BoundingInfo2D.CreateFromSizeToRef(size, r, origin);
  35106. return r;
  35107. };
  35108. BoundingInfo2D.CreateFromRadius = function (radius, origin) {
  35109. var r = new BoundingInfo2D();
  35110. BoundingInfo2D.CreateFromRadiusToRef(radius, r, origin);
  35111. return r;
  35112. };
  35113. BoundingInfo2D.CreateFromPoints = function (points, origin) {
  35114. var r = new BoundingInfo2D();
  35115. BoundingInfo2D.CreateFromPointsToRef(points, r, origin);
  35116. return r;
  35117. };
  35118. BoundingInfo2D.CreateFromSizeToRef = function (size, b, origin) {
  35119. b.center = new BABYLON.Vector2(size.width / 2, size.height / 2);
  35120. b.extent = b.center.clone();
  35121. if (origin) {
  35122. b.center.x -= size.width * origin.x;
  35123. b.center.y -= size.height * origin.y;
  35124. }
  35125. b.radius = b.extent.length();
  35126. };
  35127. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b, origin) {
  35128. b.center = BABYLON.Vector2.Zero();
  35129. if (origin) {
  35130. b.center.x -= radius * origin.x;
  35131. b.center.y -= radius * origin.y;
  35132. }
  35133. b.extent = new BABYLON.Vector2(radius, radius);
  35134. b.radius = radius;
  35135. };
  35136. BoundingInfo2D.CreateFromPointsToRef = function (points, b, origin) {
  35137. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  35138. for (var _i = 0; _i < points.length; _i++) {
  35139. var p = points[_i];
  35140. xmin = Math.min(p.x, xmin);
  35141. xmax = Math.max(p.x, xmax);
  35142. ymin = Math.min(p.y, ymin);
  35143. ymax = Math.max(p.y, ymax);
  35144. }
  35145. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b, origin);
  35146. };
  35147. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b, origin) {
  35148. var w = xmax - xmin;
  35149. var h = ymax - ymin;
  35150. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  35151. if (origin) {
  35152. b.center.x -= w * origin.x;
  35153. b.center.y -= h * origin.y;
  35154. }
  35155. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  35156. b.radius = b.extent.length();
  35157. };
  35158. /**
  35159. * Duplicate this instance and return a new one
  35160. * @return the duplicated instance
  35161. */
  35162. BoundingInfo2D.prototype.clone = function () {
  35163. var r = new BoundingInfo2D();
  35164. r.center = this.center.clone();
  35165. r.radius = this.radius;
  35166. r.extent = this.extent.clone();
  35167. return r;
  35168. };
  35169. BoundingInfo2D.prototype.max = function () {
  35170. var r = BABYLON.Vector2.Zero();
  35171. this.maxToRef(r);
  35172. return r;
  35173. };
  35174. BoundingInfo2D.prototype.maxToRef = function (result) {
  35175. result.x = this.center.x + this.extent.x;
  35176. result.y = this.center.y + this.extent.y;
  35177. };
  35178. /**
  35179. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  35180. * @param matrix the transformation matrix to apply
  35181. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  35182. */
  35183. BoundingInfo2D.prototype.transform = function (matrix) {
  35184. var r = new BoundingInfo2D();
  35185. this.transformToRef(matrix, r);
  35186. return r;
  35187. };
  35188. /**
  35189. * Compute the union of this BoundingInfo2D with a given one, return a new BoundingInfo2D as a result
  35190. * @param other the second BoundingInfo2D to compute the union with this one
  35191. * @return a new instance containing the result of the union
  35192. */
  35193. BoundingInfo2D.prototype.union = function (other) {
  35194. var r = new BoundingInfo2D();
  35195. this.unionToRef(other, r);
  35196. return r;
  35197. };
  35198. /**
  35199. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  35200. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  35201. * @param matrix The matrix to use to compute the transformation
  35202. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  35203. */
  35204. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  35205. // Construct a bounding box based on the extent values
  35206. var p = new Array(4);
  35207. p[0] = new BABYLON.Vector2(this.center.x + this.extent.x, this.center.y + this.extent.y);
  35208. p[1] = new BABYLON.Vector2(this.center.x + this.extent.x, this.center.y - this.extent.y);
  35209. p[2] = new BABYLON.Vector2(this.center.x - this.extent.x, this.center.y - this.extent.y);
  35210. p[3] = new BABYLON.Vector2(this.center.x - this.extent.x, this.center.y + this.extent.y);
  35211. // Transform the four points of the bounding box with the matrix
  35212. for (var i = 0; i < 4; i++) {
  35213. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  35214. }
  35215. BoundingInfo2D.CreateFromPointsToRef(p, result);
  35216. };
  35217. /**
  35218. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  35219. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  35220. * @param other the second object used to compute the union
  35221. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  35222. */
  35223. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  35224. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  35225. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  35226. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  35227. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  35228. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  35229. };
  35230. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  35231. // is it inside the radius?
  35232. var pickLocal = pickPosition.subtract(this.center);
  35233. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  35234. // is it inside the rectangle?
  35235. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  35236. }
  35237. return false;
  35238. };
  35239. return BoundingInfo2D;
  35240. })();
  35241. BABYLON.BoundingInfo2D = BoundingInfo2D;
  35242. })(BABYLON || (BABYLON = {}));
  35243. var BABYLON;
  35244. (function (BABYLON) {
  35245. /**
  35246. * Base class implementing the ILocable interface.
  35247. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  35248. */
  35249. var LockableBase = (function () {
  35250. function LockableBase() {
  35251. }
  35252. LockableBase.prototype.isLocked = function () {
  35253. return this._isLocked;
  35254. };
  35255. LockableBase.prototype.lock = function () {
  35256. if (this._isLocked) {
  35257. return true;
  35258. }
  35259. this.onLock();
  35260. this._isLocked = true;
  35261. return false;
  35262. };
  35263. /**
  35264. * Protected handler that will be called when the instance is about to be locked.
  35265. */
  35266. LockableBase.prototype.onLock = function () {
  35267. };
  35268. return LockableBase;
  35269. })();
  35270. BABYLON.LockableBase = LockableBase;
  35271. /**
  35272. * This class implements a Brush that will be drawn with a uniform solid color (i.e. the same color everywhere in the content where the brush is assigned to).
  35273. */
  35274. var SolidColorBrush2D = (function (_super) {
  35275. __extends(SolidColorBrush2D, _super);
  35276. function SolidColorBrush2D(color, lock) {
  35277. if (lock === void 0) { lock = false; }
  35278. _super.call(this);
  35279. this._color = color;
  35280. if (lock) {
  35281. {
  35282. this.lock();
  35283. }
  35284. }
  35285. }
  35286. SolidColorBrush2D.prototype.isTransparent = function () {
  35287. return this._color && this._color.a < 1.0;
  35288. };
  35289. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  35290. /**
  35291. * The color used by this instance to render
  35292. * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
  35293. */
  35294. get: function () {
  35295. return this._color;
  35296. },
  35297. set: function (value) {
  35298. if (this.isLocked()) {
  35299. return;
  35300. }
  35301. this._color = value;
  35302. },
  35303. enumerable: true,
  35304. configurable: true
  35305. });
  35306. /**
  35307. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  35308. */
  35309. SolidColorBrush2D.prototype.toString = function () {
  35310. return this._color.toHexString();
  35311. };
  35312. SolidColorBrush2D = __decorate([
  35313. BABYLON.className("SolidColorBrush2D")
  35314. ], SolidColorBrush2D);
  35315. return SolidColorBrush2D;
  35316. })(LockableBase);
  35317. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  35318. var GradientColorBrush2D = (function (_super) {
  35319. __extends(GradientColorBrush2D, _super);
  35320. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  35321. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  35322. if (rotation === void 0) { rotation = 0; }
  35323. if (scale === void 0) { scale = 1; }
  35324. if (lock === void 0) { lock = false; }
  35325. _super.call(this);
  35326. this._color1 = color1;
  35327. this._color2 = color2;
  35328. this._translation = translation;
  35329. this._rotation = rotation;
  35330. this._scale = scale;
  35331. if (lock) {
  35332. this.lock();
  35333. }
  35334. }
  35335. GradientColorBrush2D.prototype.isTransparent = function () {
  35336. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  35337. };
  35338. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  35339. get: function () {
  35340. return this._color1;
  35341. },
  35342. set: function (value) {
  35343. if (this.isLocked()) {
  35344. return;
  35345. }
  35346. this._color1 = value;
  35347. },
  35348. enumerable: true,
  35349. configurable: true
  35350. });
  35351. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  35352. get: function () {
  35353. return this._color2;
  35354. },
  35355. set: function (value) {
  35356. if (this.isLocked()) {
  35357. return;
  35358. }
  35359. this._color2 = value;
  35360. },
  35361. enumerable: true,
  35362. configurable: true
  35363. });
  35364. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  35365. get: function () {
  35366. return this._translation;
  35367. },
  35368. set: function (value) {
  35369. if (this.isLocked()) {
  35370. return;
  35371. }
  35372. this._translation = value;
  35373. },
  35374. enumerable: true,
  35375. configurable: true
  35376. });
  35377. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  35378. get: function () {
  35379. return this._rotation;
  35380. },
  35381. set: function (value) {
  35382. if (this.isLocked()) {
  35383. return;
  35384. }
  35385. this._rotation = value;
  35386. },
  35387. enumerable: true,
  35388. configurable: true
  35389. });
  35390. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  35391. get: function () {
  35392. return this._scale;
  35393. },
  35394. set: function (value) {
  35395. if (this.isLocked()) {
  35396. return;
  35397. }
  35398. this._scale = value;
  35399. },
  35400. enumerable: true,
  35401. configurable: true
  35402. });
  35403. GradientColorBrush2D.prototype.toString = function () {
  35404. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  35405. };
  35406. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  35407. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  35408. };
  35409. GradientColorBrush2D = __decorate([
  35410. BABYLON.className("GradientColorBrush2D")
  35411. ], GradientColorBrush2D);
  35412. return GradientColorBrush2D;
  35413. })(LockableBase);
  35414. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  35415. })(BABYLON || (BABYLON = {}));
  35416. var BABYLON;
  35417. (function (BABYLON) {
  35418. var Prim2DClassInfo = (function () {
  35419. function Prim2DClassInfo() {
  35420. }
  35421. return Prim2DClassInfo;
  35422. })();
  35423. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  35424. var Prim2DPropInfo = (function () {
  35425. function Prim2DPropInfo() {
  35426. }
  35427. Prim2DPropInfo.PROPKIND_MODEL = 1;
  35428. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  35429. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  35430. return Prim2DPropInfo;
  35431. })();
  35432. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  35433. var PropertyChangedInfo = (function () {
  35434. function PropertyChangedInfo() {
  35435. }
  35436. return PropertyChangedInfo;
  35437. })();
  35438. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  35439. var ClassTreeInfo = (function () {
  35440. function ClassTreeInfo(baseClass, type, classContentFactory) {
  35441. this._baseClass = baseClass;
  35442. this._type = type;
  35443. this._subClasses = new Array();
  35444. this._levelContent = new BABYLON.StringDictionary();
  35445. this._classContentFactory = classContentFactory;
  35446. }
  35447. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  35448. get: function () {
  35449. if (!this._classContent) {
  35450. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  35451. }
  35452. return this._classContent;
  35453. },
  35454. enumerable: true,
  35455. configurable: true
  35456. });
  35457. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  35458. get: function () {
  35459. return this._type;
  35460. },
  35461. enumerable: true,
  35462. configurable: true
  35463. });
  35464. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  35465. get: function () {
  35466. return this._levelContent;
  35467. },
  35468. enumerable: true,
  35469. configurable: true
  35470. });
  35471. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  35472. get: function () {
  35473. if (!this._fullContent) {
  35474. var dic = new BABYLON.StringDictionary();
  35475. var curLevel = this;
  35476. while (curLevel) {
  35477. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  35478. curLevel = curLevel._baseClass;
  35479. }
  35480. this._fullContent = dic;
  35481. }
  35482. return this._fullContent;
  35483. },
  35484. enumerable: true,
  35485. configurable: true
  35486. });
  35487. ClassTreeInfo.prototype.getLevelOf = function (type) {
  35488. // Are we already there?
  35489. if (type === this._type) {
  35490. return this;
  35491. }
  35492. var baseProto = Object.getPrototypeOf(type);
  35493. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  35494. if (!curProtoContent) {
  35495. this.getLevelOf(baseProto);
  35496. }
  35497. return this.getOrAddType(baseProto, type);
  35498. };
  35499. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  35500. // Are we at the level corresponding to the baseType?
  35501. // If so, get or add the level we're looking for
  35502. if (baseType === this._type) {
  35503. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  35504. var subType = _a[_i];
  35505. if (subType.type === type) {
  35506. return subType.node;
  35507. }
  35508. }
  35509. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  35510. var info = { type: type, node: node };
  35511. this._subClasses.push(info);
  35512. return info.node;
  35513. }
  35514. // Recurse down to keep looking for the node corresponding to the baseTypeName
  35515. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  35516. var subType = _c[_b];
  35517. var info = subType.node.getOrAddType(baseType, type);
  35518. if (info) {
  35519. return info;
  35520. }
  35521. }
  35522. return null;
  35523. };
  35524. ClassTreeInfo.get = function (type) {
  35525. var dic = type["__classTreeInfo"];
  35526. if (!dic) {
  35527. return null;
  35528. }
  35529. return dic.getLevelOf(type);
  35530. };
  35531. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  35532. var dic = type["__classTreeInfo"];
  35533. if (!dic) {
  35534. dic = new ClassTreeInfo(null, type, classContentFactory);
  35535. type["__classTreeInfo"] = dic;
  35536. }
  35537. return dic;
  35538. };
  35539. return ClassTreeInfo;
  35540. })();
  35541. BABYLON.ClassTreeInfo = ClassTreeInfo;
  35542. var SmartPropertyPrim = (function () {
  35543. function SmartPropertyPrim() {
  35544. }
  35545. SmartPropertyPrim.prototype.setupSmartPropertyPrim = function () {
  35546. this._modelKey = null;
  35547. this._modelDirty = false;
  35548. this._levelBoundingInfoDirty = false;
  35549. this._instanceDirtyFlags = 0;
  35550. this._isDisposed = false;
  35551. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  35552. };
  35553. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  35554. get: function () {
  35555. return this._isDisposed;
  35556. },
  35557. enumerable: true,
  35558. configurable: true
  35559. });
  35560. SmartPropertyPrim.prototype.dispose = function () {
  35561. if (this.isDisposed) {
  35562. return false;
  35563. }
  35564. this._isDisposed = true;
  35565. return true;
  35566. };
  35567. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  35568. get: function () {
  35569. var _this = this;
  35570. // No need to compute it?
  35571. if (!this._modelDirty && this._modelKey) {
  35572. return this._modelKey;
  35573. }
  35574. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  35575. var propDic = this.propDic;
  35576. propDic.forEach(function (k, v) {
  35577. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  35578. var propVal = _this[v.name];
  35579. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  35580. }
  35581. });
  35582. this._modelDirty = false;
  35583. this._modelKey = modelKey;
  35584. return modelKey;
  35585. },
  35586. enumerable: true,
  35587. configurable: true
  35588. });
  35589. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  35590. get: function () {
  35591. return (this._instanceDirtyFlags !== 0) || this._modelDirty;
  35592. },
  35593. enumerable: true,
  35594. configurable: true
  35595. });
  35596. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  35597. get: function () {
  35598. if (!this._propInfo) {
  35599. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  35600. if (!cti) {
  35601. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  35602. }
  35603. this._propInfo = cti.fullContent;
  35604. }
  35605. return this._propInfo;
  35606. },
  35607. enumerable: true,
  35608. configurable: true
  35609. });
  35610. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind) {
  35611. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  35612. var node = dic.getLevelOf(target);
  35613. var propInfo = node.levelContent.get(propId.toString());
  35614. if (propInfo) {
  35615. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  35616. }
  35617. // Create, setup and add the PropInfo object to our prop dictionary
  35618. propInfo = new Prim2DPropInfo();
  35619. propInfo.id = propId;
  35620. propInfo.flagId = Math.pow(2, propId);
  35621. propInfo.kind = kind;
  35622. propInfo.name = propName;
  35623. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  35624. propInfo.typeLevelCompare = typeLevelCompare;
  35625. node.levelContent.add(propId.toString(), propInfo);
  35626. return propInfo;
  35627. };
  35628. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  35629. // Nothing to nothing: nothing to do!
  35630. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  35631. return true;
  35632. }
  35633. // Check value unchanged
  35634. if ((curValue != null) && (newValue != null)) {
  35635. if (typeof (curValue.equals) == "function") {
  35636. if (curValue.equals(newValue)) {
  35637. return true;
  35638. }
  35639. }
  35640. else {
  35641. if (curValue === newValue) {
  35642. return true;
  35643. }
  35644. }
  35645. }
  35646. return false;
  35647. };
  35648. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  35649. // Trigger property changed
  35650. var info = SmartPropertyPrim.propChangedInfo;
  35651. info.oldValue = curValue;
  35652. info.newValue = newValue;
  35653. info.propertyName = propName;
  35654. var propMask = propInfo.flagId;
  35655. this.propertyChanged.notifyObservers(info, propMask);
  35656. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  35657. if (this instanceof BABYLON.Group2D) {
  35658. this.handleGroupChanged(propInfo);
  35659. }
  35660. // Check if we need to dirty only if the type change and make the test
  35661. var skipDirty = false;
  35662. if (typeLevelCompare && curValue != null && newValue != null) {
  35663. var cvProto = curValue.__proto__;
  35664. var nvProto = newValue.__proto__;
  35665. skipDirty = (cvProto === nvProto);
  35666. }
  35667. // Set the dirty flags
  35668. if (!skipDirty) {
  35669. if (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  35670. if (!this.isDirty) {
  35671. this.onPrimBecomesDirty();
  35672. }
  35673. this._modelDirty = true;
  35674. }
  35675. else if ((propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  35676. if (!this.isDirty) {
  35677. this.onPrimBecomesDirty();
  35678. }
  35679. this._instanceDirtyFlags |= propMask;
  35680. }
  35681. }
  35682. };
  35683. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  35684. };
  35685. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  35686. return (this._instanceDirtyFlags & flags) !== 0;
  35687. };
  35688. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  35689. this._instanceDirtyFlags &= ~flags;
  35690. return this._instanceDirtyFlags;
  35691. };
  35692. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  35693. get: function () {
  35694. if (this._levelBoundingInfoDirty) {
  35695. this.updateLevelBoundingInfo();
  35696. this._levelBoundingInfoDirty = false;
  35697. }
  35698. return this._levelBoundingInfo;
  35699. },
  35700. enumerable: true,
  35701. configurable: true
  35702. });
  35703. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  35704. };
  35705. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  35706. };
  35707. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, kind) {
  35708. return function (target, propName, descriptor) {
  35709. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind);
  35710. if (piStore) {
  35711. piStore(propInfo);
  35712. }
  35713. var getter = descriptor.get, setter = descriptor.set;
  35714. // Overload the property setter implementation to add our own logic
  35715. descriptor.set = function (val) {
  35716. // check for disposed first, do nothing
  35717. if (this.isDisposed) {
  35718. return;
  35719. }
  35720. var curVal = getter.call(this);
  35721. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  35722. return;
  35723. }
  35724. // Cast the object we're working one
  35725. var prim = this;
  35726. // Change the value
  35727. setter.call(this, val);
  35728. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  35729. if (propInfo.dirtyBoundingInfo) {
  35730. prim._levelBoundingInfoDirty = true;
  35731. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  35732. if (prim instanceof BABYLON.Prim2DBase) {
  35733. var curprim = prim.parent;
  35734. while (curprim) {
  35735. curprim._boundingInfoDirty = true;
  35736. if (curprim instanceof BABYLON.Group2D) {
  35737. if (curprim.isRenderableGroup) {
  35738. break;
  35739. }
  35740. }
  35741. curprim = curprim.parent;
  35742. }
  35743. }
  35744. }
  35745. // Notify change, dirty flags update
  35746. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  35747. };
  35748. };
  35749. };
  35750. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  35751. SmartPropertyPrim = __decorate([
  35752. BABYLON.className("SmartPropertyPrim")
  35753. ], SmartPropertyPrim);
  35754. return SmartPropertyPrim;
  35755. })();
  35756. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  35757. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  35758. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  35759. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  35760. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_MODEL);
  35761. }
  35762. BABYLON.modelLevelProperty = modelLevelProperty;
  35763. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  35764. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  35765. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  35766. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_INSTANCE);
  35767. }
  35768. BABYLON.instanceLevelProperty = instanceLevelProperty;
  35769. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  35770. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  35771. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  35772. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_DYNAMIC);
  35773. }
  35774. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  35775. })(BABYLON || (BABYLON = {}));
  35776. var BABYLON;
  35777. (function (BABYLON) {
  35778. var Render2DContext = (function () {
  35779. function Render2DContext() {
  35780. }
  35781. return Render2DContext;
  35782. })();
  35783. BABYLON.Render2DContext = Render2DContext;
  35784. /**
  35785. * This class store information for the pointerEventObservable Observable.
  35786. * The Observable is divided into many sub events (using the Mask feature of the Observable pattern): PointerOver, PointerEnter, PointerDown, PointerMouseWheel, PointerMove, PointerUp, PointerDown, PointerLeave, PointerGotCapture and PointerLostCapture.
  35787. */
  35788. var PrimitivePointerInfo = (function () {
  35789. function PrimitivePointerInfo() {
  35790. this.primitivePointerPos = BABYLON.Vector2.Zero();
  35791. this.tilt = BABYLON.Vector2.Zero();
  35792. this.cancelBubble = false;
  35793. }
  35794. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  35795. // The behavior is based on the HTML specifications of the Pointer Events (https://www.w3.org/TR/pointerevents/#list-of-pointer-events). This is not 100% compliant and not meant to be, but still, it's based on these specs for most use cases to be programmed the same way (as closest as possible) as it would have been in HTML.
  35796. /**
  35797. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  35798. * Bubbles: yes
  35799. */
  35800. get: function () {
  35801. return PrimitivePointerInfo._pointerOver;
  35802. },
  35803. enumerable: true,
  35804. configurable: true
  35805. });
  35806. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  35807. /**
  35808. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  35809. * Bubbles: no
  35810. */
  35811. get: function () {
  35812. return PrimitivePointerInfo._pointerEnter;
  35813. },
  35814. enumerable: true,
  35815. configurable: true
  35816. });
  35817. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  35818. /**
  35819. * This event type is raised when a pointer enters the active button state (non-zero value in the buttons property). For mouse it's when the device transitions from no buttons depressed to at least one button depressed. For touch/pen this is when a physical contact is made.
  35820. * Bubbles: yes
  35821. */
  35822. get: function () {
  35823. return PrimitivePointerInfo._pointerDown;
  35824. },
  35825. enumerable: true,
  35826. configurable: true
  35827. });
  35828. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  35829. /**
  35830. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  35831. * Bubbles: yes
  35832. */
  35833. get: function () {
  35834. return PrimitivePointerInfo._pointerMouseWheel;
  35835. },
  35836. enumerable: true,
  35837. configurable: true
  35838. });
  35839. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  35840. /**
  35841. * This event type is raised when a pointer change coordinates or when a pointer changes button state, pressure, tilt, or contact geometry and the circumstances produce no other pointers events.
  35842. * Bubbles: yes
  35843. */
  35844. get: function () {
  35845. return PrimitivePointerInfo._pointerMove;
  35846. },
  35847. enumerable: true,
  35848. configurable: true
  35849. });
  35850. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  35851. /**
  35852. * This event type is raised when the pointer leaves the active buttons states (zero value in the buttons property). For mouse, this is when the device transitions from at least one button depressed to no buttons depressed. For touch/pen, this is when physical contact is removed.
  35853. * Bubbles: yes
  35854. */
  35855. get: function () {
  35856. return PrimitivePointerInfo._pointerUp;
  35857. },
  35858. enumerable: true,
  35859. configurable: true
  35860. });
  35861. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  35862. /**
  35863. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  35864. * Bubbles: yes
  35865. */
  35866. get: function () {
  35867. return PrimitivePointerInfo._pointerOut;
  35868. },
  35869. enumerable: true,
  35870. configurable: true
  35871. });
  35872. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  35873. /**
  35874. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  35875. * Bubbles: no
  35876. */
  35877. get: function () {
  35878. return PrimitivePointerInfo._pointerLeave;
  35879. },
  35880. enumerable: true,
  35881. configurable: true
  35882. });
  35883. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  35884. /**
  35885. * This event type is raised when a primitive receives the pointer capture. This event is fired at the element that is receiving pointer capture. Subsequent events for that pointer will be fired at this element.
  35886. * Bubbles: yes
  35887. */
  35888. get: function () {
  35889. return PrimitivePointerInfo._pointerGotCapture;
  35890. },
  35891. enumerable: true,
  35892. configurable: true
  35893. });
  35894. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  35895. /**
  35896. * This event type is raised after pointer capture is released for a pointer.
  35897. * Bubbles: yes
  35898. */
  35899. get: function () {
  35900. return PrimitivePointerInfo._pointerLostCapture;
  35901. },
  35902. enumerable: true,
  35903. configurable: true
  35904. });
  35905. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  35906. get: function () {
  35907. return PrimitivePointerInfo._mouseWheelPrecision;
  35908. },
  35909. enumerable: true,
  35910. configurable: true
  35911. });
  35912. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  35913. this.relatedTarget = prim;
  35914. this.relatedTargetPointerPos = primPointerPos;
  35915. };
  35916. PrimitivePointerInfo.getEventTypeName = function (mask) {
  35917. switch (mask) {
  35918. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  35919. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  35920. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  35921. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  35922. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  35923. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  35924. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  35925. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  35926. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  35927. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  35928. }
  35929. };
  35930. PrimitivePointerInfo._pointerOver = 0x0001;
  35931. PrimitivePointerInfo._pointerEnter = 0x0002;
  35932. PrimitivePointerInfo._pointerDown = 0x0004;
  35933. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  35934. PrimitivePointerInfo._pointerMove = 0x0010;
  35935. PrimitivePointerInfo._pointerUp = 0x0020;
  35936. PrimitivePointerInfo._pointerOut = 0x0040;
  35937. PrimitivePointerInfo._pointerLeave = 0x0080;
  35938. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  35939. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  35940. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  35941. return PrimitivePointerInfo;
  35942. })();
  35943. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  35944. /**
  35945. * Stores information about a Primitive that was intersected
  35946. */
  35947. var PrimitiveIntersectedInfo = (function () {
  35948. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  35949. this.prim = prim;
  35950. this.intersectionLocation = intersectionLocation;
  35951. }
  35952. return PrimitiveIntersectedInfo;
  35953. })();
  35954. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  35955. /**
  35956. * Main class used for the Primitive Intersection API
  35957. */
  35958. var IntersectInfo2D = (function () {
  35959. function IntersectInfo2D() {
  35960. this.findFirstOnly = false;
  35961. this.intersectHidden = false;
  35962. this.pickPosition = BABYLON.Vector2.Zero();
  35963. }
  35964. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  35965. /**
  35966. * true if at least one primitive intersected during the test
  35967. */
  35968. get: function () {
  35969. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  35970. },
  35971. enumerable: true,
  35972. configurable: true
  35973. });
  35974. // Internals, don't use
  35975. IntersectInfo2D.prototype._exit = function (firstLevel) {
  35976. if (firstLevel) {
  35977. this._globalPickPosition = null;
  35978. }
  35979. };
  35980. return IntersectInfo2D;
  35981. })();
  35982. BABYLON.IntersectInfo2D = IntersectInfo2D;
  35983. var Prim2DBase = (function (_super) {
  35984. __extends(Prim2DBase, _super);
  35985. function Prim2DBase() {
  35986. _super.apply(this, arguments);
  35987. }
  35988. Prim2DBase.prototype.setupPrim2DBase = function (owner, parent, id, position, isVisible) {
  35989. if (isVisible === void 0) { isVisible = true; }
  35990. if (!(this instanceof BABYLON.Group2D) && !(this instanceof BABYLON.Sprite2D && id !== null && id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  35991. throw new Error("Can't create a primitive with the canvas as direct parent when the caching strategy is TOPLEVELGROUPS. You need to create a Group below the canvas and use it as the parent for the primitive");
  35992. }
  35993. this.setupSmartPropertyPrim();
  35994. this._pointerEventObservable = new BABYLON.Observable();
  35995. this._isPickable = true;
  35996. this._siblingDepthOffset = this._hierarchyDepthOffset = 0;
  35997. this._boundingInfoDirty = true;
  35998. this._boundingInfo = new BABYLON.BoundingInfo2D();
  35999. this._owner = owner;
  36000. this._parent = parent;
  36001. if (parent != null) {
  36002. this._hierarchyDepth = parent._hierarchyDepth + 1;
  36003. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  36004. parent.addChild(this);
  36005. }
  36006. else {
  36007. this._hierarchyDepth = 0;
  36008. this._renderGroup = null;
  36009. }
  36010. this._id = id;
  36011. this.propertyChanged = new BABYLON.Observable();
  36012. this._children = new Array();
  36013. this._globalTransformProcessStep = 0;
  36014. this._globalTransformStep = 0;
  36015. if (this instanceof BABYLON.Group2D) {
  36016. var group = this;
  36017. group.detectGroupStates();
  36018. }
  36019. this.position = position;
  36020. this.rotation = 0;
  36021. this.scale = 1;
  36022. this.levelVisible = isVisible;
  36023. this.origin = new BABYLON.Vector2(0.5, 0.5);
  36024. };
  36025. /**
  36026. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  36027. * @param predicate the predicate to test on each parent
  36028. * @return the first primitive where the predicate was successful
  36029. */
  36030. Prim2DBase.prototype.traverseUp = function (predicate) {
  36031. var p = this;
  36032. while (p != null) {
  36033. if (predicate(p)) {
  36034. return p;
  36035. }
  36036. p = p._parent;
  36037. }
  36038. return null;
  36039. };
  36040. Object.defineProperty(Prim2DBase.prototype, "owner", {
  36041. /**
  36042. * Retrieve the owner Canvas2D
  36043. */
  36044. get: function () {
  36045. return this._owner;
  36046. },
  36047. enumerable: true,
  36048. configurable: true
  36049. });
  36050. Object.defineProperty(Prim2DBase.prototype, "parent", {
  36051. /**
  36052. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  36053. */
  36054. get: function () {
  36055. return this._parent;
  36056. },
  36057. enumerable: true,
  36058. configurable: true
  36059. });
  36060. Object.defineProperty(Prim2DBase.prototype, "children", {
  36061. /**
  36062. * The array of direct children primitives
  36063. */
  36064. get: function () {
  36065. return this._children;
  36066. },
  36067. enumerable: true,
  36068. configurable: true
  36069. });
  36070. Object.defineProperty(Prim2DBase.prototype, "id", {
  36071. /**
  36072. * The identifier of this primitive, may not be unique, it's for information purpose only
  36073. */
  36074. get: function () {
  36075. return this._id;
  36076. },
  36077. enumerable: true,
  36078. configurable: true
  36079. });
  36080. Object.defineProperty(Prim2DBase.prototype, "position", {
  36081. get: function () {
  36082. return this._position;
  36083. },
  36084. set: function (value) {
  36085. this._position = value;
  36086. },
  36087. enumerable: true,
  36088. configurable: true
  36089. });
  36090. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  36091. get: function () {
  36092. return this._rotation;
  36093. },
  36094. set: function (value) {
  36095. this._rotation = value;
  36096. },
  36097. enumerable: true,
  36098. configurable: true
  36099. });
  36100. Object.defineProperty(Prim2DBase.prototype, "scale", {
  36101. get: function () {
  36102. return this._scale;
  36103. },
  36104. set: function (value) {
  36105. this._scale = value;
  36106. },
  36107. enumerable: true,
  36108. configurable: true
  36109. });
  36110. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  36111. /**
  36112. * this method must be implemented by the primitive type to return its size
  36113. * @returns The size of the primitive
  36114. */
  36115. get: function () {
  36116. return undefined;
  36117. },
  36118. enumerable: true,
  36119. configurable: true
  36120. });
  36121. Object.defineProperty(Prim2DBase.prototype, "origin", {
  36122. /**
  36123. * The origin defines the normalized coordinate of the center of the primitive, from the top/left corner.
  36124. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  36125. * For instance:
  36126. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  36127. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  36128. * 0,1 means the center is top/left
  36129. * @returns The normalized center.
  36130. */
  36131. get: function () {
  36132. return this._origin;
  36133. },
  36134. set: function (value) {
  36135. this._origin = value;
  36136. },
  36137. enumerable: true,
  36138. configurable: true
  36139. });
  36140. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  36141. get: function () {
  36142. return this._levelVisible;
  36143. },
  36144. set: function (value) {
  36145. this._levelVisible = value;
  36146. },
  36147. enumerable: true,
  36148. configurable: true
  36149. });
  36150. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  36151. get: function () {
  36152. return this._isVisible;
  36153. },
  36154. set: function (value) {
  36155. this._isVisible = value;
  36156. },
  36157. enumerable: true,
  36158. configurable: true
  36159. });
  36160. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  36161. get: function () {
  36162. return this._zOrder;
  36163. },
  36164. set: function (value) {
  36165. this._zOrder = value;
  36166. },
  36167. enumerable: true,
  36168. configurable: true
  36169. });
  36170. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  36171. /**
  36172. * Define if the Primitive can be subject to intersection test or not (default is true)
  36173. */
  36174. get: function () {
  36175. return this._isPickable;
  36176. },
  36177. set: function (value) {
  36178. this._isPickable = value;
  36179. },
  36180. enumerable: true,
  36181. configurable: true
  36182. });
  36183. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  36184. /**
  36185. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  36186. * @returns {}
  36187. */
  36188. get: function () {
  36189. return this._hierarchyDepth;
  36190. },
  36191. enumerable: true,
  36192. configurable: true
  36193. });
  36194. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  36195. /**
  36196. * Retrieve the Group that is responsible to render this primitive
  36197. * @returns {}
  36198. */
  36199. get: function () {
  36200. return this._renderGroup;
  36201. },
  36202. enumerable: true,
  36203. configurable: true
  36204. });
  36205. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  36206. /**
  36207. * Get the global transformation matrix of the primitive
  36208. */
  36209. get: function () {
  36210. return this._globalTransform;
  36211. },
  36212. enumerable: true,
  36213. configurable: true
  36214. });
  36215. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  36216. /**
  36217. * Get invert of the global transformation matrix of the primitive
  36218. * @returns {}
  36219. */
  36220. get: function () {
  36221. return this._invGlobalTransform;
  36222. },
  36223. enumerable: true,
  36224. configurable: true
  36225. });
  36226. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  36227. /**
  36228. * Get the local transformation of the primitive
  36229. */
  36230. get: function () {
  36231. this._updateLocalTransform();
  36232. return this._localTransform;
  36233. },
  36234. enumerable: true,
  36235. configurable: true
  36236. });
  36237. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  36238. /**
  36239. * Get the boundingInfo associated to the primitive.
  36240. * The value is supposed to be always up to date
  36241. */
  36242. get: function () {
  36243. if (this._boundingInfoDirty) {
  36244. this._boundingInfo = this.levelBoundingInfo.clone();
  36245. var bi = this._boundingInfo;
  36246. var tps = new BABYLON.BoundingInfo2D();
  36247. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  36248. var curChild = _a[_i];
  36249. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  36250. bi.unionToRef(tps, bi);
  36251. }
  36252. this._boundingInfoDirty = false;
  36253. }
  36254. return this._boundingInfo;
  36255. },
  36256. enumerable: true,
  36257. configurable: true
  36258. });
  36259. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  36260. /**
  36261. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  36262. */
  36263. get: function () {
  36264. return this._pointerEventObservable;
  36265. },
  36266. enumerable: true,
  36267. configurable: true
  36268. });
  36269. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  36270. return false;
  36271. };
  36272. /**
  36273. * Capture all the Events of the given PointerId for this primitive.
  36274. * Don't forget to call releasePointerEventsCapture when done.
  36275. * @param pointerId the Id of the pointer to capture the events from.
  36276. */
  36277. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  36278. return this.owner._setPointerCapture(pointerId, this);
  36279. };
  36280. /**
  36281. * Release a captured pointer made with setPointerEventCapture.
  36282. * @param pointerId the Id of the pointer to release the capture from.
  36283. */
  36284. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  36285. return this.owner._releasePointerCapture(pointerId, this);
  36286. };
  36287. /**
  36288. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  36289. * @param intersectInfo contains the settings of the intersection to perform, to setup before calling this method as well as the result, available after a call to this method.
  36290. */
  36291. Prim2DBase.prototype.intersect = function (intersectInfo) {
  36292. if (!intersectInfo) {
  36293. return false;
  36294. }
  36295. // If this is null it means this method is call for the first level, initialize stuffs
  36296. var firstLevel = !intersectInfo._globalPickPosition;
  36297. if (firstLevel) {
  36298. // Compute the pickPosition in global space and use it to find the local position for each level down, always relative from the world to get the maximum accuracy (and speed). The other way would have been to compute in local every level down relative to its parent's local, which wouldn't be as accurate (even if javascript number is 80bits accurate).
  36299. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  36300. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  36301. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  36302. intersectInfo.intersectedPrimitives = new Array();
  36303. intersectInfo.topMostIntersectedPrimitive = null;
  36304. }
  36305. if (!intersectInfo.intersectHidden && !this.isVisible) {
  36306. return false;
  36307. }
  36308. // Fast rejection test with boundingInfo
  36309. if (!this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  36310. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  36311. intersectInfo._exit(firstLevel);
  36312. return false;
  36313. }
  36314. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  36315. var levelIntersectRes = this.levelIntersect(intersectInfo);
  36316. if (levelIntersectRes) {
  36317. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  36318. intersectInfo.intersectedPrimitives.push(pii);
  36319. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.getActualZOffset() > pii.prim.getActualZOffset())) {
  36320. intersectInfo.topMostIntersectedPrimitive = pii;
  36321. }
  36322. // If we must stop at the first intersection, we're done, quit!
  36323. if (intersectInfo.findFirstOnly) {
  36324. intersectInfo._exit(firstLevel);
  36325. return true;
  36326. }
  36327. }
  36328. // Recurse to children if needed
  36329. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  36330. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  36331. var curChild = _a[_i];
  36332. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  36333. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  36334. continue;
  36335. }
  36336. // Must compute the localPickLocation for the children level
  36337. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  36338. // If we got an intersection with the child and we only need to find the first one, quit!
  36339. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  36340. intersectInfo._exit(firstLevel);
  36341. return true;
  36342. }
  36343. }
  36344. }
  36345. intersectInfo._exit(firstLevel);
  36346. return intersectInfo.isIntersected;
  36347. };
  36348. Prim2DBase.prototype.moveChild = function (child, previous) {
  36349. if (child.parent !== this) {
  36350. return false;
  36351. }
  36352. var prevOffset, nextOffset;
  36353. var childIndex = this._children.indexOf(child);
  36354. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  36355. // Move to first position
  36356. if (!previous) {
  36357. prevOffset = 1;
  36358. nextOffset = this._children[1]._siblingDepthOffset;
  36359. }
  36360. else {
  36361. prevOffset = this._children[prevIndex]._siblingDepthOffset;
  36362. nextOffset = this._children[prevIndex + 1]._siblingDepthOffset;
  36363. }
  36364. child._siblingDepthOffset = (nextOffset - prevOffset) / 2;
  36365. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  36366. };
  36367. Prim2DBase.prototype.addChild = function (child) {
  36368. child._siblingDepthOffset = (this._children.length + 1) * this.owner.hierarchySiblingZDelta;
  36369. child._depthLevel = this._depthLevel + 1;
  36370. child._hierarchyDepthOffset = child._depthLevel * this.owner.hierarchyLevelZFactor;
  36371. this._children.push(child);
  36372. };
  36373. Prim2DBase.prototype.dispose = function () {
  36374. if (!_super.prototype.dispose.call(this)) {
  36375. return false;
  36376. }
  36377. // If there's a parent, remove this object from its parent list
  36378. if (this._parent) {
  36379. var i = this._parent._children.indexOf(this);
  36380. if (i !== undefined) {
  36381. this._parent._children.splice(i, 1);
  36382. }
  36383. this._parent = null;
  36384. }
  36385. // Recurse dispose to children
  36386. if (this._children) {
  36387. while (this._children.length > 0) {
  36388. this._children[this._children.length - 1].dispose();
  36389. }
  36390. }
  36391. return true;
  36392. };
  36393. Prim2DBase.prototype.getActualZOffset = function () {
  36394. return this._zOrder || 1 - (this._siblingDepthOffset + this._hierarchyDepthOffset);
  36395. };
  36396. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  36397. if (this._renderGroup) {
  36398. this._renderGroup._addPrimToDirtyList(this);
  36399. }
  36400. };
  36401. Prim2DBase.prototype._needPrepare = function () {
  36402. return (this.isVisible || this._visibilityChanged) && (this._modelDirty || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep));
  36403. };
  36404. Prim2DBase.prototype._prepareRender = function (context) {
  36405. this._prepareRenderPre(context);
  36406. this._prepareRenderPost(context);
  36407. };
  36408. Prim2DBase.prototype._prepareRenderPre = function (context) {
  36409. };
  36410. Prim2DBase.prototype._prepareRenderPost = function (context) {
  36411. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  36412. if (this instanceof BABYLON.Group2D) {
  36413. var self = this;
  36414. if (self.isRenderableGroup) {
  36415. return;
  36416. }
  36417. }
  36418. // Check if we need to recurse the prepare to children primitives
  36419. // - must have children
  36420. // - the global transform of this level have changed, or
  36421. // - the visible state of primitive has changed
  36422. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  36423. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  36424. this._children.forEach(function (c) {
  36425. // As usual stop the recursion if we meet a renderable group
  36426. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  36427. c._prepareRender(context);
  36428. }
  36429. });
  36430. }
  36431. // Finally reset the dirty flags as we've processed everything
  36432. this._modelDirty = false;
  36433. this._instanceDirtyFlags = 0;
  36434. };
  36435. Prim2DBase.CheckParent = function (parent) {
  36436. if (!parent) {
  36437. throw new Error("A Primitive needs a valid Parent, it can be any kind of Primitives based types, even the Canvas (with the exception that only Group2D can be direct child of a Canvas if the cache strategy used is TOPLEVELGROUPS)");
  36438. }
  36439. };
  36440. Prim2DBase.prototype.updateGlobalTransVisOf = function (list, recurse) {
  36441. for (var _i = 0; _i < list.length; _i++) {
  36442. var cur = list[_i];
  36443. cur.updateGlobalTransVis(recurse);
  36444. }
  36445. };
  36446. Prim2DBase.prototype._updateLocalTransform = function () {
  36447. var tflags = Prim2DBase.positionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId;
  36448. if (this.checkPropertiesDirty(tflags)) {
  36449. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  36450. var local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale, this._scale, this._scale), rot, new BABYLON.Vector3(this._position.x, this._position.y, 0));
  36451. this._localTransform = local;
  36452. this.clearPropertiesDirty(tflags);
  36453. // this is important to access actualSize AFTER fetching a first version of the local transform and reset the dirty flag, because accessing actualSize on a Group2D which actualSize is built from its content will trigger a call to this very method on this very object. We won't mind about the origin offset not being computed, as long as we return a local transform based on the position/rotation/scale
  36454. //var actualSize = this.actualSize;
  36455. //if (!actualSize) {
  36456. // throw new Error(`The primitive type: ${Tools.getClassName(this)} must implement the actualSize get property!`);
  36457. //}
  36458. //local.m[12] -= (actualSize.width * this.origin.x) * local.m[0] + (actualSize.height * this.origin.y) * local.m[4];
  36459. //local.m[13] -= (actualSize.width * this.origin.x) * local.m[1] + (actualSize.height * this.origin.y) * local.m[5];
  36460. return true;
  36461. }
  36462. return false;
  36463. };
  36464. Prim2DBase.prototype.updateGlobalTransVis = function (recurse) {
  36465. if (this.isDisposed) {
  36466. return;
  36467. }
  36468. // Check if the parent is synced
  36469. if (this._parent && this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  36470. this._parent.updateGlobalTransVis(false);
  36471. }
  36472. // Check if we must update this prim
  36473. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  36474. var curVisibleState = this.isVisible;
  36475. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  36476. // Detect a change of visibility
  36477. this._visibilityChanged = (curVisibleState !== undefined) && curVisibleState !== this.isVisible;
  36478. // Get/compute the localTransform
  36479. var localDirty = this._updateLocalTransform();
  36480. // Check if we have to update the globalTransform
  36481. if (!this._globalTransform || localDirty || (this._parent && this._parent._globalTransformStep !== this._parentTransformStep)) {
  36482. this._globalTransform = this._parent ? this._localTransform.multiply(this._parent._globalTransform) : this._localTransform;
  36483. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  36484. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  36485. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  36486. }
  36487. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  36488. }
  36489. if (recurse) {
  36490. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  36491. var child = _a[_i];
  36492. // Stop the recursion if we meet a renderable group
  36493. child.updateGlobalTransVis(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  36494. }
  36495. }
  36496. };
  36497. Prim2DBase.PRIM2DBASE_PROPCOUNT = 10;
  36498. __decorate([
  36499. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.positionProperty = pi; }, false, true)
  36500. ], Prim2DBase.prototype, "position", null);
  36501. __decorate([
  36502. BABYLON.instanceLevelProperty(2, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  36503. ], Prim2DBase.prototype, "rotation", null);
  36504. __decorate([
  36505. BABYLON.instanceLevelProperty(3, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  36506. ], Prim2DBase.prototype, "scale", null);
  36507. __decorate([
  36508. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  36509. ], Prim2DBase.prototype, "origin", null);
  36510. __decorate([
  36511. BABYLON.dynamicLevelProperty(5, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  36512. ], Prim2DBase.prototype, "levelVisible", null);
  36513. __decorate([
  36514. BABYLON.instanceLevelProperty(6, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  36515. ], Prim2DBase.prototype, "isVisible", null);
  36516. __decorate([
  36517. BABYLON.instanceLevelProperty(7, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  36518. ], Prim2DBase.prototype, "zOrder", null);
  36519. Prim2DBase = __decorate([
  36520. BABYLON.className("Prim2DBase")
  36521. ], Prim2DBase);
  36522. return Prim2DBase;
  36523. })(BABYLON.SmartPropertyPrim);
  36524. BABYLON.Prim2DBase = Prim2DBase;
  36525. })(BABYLON || (BABYLON = {}));
  36526. var BABYLON;
  36527. (function (BABYLON) {
  36528. var GroupInstanceInfo = (function () {
  36529. function GroupInstanceInfo(owner, cache) {
  36530. this._owner = owner;
  36531. this._modelCache = cache;
  36532. this._modelCache.addRef();
  36533. this._instancesPartsData = new Array();
  36534. this._instancesPartsBuffer = new Array();
  36535. this._instancesPartsBufferSize = new Array();
  36536. this._partIndexFromId = new BABYLON.StringDictionary();
  36537. this._instancesPartsUsedShaderCategories = new Array();
  36538. }
  36539. GroupInstanceInfo.prototype.dispose = function () {
  36540. if (this._isDisposed) {
  36541. return false;
  36542. }
  36543. if (this._modelCache) {
  36544. this._modelCache.dispose();
  36545. }
  36546. var engine = this._owner.owner.engine;
  36547. if (this._instancesPartsBuffer) {
  36548. this._instancesPartsBuffer.forEach(function (b) {
  36549. engine._releaseBuffer(b);
  36550. });
  36551. }
  36552. this._partIndexFromId = null;
  36553. this._instancesPartsData = null;
  36554. this._instancesPartsBufferSize = null;
  36555. this._instancesPartsUsedShaderCategories = null;
  36556. return true;
  36557. };
  36558. return GroupInstanceInfo;
  36559. })();
  36560. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  36561. var ModelRenderCache = (function () {
  36562. function ModelRenderCache(engine, modelKey, isTransparent) {
  36563. this._engine = engine;
  36564. this._modelKey = modelKey;
  36565. this._isTransparent = isTransparent;
  36566. this._nextKey = 1;
  36567. this._refCounter = 1;
  36568. this._instancesData = new BABYLON.StringDictionary();
  36569. }
  36570. ModelRenderCache.prototype.dispose = function () {
  36571. if (--this._refCounter !== 0) {
  36572. return false;
  36573. }
  36574. // Remove the Model Render Cache from the global dictionary
  36575. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  36576. if (edata) {
  36577. edata.DisposeModelRenderCache(this);
  36578. }
  36579. return true;
  36580. };
  36581. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  36582. get: function () {
  36583. return this._refCounter <= 0;
  36584. },
  36585. enumerable: true,
  36586. configurable: true
  36587. });
  36588. ModelRenderCache.prototype.addRef = function () {
  36589. return ++this._refCounter;
  36590. };
  36591. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  36592. get: function () {
  36593. return this._modelKey;
  36594. },
  36595. enumerable: true,
  36596. configurable: true
  36597. });
  36598. /**
  36599. * Render the model instances
  36600. * @param instanceInfo
  36601. * @param context
  36602. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  36603. */
  36604. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  36605. return true;
  36606. };
  36607. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  36608. var key = this._nextKey.toString();
  36609. if (!this._instancesData.add(key, data)) {
  36610. throw Error("Key: " + key + " is already allocated");
  36611. }
  36612. ++this._nextKey;
  36613. return key;
  36614. };
  36615. ModelRenderCache.prototype.removeInstanceData = function (key) {
  36616. this._instancesData.remove(key);
  36617. };
  36618. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  36619. for (var i = 0; i < this._partIdList.length; i++) {
  36620. if (this._partIdList[i] === partId) {
  36621. return i;
  36622. }
  36623. }
  36624. return null;
  36625. };
  36626. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  36627. var i = this.getPartIndexFromId(partId);
  36628. if (i === null) {
  36629. return null;
  36630. }
  36631. var ci = this._partsClassInfo[i];
  36632. var categories = this._partsUsedCategories[i];
  36633. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  36634. return res;
  36635. };
  36636. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  36637. var offset = (this._partsDataStride[partIndex] / 4) * elementCount;
  36638. var pci = this._partsClassInfo[partIndex];
  36639. var self = this;
  36640. pci.fullContent.forEach(function (k, v) {
  36641. if (!v.category || self._partsUsedCategories[partIndex].indexOf(v.category) !== 1) {
  36642. switch (v.dataType) {
  36643. case 4 /* float */:
  36644. {
  36645. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  36646. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  36647. break;
  36648. }
  36649. case 0 /* Vector2 */:
  36650. {
  36651. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  36652. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  36653. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  36654. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  36655. break;
  36656. }
  36657. case 5 /* Color3 */:
  36658. case 1 /* Vector3 */:
  36659. {
  36660. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  36661. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  36662. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  36663. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  36664. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  36665. break;
  36666. }
  36667. case 6 /* Color4 */:
  36668. case 2 /* Vector4 */:
  36669. {
  36670. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  36671. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  36672. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  36673. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  36674. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  36675. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  36676. break;
  36677. }
  36678. default:
  36679. }
  36680. }
  36681. });
  36682. };
  36683. Object.defineProperty(ModelRenderCache.prototype, "isTransparent", {
  36684. get: function () {
  36685. return this._isTransparent;
  36686. },
  36687. enumerable: true,
  36688. configurable: true
  36689. });
  36690. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  36691. // let i = this.getPartIndexFromId(partId);
  36692. // if (i === null) {
  36693. // return null;
  36694. // }
  36695. // let pci = this._partsClassInfo[i];
  36696. // pci.fullContent.forEach((k, v) => {
  36697. // if (uniforms.indexOf(v.attributeName) !== -1) {
  36698. // v.uniformLocation = effect.getUniform(v.attributeName);
  36699. // }
  36700. // });
  36701. //}
  36702. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  36703. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  36704. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  36705. return ModelRenderCache;
  36706. })();
  36707. BABYLON.ModelRenderCache = ModelRenderCache;
  36708. })(BABYLON || (BABYLON = {}));
  36709. var BABYLON;
  36710. (function (BABYLON) {
  36711. var InstanceClassInfo = (function () {
  36712. function InstanceClassInfo(base) {
  36713. this._baseInfo = base;
  36714. this._nextOffset = new BABYLON.StringDictionary();
  36715. this._attributes = new Array();
  36716. }
  36717. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  36718. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  36719. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  36720. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  36721. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  36722. if (push) {
  36723. this._attributes.push(propInfo);
  36724. }
  36725. };
  36726. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  36727. var catInline = categories.join(";");
  36728. var res = new Array();
  36729. var curInfo = this;
  36730. while (curInfo) {
  36731. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  36732. var attrib = _a[_i];
  36733. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  36734. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  36735. var index = effect.getAttributeLocationByName(attrib.attributeName);
  36736. var iai = new BABYLON.InstancingAttributeInfo();
  36737. iai.index = index;
  36738. iai.attributeSize = attrib.size / 4; // attrib.size is in byte and we need to store in "component" (i.e float is 1, vec3 is 3)
  36739. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  36740. iai.attributeName = attrib.attributeName;
  36741. res.push(iai);
  36742. }
  36743. }
  36744. curInfo = curInfo._baseInfo;
  36745. }
  36746. return res;
  36747. };
  36748. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  36749. var res = new Array();
  36750. var curInfo = this;
  36751. while (curInfo) {
  36752. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  36753. var attrib = _a[_i];
  36754. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  36755. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  36756. res.push(attrib.attributeName);
  36757. }
  36758. }
  36759. curInfo = curInfo._baseInfo;
  36760. }
  36761. return res;
  36762. };
  36763. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  36764. var curOffset = 0;
  36765. var curBase = this._baseInfo;
  36766. while (curBase) {
  36767. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  36768. curBase = curBase._baseInfo;
  36769. }
  36770. return curOffset;
  36771. };
  36772. return InstanceClassInfo;
  36773. })();
  36774. BABYLON.InstanceClassInfo = InstanceClassInfo;
  36775. var InstancePropInfo = (function () {
  36776. //uniformLocation: WebGLUniformLocation;
  36777. function InstancePropInfo() {
  36778. this.instanceOffset = new BABYLON.StringDictionary();
  36779. }
  36780. InstancePropInfo.prototype.setSize = function (val) {
  36781. if (val instanceof BABYLON.Vector2) {
  36782. this.size = 8;
  36783. this.dataType = 0 /* Vector2 */;
  36784. return;
  36785. }
  36786. if (val instanceof BABYLON.Vector3) {
  36787. this.size = 12;
  36788. this.dataType = 1 /* Vector3 */;
  36789. return;
  36790. }
  36791. if (val instanceof BABYLON.Vector4) {
  36792. this.size = 16;
  36793. this.dataType = 2 /* Vector4 */;
  36794. return;
  36795. }
  36796. if (val instanceof BABYLON.Matrix) {
  36797. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  36798. }
  36799. if (typeof (val) === "number") {
  36800. this.size = 4;
  36801. this.dataType = 4 /* float */;
  36802. return;
  36803. }
  36804. if (val instanceof BABYLON.Color3) {
  36805. this.size = 12;
  36806. this.dataType = 5 /* Color3 */;
  36807. return;
  36808. }
  36809. if (val instanceof BABYLON.Color4) {
  36810. this.size = 16;
  36811. this.dataType = 6 /* Color4 */;
  36812. return;
  36813. }
  36814. return;
  36815. };
  36816. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  36817. switch (this.dataType) {
  36818. case 0 /* Vector2 */:
  36819. {
  36820. var v = val;
  36821. array[offset + 0] = v.x;
  36822. array[offset + 1] = v.y;
  36823. break;
  36824. }
  36825. case 1 /* Vector3 */:
  36826. {
  36827. var v = val;
  36828. array[offset + 0] = v.x;
  36829. array[offset + 1] = v.y;
  36830. array[offset + 2] = v.z;
  36831. break;
  36832. }
  36833. case 2 /* Vector4 */:
  36834. {
  36835. var v = val;
  36836. array[offset + 0] = v.x;
  36837. array[offset + 1] = v.y;
  36838. array[offset + 2] = v.z;
  36839. array[offset + 3] = v.w;
  36840. break;
  36841. }
  36842. case 5 /* Color3 */:
  36843. {
  36844. var v = val;
  36845. array[offset + 0] = v.r;
  36846. array[offset + 1] = v.g;
  36847. array[offset + 2] = v.b;
  36848. break;
  36849. }
  36850. case 6 /* Color4 */:
  36851. {
  36852. var v = val;
  36853. array[offset + 0] = v.r;
  36854. array[offset + 1] = v.g;
  36855. array[offset + 2] = v.b;
  36856. array[offset + 3] = v.a;
  36857. break;
  36858. }
  36859. case 4 /* float */:
  36860. {
  36861. var v = val;
  36862. array[offset] = v;
  36863. break;
  36864. }
  36865. case 3 /* Matrix */:
  36866. {
  36867. var v = val;
  36868. for (var i = 0; i < 16; i++) {
  36869. array[offset + i] = v.m[i];
  36870. }
  36871. break;
  36872. }
  36873. }
  36874. };
  36875. return InstancePropInfo;
  36876. })();
  36877. BABYLON.InstancePropInfo = InstancePropInfo;
  36878. function instanceData(category, shaderAttributeName) {
  36879. return function (target, propName, descriptor) {
  36880. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  36881. var node = dic.getLevelOf(target);
  36882. var instanceDataName = propName;
  36883. shaderAttributeName = shaderAttributeName || instanceDataName;
  36884. var info = node.levelContent.get(instanceDataName);
  36885. if (info) {
  36886. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  36887. }
  36888. info = new InstancePropInfo();
  36889. info.attributeName = shaderAttributeName;
  36890. info.category = category || null;
  36891. node.levelContent.add(instanceDataName, info);
  36892. descriptor.get = function () {
  36893. return null;
  36894. };
  36895. descriptor.set = function (val) {
  36896. if (!info.size) {
  36897. info.setSize(val);
  36898. node.classContent.mapProperty(info, true);
  36899. }
  36900. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  36901. node.classContent.mapProperty(info, false);
  36902. }
  36903. var obj = this;
  36904. if (obj.dataBuffer && obj.dataElements) {
  36905. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  36906. info.writeData(obj.dataBuffer.buffer, offset, val);
  36907. }
  36908. };
  36909. };
  36910. }
  36911. BABYLON.instanceData = instanceData;
  36912. var InstanceDataBase = (function () {
  36913. function InstanceDataBase(partId, dataElementCount) {
  36914. this.id = partId;
  36915. this.curElement = 0;
  36916. this.dataElementCount = dataElementCount;
  36917. }
  36918. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  36919. get: function () {
  36920. return null;
  36921. },
  36922. enumerable: true,
  36923. configurable: true
  36924. });
  36925. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  36926. get: function () {
  36927. return null;
  36928. },
  36929. enumerable: true,
  36930. configurable: true
  36931. });
  36932. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  36933. get: function () {
  36934. return null;
  36935. },
  36936. enumerable: true,
  36937. configurable: true
  36938. });
  36939. Object.defineProperty(InstanceDataBase.prototype, "origin", {
  36940. get: function () {
  36941. return null;
  36942. },
  36943. enumerable: true,
  36944. configurable: true
  36945. });
  36946. InstanceDataBase.prototype.getClassTreeInfo = function () {
  36947. if (!this.typeInfo) {
  36948. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  36949. }
  36950. return this.typeInfo;
  36951. };
  36952. InstanceDataBase.prototype.allocElements = function () {
  36953. if (!this.dataBuffer) {
  36954. return;
  36955. }
  36956. var res = new Array(this.dataElementCount);
  36957. for (var i = 0; i < this.dataElementCount; i++) {
  36958. res[i] = this.dataBuffer.allocElement();
  36959. }
  36960. this.dataElements = res;
  36961. };
  36962. InstanceDataBase.prototype.freeElements = function () {
  36963. if (!this.dataElements) {
  36964. return;
  36965. }
  36966. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  36967. var ei = _a[_i];
  36968. this.dataBuffer.freeElement(ei);
  36969. }
  36970. this.dataElements = null;
  36971. };
  36972. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  36973. get: function () {
  36974. return this._dataElementCount;
  36975. },
  36976. set: function (value) {
  36977. if (value === this._dataElementCount) {
  36978. return;
  36979. }
  36980. this.freeElements();
  36981. this._dataElementCount = value;
  36982. this.allocElements();
  36983. },
  36984. enumerable: true,
  36985. configurable: true
  36986. });
  36987. __decorate([
  36988. instanceData()
  36989. ], InstanceDataBase.prototype, "zBias", null);
  36990. __decorate([
  36991. instanceData()
  36992. ], InstanceDataBase.prototype, "transformX", null);
  36993. __decorate([
  36994. instanceData()
  36995. ], InstanceDataBase.prototype, "transformY", null);
  36996. __decorate([
  36997. instanceData()
  36998. ], InstanceDataBase.prototype, "origin", null);
  36999. return InstanceDataBase;
  37000. })();
  37001. BABYLON.InstanceDataBase = InstanceDataBase;
  37002. var RenderablePrim2D = (function (_super) {
  37003. __extends(RenderablePrim2D, _super);
  37004. function RenderablePrim2D() {
  37005. _super.apply(this, arguments);
  37006. }
  37007. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  37008. get: function () {
  37009. return this._isTransparent;
  37010. },
  37011. set: function (value) {
  37012. this._isTransparent = value;
  37013. },
  37014. enumerable: true,
  37015. configurable: true
  37016. });
  37017. RenderablePrim2D.prototype.setupRenderablePrim2D = function (owner, parent, id, position, isVisible) {
  37018. this.setupPrim2DBase(owner, parent, id, position);
  37019. this._isTransparent = false;
  37020. };
  37021. RenderablePrim2D.prototype.dispose = function () {
  37022. if (!_super.prototype.dispose.call(this)) {
  37023. return false;
  37024. }
  37025. if (this._modelRenderInstanceID) {
  37026. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  37027. this._modelRenderInstanceID = null;
  37028. }
  37029. if (this._modelRenderCache) {
  37030. this._modelRenderCache.dispose();
  37031. this._modelRenderCache = null;
  37032. }
  37033. if (this._instanceDataParts) {
  37034. this._instanceDataParts.forEach(function (p) {
  37035. p.freeElements();
  37036. });
  37037. this._instanceDataParts = null;
  37038. }
  37039. return true;
  37040. };
  37041. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  37042. var _this = this;
  37043. _super.prototype._prepareRenderPre.call(this, context);
  37044. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  37045. if (this._modelDirty && this._modelRenderInstanceID) {
  37046. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  37047. this._modelRenderInstanceID = null;
  37048. }
  37049. // Need to create the model?
  37050. var setupModelRenderCache = false;
  37051. if (!this._modelRenderCache || this._modelDirty) {
  37052. if (this._modelRenderCache) {
  37053. this._modelRenderCache.dispose();
  37054. }
  37055. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  37056. var mrc = _this.createModelRenderCache(key, _this.isTransparent);
  37057. setupModelRenderCache = true;
  37058. return mrc;
  37059. });
  37060. this._modelDirty = false;
  37061. // if this is still false it means the MRC already exists, so we add a reference to it
  37062. if (!setupModelRenderCache) {
  37063. this._modelRenderCache.addRef();
  37064. }
  37065. }
  37066. var gii;
  37067. var newInstance = false;
  37068. // Need to create the instance data parts?
  37069. if (!this._modelRenderInstanceID) {
  37070. // Yes, flag it for later, more processing will have to be done
  37071. newInstance = true;
  37072. // Create the instance data parts of the primitive and store them
  37073. var parts = this.createInstanceDataParts();
  37074. this._instanceDataParts = parts;
  37075. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  37076. if (!this._modelRenderCache._partsDataStride) {
  37077. var ctiArray = new Array();
  37078. var dataStrides = new Array();
  37079. var usedCatList = new Array();
  37080. var partIdList = new Array();
  37081. var joinedUsedCatList = new Array();
  37082. for (var _i = 0; _i < parts.length; _i++) {
  37083. var dataPart = parts[_i];
  37084. var cat = this.getUsedShaderCategories(dataPart);
  37085. var cti = dataPart.getClassTreeInfo();
  37086. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  37087. var curVisible = this.isVisible;
  37088. this.isVisible = true;
  37089. // We manually trigger refreshInstanceData for the only sake of evaluating each instance property size and offset in the instance data, this can only be made at runtime. Once it's done we have all the information to create the instance data buffer.
  37090. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  37091. var joinCat = cat.join(";");
  37092. joinedUsedCatList.push(joinCat);
  37093. InstanceClassInfo._CurCategories = joinCat;
  37094. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  37095. this.refreshInstanceDataPart(dataPart);
  37096. this.afterRefreshForLayoutConstruction(dataPart, obj);
  37097. this.isVisible = curVisible;
  37098. var size = 0;
  37099. cti.fullContent.forEach(function (k, v) {
  37100. if (!v.category || cat.indexOf(v.category) !== -1) {
  37101. if (!v.size) {
  37102. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  37103. }
  37104. else {
  37105. size += v.size;
  37106. }
  37107. }
  37108. });
  37109. dataStrides.push(size);
  37110. usedCatList.push(cat);
  37111. ctiArray.push(cti);
  37112. partIdList.push(dataPart.id);
  37113. }
  37114. this._modelRenderCache._partsDataStride = dataStrides;
  37115. this._modelRenderCache._partsUsedCategories = usedCatList;
  37116. this._modelRenderCache._partsJoinedUsedCategories = joinedUsedCatList;
  37117. this._modelRenderCache._partsClassInfo = ctiArray;
  37118. this._modelRenderCache._partIdList = partIdList;
  37119. }
  37120. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  37121. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  37122. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  37123. gii = this.renderGroup._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) { return new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache); });
  37124. // First time init of the GroupInstanceInfo
  37125. if (gii._instancesPartsData.length === 0) {
  37126. for (var j = 0; j < this._modelRenderCache._partsDataStride.length; j++) {
  37127. var stride = this._modelRenderCache._partsDataStride[j];
  37128. gii._instancesPartsData.push(new BABYLON.DynamicFloatArray(stride / 4, 50));
  37129. gii._partIndexFromId.add(this._modelRenderCache._partIdList[j].toString(), j);
  37130. for (var _a = 0, _b = this._instanceDataParts; _a < _b.length; _a++) {
  37131. var part = _b[_a];
  37132. gii._instancesPartsUsedShaderCategories[gii._partIndexFromId.get(part.id.toString())] = this.getUsedShaderCategories(part).join(";");
  37133. }
  37134. }
  37135. }
  37136. // For each instance data part of the primitive, allocate the instanced element it needs for render
  37137. for (var i = 0; i < parts.length; i++) {
  37138. var part = parts[i];
  37139. part.dataBuffer = gii._instancesPartsData[i];
  37140. part.allocElements();
  37141. }
  37142. // Add the instance data parts in the ModelRenderCache they belong, track them by storing their ID in the primitive in case we need to change the model later on, so we'll have to release the allocated instance data parts because they won't fit anymore
  37143. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  37144. }
  37145. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  37146. if (setupModelRenderCache) {
  37147. this.setupModelRenderCache(this._modelRenderCache);
  37148. }
  37149. // At this stage we have everything correctly initialized, ModelRenderCache is setup, Model Instance data are good too, they have allocated elements in the Instanced DynamicFloatArray.
  37150. // The last thing to do is check if the instanced related data must be updated because a InstanceLevel property had changed or the primitive visibility changed.
  37151. if (this._visibilityChanged || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  37152. // Fetch the GroupInstanceInfo if we don't already have it
  37153. if (!gii) {
  37154. gii = this.renderGroup._renderGroupInstancesInfo.get(this.modelKey);
  37155. }
  37156. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  37157. for (var _c = 0, _d = this._instanceDataParts; _c < _d.length; _c++) {
  37158. var part = _d[_c];
  37159. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  37160. if (this._visibilityChanged && !part.dataElements) {
  37161. part.allocElements();
  37162. }
  37163. InstanceClassInfo._CurCategories = gii._instancesPartsUsedShaderCategories[gii._partIndexFromId.get(part.id.toString())];
  37164. // Will return false if the instance should not be rendered (not visible or other any reasons)
  37165. if (!this.refreshInstanceDataPart(part)) {
  37166. // Free the data element
  37167. if (part.dataElements) {
  37168. part.freeElements();
  37169. }
  37170. }
  37171. }
  37172. this._instanceDirtyFlags = 0;
  37173. gii._dirtyInstancesData = true;
  37174. this._visibilityChanged = false; // Reset the flag as we've handled the case
  37175. }
  37176. };
  37177. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes) {
  37178. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  37179. if (!dataPart) {
  37180. return null;
  37181. }
  37182. var instancedArray = this.owner.supportInstancedArray;
  37183. var cti = dataPart.getClassTreeInfo();
  37184. var categories = this.getUsedShaderCategories(dataPart);
  37185. var att = cti.classContent.getShaderAttributes(categories);
  37186. var defines = "";
  37187. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  37188. if (instancedArray) {
  37189. defines += "#define Instanced\n";
  37190. }
  37191. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  37192. };
  37193. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  37194. get: function () {
  37195. return this._modelRenderCache;
  37196. },
  37197. enumerable: true,
  37198. configurable: true
  37199. });
  37200. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  37201. return null;
  37202. };
  37203. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  37204. };
  37205. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  37206. return null;
  37207. };
  37208. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  37209. return [];
  37210. };
  37211. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  37212. };
  37213. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  37214. };
  37215. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  37216. if (!this.isVisible) {
  37217. return false;
  37218. }
  37219. part.isVisible = this.isVisible;
  37220. // Which means, if there's only one data element, we're update it from this method, otherwise it is the responsibility of the derived class to call updateInstanceDataPart as many times as needed, properly (look at Text2D's implementation for more information)
  37221. if (part.dataElementCount === 1) {
  37222. part.curElement = 0;
  37223. this.updateInstanceDataPart(part);
  37224. }
  37225. return true;
  37226. };
  37227. /**
  37228. * Update the instanceDataBase level properties of a part
  37229. * @param part the part to update
  37230. * @param positionOffset to use in multi part per primitive (e.g. the Text2D has N parts for N letter to display), this give the offset to apply (e.g. the position of the letter from the bottom/left corner of the text). You MUST also set customSize.
  37231. * @param customSize to use in multi part per primitive, this is the size of the overall primitive to display (the bounding rect's size of the Text, for instance). This is mandatory to compute correct transformation based on the Primitive's origin property.
  37232. */
  37233. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset, customSize) {
  37234. if (positionOffset === void 0) { positionOffset = null; }
  37235. if (customSize === void 0) { customSize = null; }
  37236. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  37237. var size = this.renderGroup.viewportSize;
  37238. var zBias = this.getActualZOffset();
  37239. var offX = 0;
  37240. var offY = 0;
  37241. // If there's an offset, apply the global transformation matrix on it to get a global offset
  37242. if (positionOffset && customSize) {
  37243. offX = (positionOffset.x - (customSize.width * this.origin.x)) * t.m[0] + (positionOffset.y - (customSize.height * this.origin.y)) * t.m[4];
  37244. offY = (positionOffset.x - (customSize.width * this.origin.x)) * t.m[1] + (positionOffset.y - (customSize.height * this.origin.y)) * t.m[5];
  37245. }
  37246. // Have to convert the coordinates to clip space which is ranged between [-1;1] on X and Y axis, with 0,0 being the left/bottom corner
  37247. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  37248. // RenderGroup Width and Height are multiplied by zBias because the VertexShader will multiply X and Y by W, which is 1/zBias. As we divide our coordinate by these Width/Height, we will also divide by the zBias to compensate the operation made by the VertexShader.
  37249. // So for X:
  37250. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  37251. // - tx.w = (value * 2 / width) - 1: w stores the translation in renderGroup coordinates so (value * 2 / width) to switch to a clip space translation value. - 1 is to offset the overall [0;2] to [-1;1]. Don't forget it's -(1/zBias) and not -1 because everything need to be scaled by 1/zBias.
  37252. var w = size.width * zBias;
  37253. var h = size.height * zBias;
  37254. var invZBias = 1 / zBias;
  37255. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * 2 / w) - (invZBias));
  37256. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * 2 / h) - (invZBias));
  37257. part.transformX = tx;
  37258. part.transformY = ty;
  37259. part.origin = this.origin;
  37260. // Stores zBias and it's inverse value because that's needed to compute the clip space W coordinate (which is 1/Z, so 1/zBias)
  37261. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  37262. };
  37263. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  37264. __decorate([
  37265. BABYLON.modelLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  37266. ], RenderablePrim2D.prototype, "isTransparent", null);
  37267. RenderablePrim2D = __decorate([
  37268. BABYLON.className("RenderablePrim2D")
  37269. ], RenderablePrim2D);
  37270. return RenderablePrim2D;
  37271. })(BABYLON.Prim2DBase);
  37272. BABYLON.RenderablePrim2D = RenderablePrim2D;
  37273. })(BABYLON || (BABYLON = {}));
  37274. var BABYLON;
  37275. (function (BABYLON) {
  37276. var Shape2D = (function (_super) {
  37277. __extends(Shape2D, _super);
  37278. function Shape2D() {
  37279. _super.apply(this, arguments);
  37280. }
  37281. Object.defineProperty(Shape2D.prototype, "border", {
  37282. get: function () {
  37283. return this._border;
  37284. },
  37285. set: function (value) {
  37286. this._border = value;
  37287. this._updateTransparencyStatus();
  37288. },
  37289. enumerable: true,
  37290. configurable: true
  37291. });
  37292. Object.defineProperty(Shape2D.prototype, "fill", {
  37293. get: function () {
  37294. return this._fill;
  37295. },
  37296. set: function (value) {
  37297. this._fill = value;
  37298. this._updateTransparencyStatus();
  37299. },
  37300. enumerable: true,
  37301. configurable: true
  37302. });
  37303. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  37304. get: function () {
  37305. return this._borderThickness;
  37306. },
  37307. set: function (value) {
  37308. this._borderThickness = value;
  37309. },
  37310. enumerable: true,
  37311. configurable: true
  37312. });
  37313. Shape2D.prototype.setupShape2D = function (owner, parent, id, position, isVisible, fill, border, borderThickness) {
  37314. if (borderThickness === void 0) { borderThickness = 1.0; }
  37315. this.setupRenderablePrim2D(owner, parent, id, position, isVisible);
  37316. this.border = border;
  37317. this.fill = fill;
  37318. this.borderThickness = borderThickness;
  37319. };
  37320. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  37321. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  37322. // Fill Part
  37323. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  37324. var fill = this.fill;
  37325. if (fill instanceof BABYLON.SolidColorBrush2D) {
  37326. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  37327. }
  37328. if (fill instanceof BABYLON.GradientColorBrush2D) {
  37329. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  37330. }
  37331. }
  37332. // Border Part
  37333. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  37334. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  37335. var border = this.border;
  37336. if (border instanceof BABYLON.SolidColorBrush2D) {
  37337. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  37338. }
  37339. if (border instanceof BABYLON.GradientColorBrush2D) {
  37340. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  37341. }
  37342. }
  37343. return cat;
  37344. };
  37345. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  37346. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  37347. return false;
  37348. }
  37349. // Fill Part
  37350. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  37351. var d = part;
  37352. if (this.fill) {
  37353. var fill = this.fill;
  37354. if (fill instanceof BABYLON.SolidColorBrush2D) {
  37355. d.fillSolidColor = fill.color;
  37356. }
  37357. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  37358. d.fillGradientColor1 = fill.color1;
  37359. d.fillGradientColor2 = fill.color2;
  37360. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(fill.scale, fill.scale, fill.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), fill.rotation), new BABYLON.Vector3(fill.translation.x, fill.translation.y, 0));
  37361. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  37362. d.fillGradientTY = ty;
  37363. }
  37364. }
  37365. }
  37366. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  37367. var d = part;
  37368. if (this.border) {
  37369. d.borderThickness = this.borderThickness;
  37370. var border = this.border;
  37371. if (border instanceof BABYLON.SolidColorBrush2D) {
  37372. d.borderSolidColor = border.color;
  37373. }
  37374. else if (border instanceof BABYLON.GradientColorBrush2D) {
  37375. d.borderGradientColor1 = border.color1;
  37376. d.borderGradientColor2 = border.color2;
  37377. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(border.scale, border.scale, border.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), border.rotation), new BABYLON.Vector3(border.translation.x, border.translation.y, 0));
  37378. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  37379. d.borderGradientTY = ty;
  37380. }
  37381. }
  37382. }
  37383. return true;
  37384. };
  37385. Shape2D.prototype._updateTransparencyStatus = function () {
  37386. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent());
  37387. };
  37388. Shape2D.SHAPE2D_BORDERPARTID = 1;
  37389. Shape2D.SHAPE2D_FILLPARTID = 2;
  37390. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  37391. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  37392. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  37393. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  37394. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  37395. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  37396. __decorate([
  37397. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  37398. ], Shape2D.prototype, "border", null);
  37399. __decorate([
  37400. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  37401. ], Shape2D.prototype, "fill", null);
  37402. __decorate([
  37403. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  37404. ], Shape2D.prototype, "borderThickness", null);
  37405. Shape2D = __decorate([
  37406. BABYLON.className("Shape2D")
  37407. ], Shape2D);
  37408. return Shape2D;
  37409. })(BABYLON.RenderablePrim2D);
  37410. BABYLON.Shape2D = Shape2D;
  37411. var Shape2DInstanceData = (function (_super) {
  37412. __extends(Shape2DInstanceData, _super);
  37413. function Shape2DInstanceData() {
  37414. _super.apply(this, arguments);
  37415. }
  37416. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  37417. // FILL ATTRIBUTES
  37418. get: function () {
  37419. return null;
  37420. },
  37421. enumerable: true,
  37422. configurable: true
  37423. });
  37424. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  37425. get: function () {
  37426. return null;
  37427. },
  37428. enumerable: true,
  37429. configurable: true
  37430. });
  37431. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  37432. get: function () {
  37433. return null;
  37434. },
  37435. enumerable: true,
  37436. configurable: true
  37437. });
  37438. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  37439. get: function () {
  37440. return null;
  37441. },
  37442. enumerable: true,
  37443. configurable: true
  37444. });
  37445. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  37446. // BORDER ATTRIBUTES
  37447. get: function () {
  37448. return null;
  37449. },
  37450. enumerable: true,
  37451. configurable: true
  37452. });
  37453. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  37454. get: function () {
  37455. return null;
  37456. },
  37457. enumerable: true,
  37458. configurable: true
  37459. });
  37460. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  37461. get: function () {
  37462. return null;
  37463. },
  37464. enumerable: true,
  37465. configurable: true
  37466. });
  37467. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  37468. get: function () {
  37469. return null;
  37470. },
  37471. enumerable: true,
  37472. configurable: true
  37473. });
  37474. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  37475. get: function () {
  37476. return null;
  37477. },
  37478. enumerable: true,
  37479. configurable: true
  37480. });
  37481. __decorate([
  37482. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  37483. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  37484. __decorate([
  37485. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  37486. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  37487. __decorate([
  37488. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  37489. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  37490. __decorate([
  37491. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  37492. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  37493. __decorate([
  37494. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  37495. ], Shape2DInstanceData.prototype, "borderThickness", null);
  37496. __decorate([
  37497. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  37498. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  37499. __decorate([
  37500. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  37501. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  37502. __decorate([
  37503. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  37504. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  37505. __decorate([
  37506. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  37507. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  37508. return Shape2DInstanceData;
  37509. })(BABYLON.InstanceDataBase);
  37510. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  37511. })(BABYLON || (BABYLON = {}));
  37512. var BABYLON;
  37513. (function (BABYLON) {
  37514. var Group2D = (function (_super) {
  37515. __extends(Group2D, _super);
  37516. /**
  37517. * Don't invoke directly, rely on Group2D.CreateXXX methods
  37518. */
  37519. function Group2D() {
  37520. _super.call(this);
  37521. this._primDirtyList = new Array();
  37522. this._childrenRenderableGroups = new Array();
  37523. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  37524. }
  37525. Group2D.CreateGroup2D = function (parent, id, position, size, cacheBehabior) {
  37526. if (cacheBehabior === void 0) { cacheBehabior = Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY; }
  37527. BABYLON.Prim2DBase.CheckParent(parent);
  37528. var g = new Group2D();
  37529. g.setupGroup2D(parent.owner, parent, id, position, size, cacheBehabior);
  37530. return g;
  37531. };
  37532. Group2D._createCachedCanvasGroup = function (owner) {
  37533. var g = new Group2D();
  37534. g.setupGroup2D(owner, null, "__cachedCanvasGroup__", BABYLON.Vector2.Zero());
  37535. g.origin = BABYLON.Vector2.Zero();
  37536. return g;
  37537. };
  37538. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  37539. this._bindCacheTarget();
  37540. var uv = vertexData.uvs;
  37541. var nodeuv = this._cacheNode.UVs;
  37542. for (var i = 0; i < 4; i++) {
  37543. uv[i * 2 + 0] = nodeuv[i].x;
  37544. uv[i * 2 + 1] = nodeuv[i].y;
  37545. }
  37546. material.diffuseTexture = this._cacheTexture;
  37547. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  37548. this._cacheTexture.hasAlpha = true;
  37549. this._unbindCacheTarget();
  37550. };
  37551. /**
  37552. * Call this method to remove this Group and its children from the Canvas
  37553. */
  37554. Group2D.prototype.dispose = function () {
  37555. if (!_super.prototype.dispose.call(this)) {
  37556. return false;
  37557. }
  37558. if (this._cacheRenderSprite) {
  37559. this._cacheRenderSprite.dispose();
  37560. this._cacheRenderSprite = null;
  37561. }
  37562. if (this._cacheTexture && this._cacheNode) {
  37563. this._cacheTexture.freeRect(this._cacheNode);
  37564. this._cacheTexture = null;
  37565. this._cacheNode = null;
  37566. }
  37567. if (this._primDirtyList) {
  37568. this._primDirtyList.splice(0);
  37569. this._primDirtyList = null;
  37570. }
  37571. if (this._renderGroupInstancesInfo) {
  37572. this._renderGroupInstancesInfo.forEach(function (k, v) {
  37573. v.dispose();
  37574. });
  37575. this._renderGroupInstancesInfo = null;
  37576. }
  37577. return true;
  37578. };
  37579. Group2D.prototype.setupGroup2D = function (owner, parent, id, position, size, cacheBehavior) {
  37580. if (cacheBehavior === void 0) { cacheBehavior = Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY; }
  37581. this._cacheBehavior = cacheBehavior;
  37582. this.setupPrim2DBase(owner, parent, id, position);
  37583. this.size = size;
  37584. this._viewportPosition = BABYLON.Vector2.Zero();
  37585. };
  37586. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  37587. /**
  37588. * @returns Returns true if the Group render content, false if it's a logical group only
  37589. */
  37590. get: function () {
  37591. return this._isRenderableGroup;
  37592. },
  37593. enumerable: true,
  37594. configurable: true
  37595. });
  37596. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  37597. /**
  37598. * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time
  37599. */
  37600. get: function () {
  37601. return this._isCachedGroup;
  37602. },
  37603. enumerable: true,
  37604. configurable: true
  37605. });
  37606. Object.defineProperty(Group2D.prototype, "size", {
  37607. get: function () {
  37608. return this._size;
  37609. },
  37610. /**
  37611. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  37612. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does.
  37613. */
  37614. set: function (val) {
  37615. this._size = val;
  37616. },
  37617. enumerable: true,
  37618. configurable: true
  37619. });
  37620. Object.defineProperty(Group2D.prototype, "viewportSize", {
  37621. get: function () {
  37622. return this._viewportSize;
  37623. },
  37624. enumerable: true,
  37625. configurable: true
  37626. });
  37627. Object.defineProperty(Group2D.prototype, "actualSize", {
  37628. get: function () {
  37629. // The computed size will be floor on both width and height
  37630. var actualSize;
  37631. // Return the size if set by the user
  37632. if (this._size) {
  37633. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  37634. }
  37635. else {
  37636. var m = this.boundingInfo.max();
  37637. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  37638. }
  37639. // Compare the size with the one we previously had, if it differ we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  37640. if (!actualSize.equals(this._actualSize)) {
  37641. this._instanceDirtyFlags |= Group2D.actualSizeProperty.flagId;
  37642. this._actualSize = actualSize;
  37643. this.handleGroupChanged(Group2D.actualSizeProperty);
  37644. }
  37645. return actualSize;
  37646. },
  37647. enumerable: true,
  37648. configurable: true
  37649. });
  37650. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  37651. /**
  37652. * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information.
  37653. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all.
  37654. */
  37655. get: function () {
  37656. return this._cacheBehavior;
  37657. },
  37658. enumerable: true,
  37659. configurable: true
  37660. });
  37661. Group2D.prototype._addPrimToDirtyList = function (prim) {
  37662. this._primDirtyList.push(prim);
  37663. };
  37664. Group2D.prototype._renderCachedCanvas = function (context) {
  37665. this.updateGlobalTransVis(true);
  37666. this._prepareGroupRender(context);
  37667. this._groupRender(context);
  37668. };
  37669. Group2D.prototype.levelIntersect = function (intersectInfo) {
  37670. // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true
  37671. return true;
  37672. };
  37673. Group2D.prototype.updateLevelBoundingInfo = function () {
  37674. var size;
  37675. // If the size is set by the user, the boundingInfo is computed from this value
  37676. if (this.size) {
  37677. size = this.size;
  37678. }
  37679. else {
  37680. size = new BABYLON.Size(0, 0);
  37681. }
  37682. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  37683. };
  37684. // Method called only on renderable groups to prepare the rendering
  37685. Group2D.prototype._prepareGroupRender = function (context) {
  37686. var sortedDirtyList = null;
  37687. // Update the Global Transformation and visibility status of the changed primitives
  37688. if ((this._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  37689. sortedDirtyList = this._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  37690. this.updateGlobalTransVisOf(sortedDirtyList, true);
  37691. }
  37692. // Setup the size of the rendering viewport
  37693. // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute
  37694. if (!this._isCachedGroup) {
  37695. // Compute the WebGL viewport's location/size
  37696. var t = this._globalTransform.getTranslation();
  37697. var s = this.actualSize.clone();
  37698. var rs = this.owner._renderingSize;
  37699. s.height = Math.min(s.height, rs.height - t.y);
  37700. s.width = Math.min(s.width, rs.width - t.x);
  37701. var x = t.x;
  37702. var y = t.y;
  37703. // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed
  37704. this._viewportPosition.x = x;
  37705. this._viewportPosition.y = y;
  37706. var vw = s.width;
  37707. var vh = s.height;
  37708. if (!this._viewportSize) {
  37709. this._viewportSize = new BABYLON.Size(vw, vh);
  37710. }
  37711. else {
  37712. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  37713. context.forceRefreshPrimitive = true;
  37714. }
  37715. this._viewportSize.width = vw;
  37716. this._viewportSize.height = vh;
  37717. }
  37718. }
  37719. else {
  37720. var newSize = this.actualSize.clone();
  37721. if (!newSize.equals(this._viewportSize)) {
  37722. context.forceRefreshPrimitive = true;
  37723. }
  37724. this._viewportSize = newSize;
  37725. }
  37726. if ((this._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  37727. // If the group is cached, set the dirty flag to true because of the incoming changes
  37728. this._cacheGroupDirty = this._isCachedGroup;
  37729. // If it's a force refresh, prepare all the children
  37730. if (context.forceRefreshPrimitive) {
  37731. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  37732. var p = _a[_i];
  37733. p._prepareRender(context);
  37734. }
  37735. }
  37736. else {
  37737. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  37738. // the hierarchyDepth in order to prepare primitives from top to bottom
  37739. if (!sortedDirtyList) {
  37740. sortedDirtyList = this._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  37741. }
  37742. sortedDirtyList.forEach(function (p) {
  37743. // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them.
  37744. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check.
  37745. if (!p.isDisposed && p._needPrepare()) {
  37746. p._prepareRender(context);
  37747. }
  37748. });
  37749. // Everything is updated, clear the dirty list
  37750. this._primDirtyList.splice(0);
  37751. }
  37752. }
  37753. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  37754. this._childrenRenderableGroups.forEach(function (g) {
  37755. g._prepareGroupRender(context);
  37756. });
  37757. };
  37758. Group2D.prototype._groupRender = function (context) {
  37759. var _this = this;
  37760. var engine = this.owner.engine;
  37761. var failedCount = 0;
  37762. // First recurse to children render group to render them (in their cache or on screen)
  37763. for (var _i = 0, _a = this._childrenRenderableGroups; _i < _a.length; _i++) {
  37764. var childGroup = _a[_i];
  37765. childGroup._groupRender(context);
  37766. }
  37767. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  37768. if (!this.isCachedGroup || this._cacheGroupDirty) {
  37769. if (this.isCachedGroup) {
  37770. this._bindCacheTarget();
  37771. }
  37772. else {
  37773. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  37774. }
  37775. // For each different model of primitive to render
  37776. var totalRenderCount = 0;
  37777. this._renderGroupInstancesInfo.forEach(function (k, v) {
  37778. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  37779. // Skip it if instanced arrays are not supported
  37780. if (_this.owner.supportInstancedArray) {
  37781. for (var i = 0; i < v._instancesPartsData.length; i++) {
  37782. // If the instances of the model was changed, pack the data
  37783. var array = v._instancesPartsData[i];
  37784. var instanceData_1 = array.pack();
  37785. totalRenderCount += array.usedElementCount;
  37786. // Compute the size the instance buffer should have
  37787. var neededSize = array.usedElementCount * array.stride * 4;
  37788. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  37789. if (!v._instancesPartsBuffer[i] || (v._instancesPartsBufferSize[i] < neededSize)) {
  37790. if (v._instancesPartsBuffer[i]) {
  37791. engine.deleteInstancesBuffer(v._instancesPartsBuffer[i]);
  37792. }
  37793. v._instancesPartsBuffer[i] = engine.createInstancesBuffer(neededSize);
  37794. v._instancesPartsBufferSize[i] = neededSize;
  37795. v._dirtyInstancesData = false;
  37796. // Update the WebGL buffer to match the new content of the instances data
  37797. engine._gl.bufferSubData(engine._gl.ARRAY_BUFFER, 0, instanceData_1);
  37798. }
  37799. else if (v._dirtyInstancesData) {
  37800. // Update the WebGL buffer to match the new content of the instances data
  37801. engine._gl.bindBuffer(engine._gl.ARRAY_BUFFER, v._instancesPartsBuffer[i]);
  37802. engine._gl.bufferSubData(engine._gl.ARRAY_BUFFER, 0, instanceData_1);
  37803. v._dirtyInstancesData = false;
  37804. }
  37805. }
  37806. }
  37807. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  37808. if (!_this.owner.supportInstancedArray || totalRenderCount > 0) {
  37809. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  37810. var renderFailed = !v._modelCache.render(v, context);
  37811. // Update dirty flag/related
  37812. v._dirtyInstancesData = renderFailed;
  37813. failedCount += renderFailed ? 1 : 0;
  37814. }
  37815. });
  37816. // The group's content is no longer dirty
  37817. this._cacheGroupDirty = failedCount !== 0;
  37818. if (this.isCachedGroup) {
  37819. this._unbindCacheTarget();
  37820. }
  37821. else {
  37822. if (curVP) {
  37823. engine.setViewport(curVP);
  37824. }
  37825. }
  37826. }
  37827. };
  37828. Group2D.prototype._bindCacheTarget = function () {
  37829. var curWidth;
  37830. var curHeight;
  37831. if (this._cacheNode) {
  37832. var size = this._cacheNode.contentSize;
  37833. var groupWidth = Math.ceil(this.actualSize.width);
  37834. var groupHeight = Math.ceil(this.actualSize.height);
  37835. if ((size.width < groupWidth) || (size.height < groupHeight)) {
  37836. curWidth = Math.floor(size.width * 1.07); // Grow 5% more to avoid frequent resizing for few pixels...
  37837. curHeight = Math.floor(size.height * 1.07);
  37838. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  37839. this._cacheTexture.freeRect(this._cacheNode);
  37840. this._cacheNode = null;
  37841. }
  37842. }
  37843. if (!this._cacheNode) {
  37844. // Check if we have to allocate a rendering zone in the global cache texture
  37845. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null);
  37846. this._cacheNode = res.node;
  37847. this._cacheTexture = res.texture;
  37848. this._cacheRenderSprite = res.sprite;
  37849. var size = this._cacheNode.contentSize;
  37850. }
  37851. var n = this._cacheNode;
  37852. this._cacheTexture.bindTextureForPosSize(n.pos, this.actualSize, true);
  37853. };
  37854. Group2D.prototype._unbindCacheTarget = function () {
  37855. if (this._cacheTexture) {
  37856. this._cacheTexture.unbindTexture();
  37857. }
  37858. };
  37859. Group2D.prototype.handleGroupChanged = function (prop) {
  37860. // This method is only for cachedGroup
  37861. if (!this.isCachedGroup || !this._cacheRenderSprite) {
  37862. return;
  37863. }
  37864. // For now we only support these property changes
  37865. // TODO: add more! :)
  37866. if (prop.id === BABYLON.Prim2DBase.positionProperty.id) {
  37867. this._cacheRenderSprite.position = this.position.clone();
  37868. }
  37869. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  37870. this._cacheRenderSprite.rotation = this.rotation;
  37871. }
  37872. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  37873. this._cacheRenderSprite.scale = this.scale;
  37874. }
  37875. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  37876. this._cacheRenderSprite.origin = this.origin.clone();
  37877. }
  37878. else if (prop.id === Group2D.actualSizeProperty.id) {
  37879. this._cacheRenderSprite.spriteSize = this.actualSize.clone();
  37880. }
  37881. };
  37882. Group2D.prototype.detectGroupStates = function () {
  37883. var isCanvas = this instanceof BABYLON.Canvas2D;
  37884. var canvasStrat = this.owner.cachingStrategy;
  37885. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  37886. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  37887. this._isRenderableGroup = isCanvas;
  37888. this._isCachedGroup = false;
  37889. }
  37890. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  37891. if (isCanvas) {
  37892. this._isRenderableGroup = true;
  37893. this._isCachedGroup = true;
  37894. }
  37895. else {
  37896. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  37897. this._isCachedGroup = false;
  37898. }
  37899. }
  37900. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  37901. if (isCanvas) {
  37902. this._isRenderableGroup = true;
  37903. this._isCachedGroup = false;
  37904. }
  37905. else {
  37906. if (this.hierarchyDepth === 1) {
  37907. this._isRenderableGroup = true;
  37908. this._isCachedGroup = true;
  37909. }
  37910. else {
  37911. this._isRenderableGroup = false;
  37912. this._isCachedGroup = false;
  37913. }
  37914. }
  37915. }
  37916. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  37917. var gcb = this.cacheBehavior;
  37918. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  37919. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  37920. this._isCachedGroup = false;
  37921. }
  37922. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  37923. this._isRenderableGroup = true;
  37924. this._isCachedGroup = true;
  37925. }
  37926. }
  37927. // If the group is tagged as renderable we add it to the renderable tree
  37928. if (this._isCachedGroup) {
  37929. var cur = this.parent;
  37930. while (cur) {
  37931. if (cur instanceof Group2D && cur._isRenderableGroup) {
  37932. cur._childrenRenderableGroups.push(this);
  37933. break;
  37934. }
  37935. cur = cur.parent;
  37936. }
  37937. }
  37938. };
  37939. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  37940. /**
  37941. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  37942. */
  37943. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  37944. /**
  37945. * When used, this group's content won't be cached, no matter which strategy used.
  37946. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  37947. */
  37948. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  37949. /**
  37950. * When used, the group's content will be cached in the nearest cached parent group/canvas
  37951. */
  37952. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  37953. __decorate([
  37954. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  37955. ], Group2D.prototype, "size", null);
  37956. __decorate([
  37957. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  37958. ], Group2D.prototype, "actualSize", null);
  37959. Group2D = __decorate([
  37960. BABYLON.className("Group2D")
  37961. ], Group2D);
  37962. return Group2D;
  37963. })(BABYLON.Prim2DBase);
  37964. BABYLON.Group2D = Group2D;
  37965. })(BABYLON || (BABYLON = {}));
  37966. var BABYLON;
  37967. (function (BABYLON) {
  37968. var Rectangle2DRenderCache = (function (_super) {
  37969. __extends(Rectangle2DRenderCache, _super);
  37970. function Rectangle2DRenderCache(engine, modelKey, isTransparent) {
  37971. _super.call(this, engine, modelKey, isTransparent);
  37972. }
  37973. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  37974. // Do nothing if the shader is still loading/preparing
  37975. if ((this.effectFill && !this.effectFill.isReady()) || (this.effectBorder && !this.effectBorder.isReady())) {
  37976. return false;
  37977. }
  37978. var engine = instanceInfo._owner.owner.engine;
  37979. var depthFunction = 0;
  37980. if (this.effectFill && this.effectBorder) {
  37981. depthFunction = engine.getDepthFunction();
  37982. engine.setDepthFunctionToLessOrEqual();
  37983. }
  37984. var cur;
  37985. if (this.isTransparent) {
  37986. cur = engine.getAlphaMode();
  37987. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  37988. }
  37989. if (this.effectFill) {
  37990. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  37991. engine.enableEffect(this.effectFill);
  37992. engine.bindBuffers(this.fillVB, this.fillIB, [1], 4, this.effectFill);
  37993. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  37994. if (instanceInfo._owner.owner.supportInstancedArray) {
  37995. if (!this.instancingFillAttributes) {
  37996. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  37997. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, this.effectFill);
  37998. }
  37999. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingFillAttributes);
  38000. engine.draw(true, 0, this.fillIndicesCount, count);
  38001. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingFillAttributes);
  38002. }
  38003. else {
  38004. for (var i = 0; i < count; i++) {
  38005. this.setupUniforms(this.effectFill, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  38006. engine.draw(true, 0, this.fillIndicesCount);
  38007. }
  38008. }
  38009. }
  38010. if (this.effectBorder) {
  38011. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  38012. engine.enableEffect(this.effectBorder);
  38013. engine.bindBuffers(this.borderVB, this.borderIB, [1], 4, this.effectBorder);
  38014. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  38015. if (instanceInfo._owner.owner.supportInstancedArray) {
  38016. if (!this.instancingBorderAttributes) {
  38017. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, this.effectBorder);
  38018. }
  38019. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingBorderAttributes);
  38020. engine.draw(true, 0, this.borderIndicesCount, count);
  38021. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingBorderAttributes);
  38022. }
  38023. else {
  38024. for (var i = 0; i < count; i++) {
  38025. this.setupUniforms(this.effectBorder, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  38026. engine.draw(true, 0, this.borderIndicesCount);
  38027. }
  38028. }
  38029. }
  38030. if (this.isTransparent) {
  38031. engine.setAlphaMode(cur);
  38032. }
  38033. if (this.effectFill && this.effectBorder) {
  38034. engine.setDepthFunction(depthFunction);
  38035. }
  38036. return true;
  38037. };
  38038. Rectangle2DRenderCache.prototype.dispose = function () {
  38039. if (!_super.prototype.dispose.call(this)) {
  38040. return false;
  38041. }
  38042. if (this.fillVB) {
  38043. this._engine._releaseBuffer(this.fillVB);
  38044. this.fillVB = null;
  38045. }
  38046. if (this.fillIB) {
  38047. this._engine._releaseBuffer(this.fillIB);
  38048. this.fillIB = null;
  38049. }
  38050. if (this.effectFill) {
  38051. this._engine._releaseEffect(this.effectFill);
  38052. this.effectFill = null;
  38053. }
  38054. if (this.borderVB) {
  38055. this._engine._releaseBuffer(this.borderVB);
  38056. this.borderVB = null;
  38057. }
  38058. if (this.borderIB) {
  38059. this._engine._releaseBuffer(this.borderIB);
  38060. this.borderIB = null;
  38061. }
  38062. if (this.effectBorder) {
  38063. this._engine._releaseEffect(this.effectBorder);
  38064. this.effectBorder = null;
  38065. }
  38066. return true;
  38067. };
  38068. return Rectangle2DRenderCache;
  38069. })(BABYLON.ModelRenderCache);
  38070. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  38071. var Rectangle2DInstanceData = (function (_super) {
  38072. __extends(Rectangle2DInstanceData, _super);
  38073. function Rectangle2DInstanceData(partId) {
  38074. _super.call(this, partId, 1);
  38075. }
  38076. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  38077. get: function () {
  38078. return null;
  38079. },
  38080. enumerable: true,
  38081. configurable: true
  38082. });
  38083. __decorate([
  38084. BABYLON.instanceData()
  38085. ], Rectangle2DInstanceData.prototype, "properties", null);
  38086. return Rectangle2DInstanceData;
  38087. })(BABYLON.Shape2DInstanceData);
  38088. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  38089. var Rectangle2D = (function (_super) {
  38090. __extends(Rectangle2D, _super);
  38091. function Rectangle2D() {
  38092. _super.apply(this, arguments);
  38093. }
  38094. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  38095. get: function () {
  38096. return this.size;
  38097. },
  38098. enumerable: true,
  38099. configurable: true
  38100. });
  38101. Object.defineProperty(Rectangle2D.prototype, "size", {
  38102. get: function () {
  38103. return this._size;
  38104. },
  38105. set: function (value) {
  38106. this._size = value;
  38107. },
  38108. enumerable: true,
  38109. configurable: true
  38110. });
  38111. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  38112. get: function () {
  38113. return this._notRounded;
  38114. },
  38115. set: function (value) {
  38116. this._notRounded = value;
  38117. },
  38118. enumerable: true,
  38119. configurable: true
  38120. });
  38121. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  38122. get: function () {
  38123. return this._roundRadius;
  38124. },
  38125. set: function (value) {
  38126. this._roundRadius = value;
  38127. this.notRounded = value === 0;
  38128. },
  38129. enumerable: true,
  38130. configurable: true
  38131. });
  38132. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  38133. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  38134. if (this.notRounded) {
  38135. return true;
  38136. }
  38137. // Well, for now we neglect the area where the pickPosition could be outside due to the roundRadius...
  38138. // TODO make REAL intersection test here!
  38139. return true;
  38140. };
  38141. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  38142. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo, this.origin);
  38143. };
  38144. Rectangle2D.prototype.setupRectangle2D = function (owner, parent, id, position, size, roundRadius, fill, border, borderThickness) {
  38145. if (roundRadius === void 0) { roundRadius = 0; }
  38146. if (borderThickness === void 0) { borderThickness = 1; }
  38147. this.setupShape2D(owner, parent, id, position, true, fill, border, borderThickness);
  38148. this.size = size;
  38149. this.notRounded = !roundRadius;
  38150. this.roundRadius = roundRadius;
  38151. };
  38152. Rectangle2D.Create = function (parent, id, x, y, width, height, fill, border) {
  38153. BABYLON.Prim2DBase.CheckParent(parent);
  38154. var rect = new Rectangle2D();
  38155. rect.setupRectangle2D(parent.owner, parent, id, new BABYLON.Vector2(x, y), new BABYLON.Size(width, height), null);
  38156. rect.fill = fill;
  38157. rect.border = border;
  38158. return rect;
  38159. };
  38160. Rectangle2D.CreateRounded = function (parent, id, x, y, width, height, roundRadius, fill, border) {
  38161. if (roundRadius === void 0) { roundRadius = 0; }
  38162. BABYLON.Prim2DBase.CheckParent(parent);
  38163. var rect = new Rectangle2D();
  38164. rect.setupRectangle2D(parent.owner, parent, id, new BABYLON.Vector2(x, y), new BABYLON.Size(width, height), roundRadius);
  38165. rect.fill = fill || BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF");
  38166. rect.border = border;
  38167. return rect;
  38168. };
  38169. Rectangle2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  38170. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey, isTransparent);
  38171. return renderCache;
  38172. };
  38173. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  38174. var renderCache = modelRenderCache;
  38175. var engine = this.owner.engine;
  38176. // Need to create WebGL resources for fill part?
  38177. if (this.fill) {
  38178. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  38179. var vb = new Float32Array(vbSize);
  38180. for (var i = 0; i < vbSize; i++) {
  38181. vb[i] = i;
  38182. }
  38183. renderCache.fillVB = engine.createVertexBuffer(vb);
  38184. var triCount = vbSize - 1;
  38185. var ib = new Float32Array(triCount * 3);
  38186. for (var i = 0; i < triCount; i++) {
  38187. ib[i * 3 + 0] = 0;
  38188. ib[i * 3 + 2] = i + 1;
  38189. ib[i * 3 + 1] = i + 2;
  38190. }
  38191. ib[triCount * 3 - 2] = 1;
  38192. renderCache.fillIB = engine.createIndexBuffer(ib);
  38193. renderCache.fillIndicesCount = triCount * 3;
  38194. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"]);
  38195. renderCache.effectFill = engine.createEffect({ vertex: "rect2d", fragment: "rect2d" }, ei.attributes, ei.uniforms, [], ei.defines, null, function (e) {
  38196. // renderCache.setupUniformsLocation(e, ei.uniforms, Shape2D.SHAPE2D_FILLPARTID);
  38197. });
  38198. }
  38199. // Need to create WebGL resource for border part?
  38200. if (this.border) {
  38201. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  38202. var vb = new Float32Array(vbSize);
  38203. for (var i = 0; i < vbSize; i++) {
  38204. vb[i] = i;
  38205. }
  38206. renderCache.borderVB = engine.createVertexBuffer(vb);
  38207. var triCount = vbSize;
  38208. var rs = triCount / 2;
  38209. var ib = new Float32Array(triCount * 3);
  38210. for (var i = 0; i < rs; i++) {
  38211. var r0 = i;
  38212. var r1 = (i + 1) % rs;
  38213. ib[i * 6 + 0] = rs + r1;
  38214. ib[i * 6 + 1] = rs + r0;
  38215. ib[i * 6 + 2] = r0;
  38216. ib[i * 6 + 3] = r1;
  38217. ib[i * 6 + 4] = rs + r1;
  38218. ib[i * 6 + 5] = r0;
  38219. }
  38220. renderCache.borderIB = engine.createIndexBuffer(ib);
  38221. renderCache.borderIndicesCount = triCount * 3;
  38222. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"]);
  38223. renderCache.effectBorder = engine.createEffect({ vertex: "rect2d", fragment: "rect2d" }, ei.attributes, ei.uniforms, [], ei.defines, null, function (e) {
  38224. // renderCache.setupUniformsLocation(e, ei.uniforms, Shape2D.SHAPE2D_BORDERPARTID);
  38225. });
  38226. }
  38227. return renderCache;
  38228. };
  38229. Rectangle2D.prototype.createInstanceDataParts = function () {
  38230. var res = new Array();
  38231. if (this.border) {
  38232. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  38233. }
  38234. if (this.fill) {
  38235. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  38236. }
  38237. return res;
  38238. };
  38239. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  38240. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  38241. return false;
  38242. }
  38243. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  38244. var d = part;
  38245. var size = this.size;
  38246. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  38247. }
  38248. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  38249. var d = part;
  38250. var size = this.size;
  38251. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  38252. }
  38253. return true;
  38254. };
  38255. Rectangle2D.roundSubdivisions = 16;
  38256. __decorate([
  38257. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.sizeProperty = pi; }, false, true)
  38258. ], Rectangle2D.prototype, "size", null);
  38259. __decorate([
  38260. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  38261. ], Rectangle2D.prototype, "notRounded", null);
  38262. __decorate([
  38263. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  38264. ], Rectangle2D.prototype, "roundRadius", null);
  38265. Rectangle2D = __decorate([
  38266. BABYLON.className("Rectangle2D")
  38267. ], Rectangle2D);
  38268. return Rectangle2D;
  38269. })(BABYLON.Shape2D);
  38270. BABYLON.Rectangle2D = Rectangle2D;
  38271. })(BABYLON || (BABYLON = {}));
  38272. var BABYLON;
  38273. (function (BABYLON) {
  38274. var Sprite2DRenderCache = (function (_super) {
  38275. __extends(Sprite2DRenderCache, _super);
  38276. function Sprite2DRenderCache() {
  38277. _super.apply(this, arguments);
  38278. }
  38279. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  38280. // Do nothing if the shader is still loading/preparing
  38281. if (!this.effect.isReady() || !this.texture.isReady()) {
  38282. return false;
  38283. }
  38284. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  38285. var engine = instanceInfo._owner.owner.engine;
  38286. engine.enableEffect(this.effect);
  38287. this.effect.setTexture("diffuseSampler", this.texture);
  38288. engine.bindBuffers(this.vb, this.ib, [1], 4, this.effect);
  38289. var cur = engine.getAlphaMode();
  38290. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38291. var count = instanceInfo._instancesPartsData[0].usedElementCount;
  38292. if (instanceInfo._owner.owner.supportInstancedArray) {
  38293. if (!this.instancingAttributes) {
  38294. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, this.effect);
  38295. }
  38296. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], null, this.instancingAttributes);
  38297. engine.draw(true, 0, 6, count);
  38298. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], this.instancingAttributes);
  38299. }
  38300. else {
  38301. for (var i = 0; i < count; i++) {
  38302. this.setupUniforms(this.effect, 0, instanceInfo._instancesPartsData[0], i);
  38303. engine.draw(true, 0, 6);
  38304. }
  38305. }
  38306. engine.setAlphaMode(cur);
  38307. return true;
  38308. };
  38309. Sprite2DRenderCache.prototype.dispose = function () {
  38310. if (!_super.prototype.dispose.call(this)) {
  38311. return false;
  38312. }
  38313. if (this.vb) {
  38314. this._engine._releaseBuffer(this.vb);
  38315. this.vb = null;
  38316. }
  38317. if (this.ib) {
  38318. this._engine._releaseBuffer(this.ib);
  38319. this.ib = null;
  38320. }
  38321. if (this.texture) {
  38322. this.texture.dispose();
  38323. this.texture = null;
  38324. }
  38325. if (this.effect) {
  38326. this._engine._releaseEffect(this.effect);
  38327. this.effect = null;
  38328. }
  38329. return true;
  38330. };
  38331. return Sprite2DRenderCache;
  38332. })(BABYLON.ModelRenderCache);
  38333. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  38334. var Sprite2DInstanceData = (function (_super) {
  38335. __extends(Sprite2DInstanceData, _super);
  38336. function Sprite2DInstanceData(partId) {
  38337. _super.call(this, partId, 1);
  38338. }
  38339. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  38340. get: function () {
  38341. return null;
  38342. },
  38343. enumerable: true,
  38344. configurable: true
  38345. });
  38346. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  38347. get: function () {
  38348. return null;
  38349. },
  38350. enumerable: true,
  38351. configurable: true
  38352. });
  38353. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  38354. get: function () {
  38355. return null;
  38356. },
  38357. enumerable: true,
  38358. configurable: true
  38359. });
  38360. Object.defineProperty(Sprite2DInstanceData.prototype, "frame", {
  38361. get: function () {
  38362. return null;
  38363. },
  38364. enumerable: true,
  38365. configurable: true
  38366. });
  38367. Object.defineProperty(Sprite2DInstanceData.prototype, "invertY", {
  38368. get: function () {
  38369. return null;
  38370. },
  38371. enumerable: true,
  38372. configurable: true
  38373. });
  38374. __decorate([
  38375. BABYLON.instanceData()
  38376. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  38377. __decorate([
  38378. BABYLON.instanceData()
  38379. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  38380. __decorate([
  38381. BABYLON.instanceData()
  38382. ], Sprite2DInstanceData.prototype, "textureSize", null);
  38383. __decorate([
  38384. BABYLON.instanceData()
  38385. ], Sprite2DInstanceData.prototype, "frame", null);
  38386. __decorate([
  38387. BABYLON.instanceData()
  38388. ], Sprite2DInstanceData.prototype, "invertY", null);
  38389. return Sprite2DInstanceData;
  38390. })(BABYLON.InstanceDataBase);
  38391. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  38392. var Sprite2D = (function (_super) {
  38393. __extends(Sprite2D, _super);
  38394. function Sprite2D() {
  38395. _super.apply(this, arguments);
  38396. }
  38397. Object.defineProperty(Sprite2D.prototype, "texture", {
  38398. get: function () {
  38399. return this._texture;
  38400. },
  38401. set: function (value) {
  38402. this._texture = value;
  38403. },
  38404. enumerable: true,
  38405. configurable: true
  38406. });
  38407. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  38408. get: function () {
  38409. return this.spriteSize;
  38410. },
  38411. enumerable: true,
  38412. configurable: true
  38413. });
  38414. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  38415. get: function () {
  38416. return this._size;
  38417. },
  38418. set: function (value) {
  38419. this._size = value;
  38420. },
  38421. enumerable: true,
  38422. configurable: true
  38423. });
  38424. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  38425. get: function () {
  38426. return this._location;
  38427. },
  38428. set: function (value) {
  38429. this._location = value;
  38430. },
  38431. enumerable: true,
  38432. configurable: true
  38433. });
  38434. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  38435. get: function () {
  38436. return this._spriteFrame;
  38437. },
  38438. set: function (value) {
  38439. this._spriteFrame = value;
  38440. },
  38441. enumerable: true,
  38442. configurable: true
  38443. });
  38444. Object.defineProperty(Sprite2D.prototype, "invertY", {
  38445. get: function () {
  38446. return this._invertY;
  38447. },
  38448. set: function (value) {
  38449. this._invertY = value;
  38450. },
  38451. enumerable: true,
  38452. configurable: true
  38453. });
  38454. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  38455. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.spriteSize, this._levelBoundingInfo, this.origin);
  38456. };
  38457. Sprite2D.prototype.setupSprite2D = function (owner, parent, id, position, texture, spriteSize, spriteLocation, invertY) {
  38458. this.setupRenderablePrim2D(owner, parent, id, position, true);
  38459. this.texture = texture;
  38460. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38461. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38462. this.spriteSize = spriteSize;
  38463. this.spriteLocation = spriteLocation;
  38464. this.spriteFrame = 0;
  38465. this.invertY = invertY;
  38466. this._isTransparent = true;
  38467. };
  38468. Sprite2D.Create = function (parent, id, x, y, texture, spriteSize, spriteLocation, invertY) {
  38469. if (invertY === void 0) { invertY = false; }
  38470. BABYLON.Prim2DBase.CheckParent(parent);
  38471. var sprite = new Sprite2D();
  38472. sprite.setupSprite2D(parent.owner, parent, id, new BABYLON.Vector2(x, y), texture, spriteSize, spriteLocation, invertY);
  38473. return sprite;
  38474. };
  38475. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  38476. var sprite = new Sprite2D();
  38477. sprite.setupSprite2D(owner, null, "__cachedCanvasSprite__", new BABYLON.Vector2(0, 0), texture, size, pos, false);
  38478. return sprite;
  38479. };
  38480. Sprite2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  38481. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey, isTransparent);
  38482. return renderCache;
  38483. };
  38484. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  38485. var renderCache = modelRenderCache;
  38486. var engine = this.owner.engine;
  38487. var vb = new Float32Array(4);
  38488. for (var i = 0; i < 4; i++) {
  38489. vb[i] = i;
  38490. }
  38491. renderCache.vb = engine.createVertexBuffer(vb);
  38492. var ib = new Float32Array(6);
  38493. ib[0] = 0;
  38494. ib[1] = 2;
  38495. ib[2] = 1;
  38496. ib[3] = 0;
  38497. ib[4] = 3;
  38498. ib[5] = 2;
  38499. renderCache.ib = engine.createIndexBuffer(ib);
  38500. renderCache.texture = this.texture;
  38501. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"]);
  38502. renderCache.effect = engine.createEffect({ vertex: "sprite2d", fragment: "sprite2d" }, ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null, function (e) {
  38503. // renderCache.setupUniformsLocation(e, ei.uniforms, Sprite2D.SPRITE2D_MAINPARTID);
  38504. });
  38505. return renderCache;
  38506. };
  38507. Sprite2D.prototype.createInstanceDataParts = function () {
  38508. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  38509. };
  38510. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  38511. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  38512. return false;
  38513. }
  38514. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  38515. var d = this._instanceDataParts[0];
  38516. var ts = this.texture.getSize();
  38517. var sl = this.spriteLocation;
  38518. var ss = this.spriteSize;
  38519. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  38520. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  38521. d.sizeUV = suv;
  38522. d.frame = this.spriteFrame;
  38523. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  38524. d.invertY = this.invertY ? 1 : 0;
  38525. }
  38526. return true;
  38527. };
  38528. Sprite2D.SPRITE2D_MAINPARTID = 1;
  38529. __decorate([
  38530. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  38531. ], Sprite2D.prototype, "texture", null);
  38532. __decorate([
  38533. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.spriteSizeProperty = pi; }, false, true)
  38534. ], Sprite2D.prototype, "spriteSize", null);
  38535. __decorate([
  38536. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  38537. ], Sprite2D.prototype, "spriteLocation", null);
  38538. __decorate([
  38539. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  38540. ], Sprite2D.prototype, "spriteFrame", null);
  38541. __decorate([
  38542. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  38543. ], Sprite2D.prototype, "invertY", null);
  38544. Sprite2D = __decorate([
  38545. BABYLON.className("Sprite2D")
  38546. ], Sprite2D);
  38547. return Sprite2D;
  38548. })(BABYLON.RenderablePrim2D);
  38549. BABYLON.Sprite2D = Sprite2D;
  38550. })(BABYLON || (BABYLON = {}));
  38551. var BABYLON;
  38552. (function (BABYLON) {
  38553. var Text2DRenderCache = (function (_super) {
  38554. __extends(Text2DRenderCache, _super);
  38555. function Text2DRenderCache() {
  38556. _super.apply(this, arguments);
  38557. }
  38558. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  38559. // Do nothing if the shader is still loading/preparing
  38560. if (!this.effect.isReady() || !this.fontTexture.isReady()) {
  38561. return false;
  38562. }
  38563. // Compute the offset locations of the attributes in the vertexshader that will be mapped to the instance buffer data
  38564. if (!this.instancingAttributes) {
  38565. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, this.effect);
  38566. }
  38567. var engine = instanceInfo._owner.owner.engine;
  38568. this.fontTexture.update();
  38569. engine.enableEffect(this.effect);
  38570. this.effect.setTexture("diffuseSampler", this.fontTexture);
  38571. engine.bindBuffers(this.vb, this.ib, [1], 4, this.effect);
  38572. var cur = engine.getAlphaMode();
  38573. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38574. var count = instanceInfo._instancesPartsData[0].usedElementCount;
  38575. if (instanceInfo._owner.owner.supportInstancedArray) {
  38576. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], null, this.instancingAttributes);
  38577. engine.draw(true, 0, 6, count);
  38578. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], this.instancingAttributes);
  38579. }
  38580. else {
  38581. for (var i = 0; i < count; i++) {
  38582. this.setupUniforms(this.effect, 0, instanceInfo._instancesPartsData[0], i);
  38583. engine.draw(true, 0, 6);
  38584. }
  38585. }
  38586. engine.setAlphaMode(cur);
  38587. return true;
  38588. };
  38589. Text2DRenderCache.prototype.dispose = function () {
  38590. if (!_super.prototype.dispose.call(this)) {
  38591. return false;
  38592. }
  38593. if (this.vb) {
  38594. this._engine._releaseBuffer(this.vb);
  38595. this.vb = null;
  38596. }
  38597. if (this.ib) {
  38598. this._engine._releaseBuffer(this.ib);
  38599. this.ib = null;
  38600. }
  38601. if (this.fontTexture) {
  38602. this.fontTexture.dispose();
  38603. this.fontTexture = null;
  38604. }
  38605. if (this.effect) {
  38606. this._engine._releaseEffect(this.effect);
  38607. this.effect = null;
  38608. }
  38609. return true;
  38610. };
  38611. return Text2DRenderCache;
  38612. })(BABYLON.ModelRenderCache);
  38613. BABYLON.Text2DRenderCache = Text2DRenderCache;
  38614. var Text2DInstanceData = (function (_super) {
  38615. __extends(Text2DInstanceData, _super);
  38616. function Text2DInstanceData(partId, dataElementCount) {
  38617. _super.call(this, partId, dataElementCount);
  38618. }
  38619. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  38620. get: function () {
  38621. return null;
  38622. },
  38623. enumerable: true,
  38624. configurable: true
  38625. });
  38626. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  38627. get: function () {
  38628. return null;
  38629. },
  38630. enumerable: true,
  38631. configurable: true
  38632. });
  38633. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  38634. get: function () {
  38635. return null;
  38636. },
  38637. enumerable: true,
  38638. configurable: true
  38639. });
  38640. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  38641. get: function () {
  38642. return null;
  38643. },
  38644. enumerable: true,
  38645. configurable: true
  38646. });
  38647. __decorate([
  38648. BABYLON.instanceData()
  38649. ], Text2DInstanceData.prototype, "topLeftUV", null);
  38650. __decorate([
  38651. BABYLON.instanceData()
  38652. ], Text2DInstanceData.prototype, "sizeUV", null);
  38653. __decorate([
  38654. BABYLON.instanceData()
  38655. ], Text2DInstanceData.prototype, "textureSize", null);
  38656. __decorate([
  38657. BABYLON.instanceData()
  38658. ], Text2DInstanceData.prototype, "color", null);
  38659. return Text2DInstanceData;
  38660. })(BABYLON.InstanceDataBase);
  38661. BABYLON.Text2DInstanceData = Text2DInstanceData;
  38662. var Text2D = (function (_super) {
  38663. __extends(Text2D, _super);
  38664. function Text2D() {
  38665. _super.apply(this, arguments);
  38666. }
  38667. Object.defineProperty(Text2D.prototype, "fontName", {
  38668. get: function () {
  38669. return this._fontName;
  38670. },
  38671. set: function (value) {
  38672. if (this._fontName) {
  38673. throw new Error("Font Name change is not supported right now.");
  38674. }
  38675. this._fontName = value;
  38676. },
  38677. enumerable: true,
  38678. configurable: true
  38679. });
  38680. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  38681. get: function () {
  38682. return this._defaultFontColor;
  38683. },
  38684. set: function (value) {
  38685. this._defaultFontColor = value;
  38686. },
  38687. enumerable: true,
  38688. configurable: true
  38689. });
  38690. Object.defineProperty(Text2D.prototype, "text", {
  38691. get: function () {
  38692. return this._text;
  38693. },
  38694. set: function (value) {
  38695. this._text = value;
  38696. this._actualSize = null; // A change of text will reset the Actual Area Size which will be recomputed next time it's used
  38697. this._updateCharCount();
  38698. },
  38699. enumerable: true,
  38700. configurable: true
  38701. });
  38702. Object.defineProperty(Text2D.prototype, "areaSize", {
  38703. get: function () {
  38704. return this._areaSize;
  38705. },
  38706. set: function (value) {
  38707. this._areaSize = value;
  38708. },
  38709. enumerable: true,
  38710. configurable: true
  38711. });
  38712. Object.defineProperty(Text2D.prototype, "vAlign", {
  38713. get: function () {
  38714. return this._vAlign;
  38715. },
  38716. set: function (value) {
  38717. this._vAlign = value;
  38718. },
  38719. enumerable: true,
  38720. configurable: true
  38721. });
  38722. Object.defineProperty(Text2D.prototype, "hAlign", {
  38723. get: function () {
  38724. return this._hAlign;
  38725. },
  38726. set: function (value) {
  38727. this._hAlign = value;
  38728. },
  38729. enumerable: true,
  38730. configurable: true
  38731. });
  38732. Object.defineProperty(Text2D.prototype, "actualSize", {
  38733. get: function () {
  38734. if (this.areaSize) {
  38735. return this.areaSize;
  38736. }
  38737. if (this._actualSize) {
  38738. return this._actualSize;
  38739. }
  38740. this._actualSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  38741. return this._actualSize;
  38742. },
  38743. enumerable: true,
  38744. configurable: true
  38745. });
  38746. Object.defineProperty(Text2D.prototype, "fontTexture", {
  38747. get: function () {
  38748. if (this._fontTexture) {
  38749. return this._fontTexture;
  38750. }
  38751. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName);
  38752. return this._fontTexture;
  38753. },
  38754. enumerable: true,
  38755. configurable: true
  38756. });
  38757. Text2D.prototype.dispose = function () {
  38758. if (!_super.prototype.dispose.call(this)) {
  38759. return false;
  38760. }
  38761. if (this._fontTexture) {
  38762. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName);
  38763. this._fontTexture = null;
  38764. }
  38765. return true;
  38766. };
  38767. Text2D.prototype.updateLevelBoundingInfo = function () {
  38768. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo, this.origin);
  38769. };
  38770. Text2D.prototype.setupText2D = function (owner, parent, id, position, fontName, text, areaSize, defaultFontColor, vAlign, hAlign, tabulationSize) {
  38771. this.setupRenderablePrim2D(owner, parent, id, position, true);
  38772. this.fontName = fontName;
  38773. this.defaultFontColor = defaultFontColor;
  38774. this.text = text;
  38775. this.areaSize = areaSize;
  38776. this.vAlign = vAlign;
  38777. this.hAlign = hAlign;
  38778. this._tabulationSize = tabulationSize;
  38779. this._isTransparent = true;
  38780. this.origin = BABYLON.Vector2.Zero();
  38781. };
  38782. Text2D.Create = function (parent, id, x, y, fontName, text, defaultFontColor, areaSize, vAlign, hAlign, tabulationSize) {
  38783. if (vAlign === void 0) { vAlign = Text2D.TEXT2D_VALIGN_TOP; }
  38784. if (hAlign === void 0) { hAlign = Text2D.TEXT2D_HALIGN_LEFT; }
  38785. if (tabulationSize === void 0) { tabulationSize = 4; }
  38786. BABYLON.Prim2DBase.CheckParent(parent);
  38787. var text2d = new Text2D();
  38788. text2d.setupText2D(parent.owner, parent, id, new BABYLON.Vector2(x, y), fontName, text, areaSize, defaultFontColor || new BABYLON.Color4(0, 0, 0, 1), vAlign, hAlign, tabulationSize);
  38789. return text2d;
  38790. };
  38791. Text2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  38792. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey, isTransparent);
  38793. return renderCache;
  38794. };
  38795. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  38796. var renderCache = modelRenderCache;
  38797. var engine = this.owner.engine;
  38798. renderCache.fontTexture = this.fontTexture;
  38799. var vb = new Float32Array(4);
  38800. for (var i = 0; i < 4; i++) {
  38801. vb[i] = i;
  38802. }
  38803. renderCache.vb = engine.createVertexBuffer(vb);
  38804. var ib = new Float32Array(6);
  38805. ib[0] = 0;
  38806. ib[1] = 2;
  38807. ib[2] = 1;
  38808. ib[3] = 0;
  38809. ib[4] = 3;
  38810. ib[5] = 2;
  38811. renderCache.ib = engine.createIndexBuffer(ib);
  38812. // Effects
  38813. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"]);
  38814. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null, function (e) {
  38815. // renderCache.setupUniformsLocation(e, ei.uniforms, Text2D.TEXT2D_MAINPARTID);
  38816. });
  38817. return renderCache;
  38818. };
  38819. Text2D.prototype.createInstanceDataParts = function () {
  38820. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  38821. };
  38822. // Looks like a hack!? Yes! Because that's what it is!
  38823. // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
  38824. // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
  38825. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  38826. if (!this._charCount) {
  38827. var curText = this._text;
  38828. this.text = "A";
  38829. return curText;
  38830. }
  38831. };
  38832. // if obj contains something, we restore the _text property
  38833. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  38834. if (obj !== undefined) {
  38835. this.text = obj;
  38836. }
  38837. };
  38838. Text2D.prototype.refreshInstanceDataPart = function (part) {
  38839. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  38840. return false;
  38841. }
  38842. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  38843. var d = part;
  38844. var texture = this.fontTexture;
  38845. var ts = texture.getSize();
  38846. var textSize = texture.measureText(this.text, this._tabulationSize);
  38847. var offset = BABYLON.Vector2.Zero();
  38848. var charxpos = 0;
  38849. d.dataElementCount = this._charCount;
  38850. d.curElement = 0;
  38851. var customOrigin = BABYLON.Vector2.Zero();
  38852. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  38853. var char = _a[_i];
  38854. // Line feed
  38855. if (char === "\n") {
  38856. offset.x = 0;
  38857. offset.y -= texture.lineHeight;
  38858. }
  38859. // Tabulation ?
  38860. if (char === "\t") {
  38861. var nextPos = charxpos + this._tabulationSize;
  38862. nextPos = nextPos - (nextPos % this._tabulationSize);
  38863. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  38864. charxpos = nextPos;
  38865. continue;
  38866. }
  38867. if (char < " ") {
  38868. continue;
  38869. }
  38870. this.updateInstanceDataPart(d, offset, textSize);
  38871. var ci = texture.getChar(char);
  38872. offset.x += ci.charWidth;
  38873. d.topLeftUV = ci.topLeftUV;
  38874. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  38875. d.sizeUV = suv;
  38876. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  38877. d.color = this.defaultFontColor;
  38878. ++d.curElement;
  38879. }
  38880. }
  38881. return true;
  38882. };
  38883. Text2D.prototype._updateCharCount = function () {
  38884. var count = 0;
  38885. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  38886. var char = _a[_i];
  38887. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  38888. continue;
  38889. }
  38890. ++count;
  38891. }
  38892. this._charCount = count;
  38893. };
  38894. Text2D.TEXT2D_MAINPARTID = 1;
  38895. Text2D.TEXT2D_VALIGN_TOP = 1;
  38896. Text2D.TEXT2D_VALIGN_CENTER = 2;
  38897. Text2D.TEXT2D_VALIGN_BOTTOM = 3;
  38898. Text2D.TEXT2D_HALIGN_LEFT = 1;
  38899. Text2D.TEXT2D_HALIGN_CENTER = 2;
  38900. Text2D.TEXT2D_HALIGN_RIGHT = 3;
  38901. __decorate([
  38902. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  38903. ], Text2D.prototype, "fontName", null);
  38904. __decorate([
  38905. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  38906. ], Text2D.prototype, "defaultFontColor", null);
  38907. __decorate([
  38908. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  38909. ], Text2D.prototype, "text", null);
  38910. __decorate([
  38911. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.areaSizeProperty = pi; })
  38912. ], Text2D.prototype, "areaSize", null);
  38913. __decorate([
  38914. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D.vAlignProperty = pi; })
  38915. ], Text2D.prototype, "vAlign", null);
  38916. __decorate([
  38917. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D.hAlignProperty = pi; })
  38918. ], Text2D.prototype, "hAlign", null);
  38919. Text2D = __decorate([
  38920. BABYLON.className("Text2D")
  38921. ], Text2D);
  38922. return Text2D;
  38923. })(BABYLON.RenderablePrim2D);
  38924. BABYLON.Text2D = Text2D;
  38925. })(BABYLON || (BABYLON = {}));
  38926. var BABYLON;
  38927. (function (BABYLON) {
  38928. var Canvas2DEngineBoundData = (function () {
  38929. function Canvas2DEngineBoundData() {
  38930. this._modelCache = new BABYLON.StringDictionary();
  38931. }
  38932. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  38933. return this._modelCache.getOrAddWithFactory(key, factory);
  38934. };
  38935. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  38936. if (!modelRenderCache.isDisposed) {
  38937. return false;
  38938. }
  38939. this._modelCache.remove(modelRenderCache.modelKey);
  38940. return true;
  38941. };
  38942. return Canvas2DEngineBoundData;
  38943. })();
  38944. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  38945. var Canvas2D = (function (_super) {
  38946. __extends(Canvas2D, _super);
  38947. function Canvas2D() {
  38948. _super.apply(this, arguments);
  38949. this._notifDebugMode = false;
  38950. this._mapCounter = 0;
  38951. }
  38952. /**
  38953. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the top/left corner of the screen.
  38954. * ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI.
  38955. * All caching strategies will be available.
  38956. * PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5]
  38957. * @param scene the Scene that owns the Canvas
  38958. * @param name the name of the Canvas, for information purpose only
  38959. * @param pos the position of the canvas, relative from the bottom/left of the scene's viewport
  38960. * @param size the Size of the canvas. If null two behaviors depend on the cachingStrategy: if it's CACHESTRATEGY_CACHECANVAS then it will always auto-fit the rendering device, in all the other modes it will fit the content of the Canvas
  38961. * @param cachingStrategy either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information.
  38962. */
  38963. Canvas2D.CreateScreenSpace = function (scene, name, pos, size, cachingStrategy, enableInteraction) {
  38964. if (cachingStrategy === void 0) { cachingStrategy = Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS; }
  38965. if (enableInteraction === void 0) { enableInteraction = true; }
  38966. var c = new Canvas2D();
  38967. c.setupCanvas(scene, name, size, true, cachingStrategy, enableInteraction);
  38968. c.position = pos;
  38969. c.origin = BABYLON.Vector2.Zero();
  38970. return c;
  38971. };
  38972. /**
  38973. * Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space.
  38974. * This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon.
  38975. * @param scene the Scene that owns the Canvas
  38976. * @param name the name of the Canvas, for information purpose only
  38977. * @param position the position of the Canvas in World Space
  38978. * @param rotation the rotation of the Canvas in World Space
  38979. * @param size the dimension of the Canvas in World Space
  38980. * @param renderScaleFactor A scale factor applied to create the rendering texture that will be mapped in the Scene Rectangle. If you set 2 for instance the texture will be twice large in width and height. A greater value will allow to achieve a better rendering quality.
  38981. * BE AWARE that the Canvas true dimension will be size*renderScaleFactor, then all coordinates and size will have to be express regarding this size.
  38982. * TIPS: if you want a renderScaleFactor independent reference of frame, create a child Group2D in the Canvas with position 0,0 and size set to null, then set its scale property to the same amount than the renderScaleFactor, put all your primitive inside using coordinates regarding the size property you pick for the Canvas and you'll be fine.
  38983. * @param sideOrientation Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one.
  38984. * @param cachingStrategy Must be CACHESTRATEGY_CANVAS for now
  38985. */
  38986. Canvas2D.CreateWorldSpace = function (scene, name, position, rotation, size, renderScaleFactor, sideOrientation, cachingStrategy, enableInteraction) {
  38987. if (renderScaleFactor === void 0) { renderScaleFactor = 1; }
  38988. if (cachingStrategy === void 0) { cachingStrategy = Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS; }
  38989. if (enableInteraction === void 0) { enableInteraction = true; }
  38990. if (cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  38991. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  38992. }
  38993. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  38994. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  38995. //}
  38996. if (!sideOrientation) {
  38997. sideOrientation = BABYLON.Mesh.DEFAULTSIDE;
  38998. }
  38999. var c = new Canvas2D();
  39000. c.setupCanvas(scene, name, new BABYLON.Size(size.width * renderScaleFactor, size.height * renderScaleFactor), false, cachingStrategy, enableInteraction);
  39001. var plane = new BABYLON.WorldSpaceCanvas2d(name, scene, c);
  39002. var vertexData = BABYLON.VertexData.CreatePlane({ width: size.width / 2, height: size.height / 2, sideOrientation: sideOrientation });
  39003. var mtl = new BABYLON.StandardMaterial(name + "_Material", scene);
  39004. c.applyCachedTexture(vertexData, mtl);
  39005. vertexData.applyToMesh(plane, false);
  39006. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  39007. mtl.disableLighting = true;
  39008. mtl.useAlphaFromDiffuseTexture = true;
  39009. plane.position = position;
  39010. plane.rotationQuaternion = rotation;
  39011. plane.material = mtl;
  39012. c._worldSpaceNode = plane;
  39013. return c;
  39014. };
  39015. Canvas2D.prototype.setupCanvas = function (scene, name, size, isScreenSpace, cachingstrategy, enableInteraction) {
  39016. var _this = this;
  39017. var engine = scene.getEngine();
  39018. this._fitRenderingDevice = !size;
  39019. if (!size) {
  39020. size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  39021. }
  39022. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  39023. this._cachingStrategy = cachingstrategy;
  39024. this._depthLevel = 0;
  39025. this._hierarchyMaxDepth = 100;
  39026. this._hierarchyLevelZFactor = 1 / this._hierarchyMaxDepth;
  39027. this._hierarchyLevelMaxSiblingCount = 1000;
  39028. this._hierarchySiblingZDelta = this._hierarchyLevelZFactor / this._hierarchyLevelMaxSiblingCount;
  39029. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  39030. this._capturedPointers = new BABYLON.StringDictionary();
  39031. this.setupGroup2D(this, null, name, BABYLON.Vector2.Zero(), size, this._cachingStrategy === Canvas2D.CACHESTRATEGY_ALLGROUPS ? BABYLON.Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE : BABYLON.Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY);
  39032. this._scene = scene;
  39033. this._engine = engine;
  39034. this._renderingSize = new BABYLON.Size(0, 0);
  39035. // Register scene dispose to also dispose the canvas when it'll happens
  39036. scene.onDisposeObservable.add(function (d, s) {
  39037. _this.dispose();
  39038. });
  39039. if (cachingstrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  39040. this._background = BABYLON.Rectangle2D.Create(this, "###CANVAS BACKGROUND###", 0, 0, size.width, size.height);
  39041. this._background.isPickable = false;
  39042. this._background.origin = BABYLON.Vector2.Zero();
  39043. this._background.levelVisible = false;
  39044. }
  39045. this._isScreeSpace = isScreenSpace;
  39046. if (this._isScreeSpace) {
  39047. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  39048. _this._engine.clear(null, false, true);
  39049. _this._render();
  39050. });
  39051. }
  39052. else {
  39053. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  39054. _this._render();
  39055. });
  39056. }
  39057. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  39058. // this._supprtInstancedArray = false; // TODO REMOVE!!!
  39059. this._setupInteraction(enableInteraction);
  39060. };
  39061. Canvas2D.prototype._setupInteraction = function (enable) {
  39062. var _this = this;
  39063. // No change detection
  39064. if (enable === this._interactionEnabled) {
  39065. return;
  39066. }
  39067. // Set the new state
  39068. this._interactionEnabled = enable;
  39069. // Disable interaction
  39070. if (!enable) {
  39071. if (this._scenePrePointerObserver) {
  39072. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  39073. this._scenePrePointerObserver = null;
  39074. }
  39075. return;
  39076. }
  39077. // Enable Interaction
  39078. // Register the observable
  39079. this.scene.onPrePointerObservable.add(function (e, s) { return _this._handlePointerEventForInteraction(e, s); });
  39080. };
  39081. /**
  39082. * Internal method, you should use the Prim2DBase version instead
  39083. */
  39084. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  39085. if (this.isPointerCaptured(pointerId)) {
  39086. return false;
  39087. }
  39088. // Try to capture the pointer on the HTML side
  39089. try {
  39090. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  39091. }
  39092. catch (e) {
  39093. }
  39094. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  39095. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture);
  39096. this._capturedPointers.add(pointerId.toString(), primitive);
  39097. return true;
  39098. };
  39099. /**
  39100. * Internal method, you should use the Prim2DBase version instead
  39101. */
  39102. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  39103. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  39104. return false;
  39105. }
  39106. // Try to release the pointer on the HTML side
  39107. try {
  39108. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  39109. }
  39110. catch (e) {
  39111. }
  39112. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  39113. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture);
  39114. this._capturedPointers.remove(pointerId.toString());
  39115. return true;
  39116. };
  39117. /**
  39118. * Determine if the given pointer is captured or not
  39119. * @param pointerId the Id of the pointer
  39120. * @return true if it's captured, false otherwise
  39121. */
  39122. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  39123. return this._capturedPointers.contains(pointerId.toString());
  39124. };
  39125. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  39126. // Avoid unnecessary lookup
  39127. if (this._capturedPointers.count === 0) {
  39128. return null;
  39129. }
  39130. return this._capturedPointers.get(pointerId.toString());
  39131. };
  39132. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, eventState) {
  39133. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  39134. this._updatePointerInfo(eventData);
  39135. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  39136. // Make sure the intersection list is up to date, we maintain this list either in response of a mouse event (here) or before rendering the canvas.
  39137. // Why before rendering the canvas? because some primitives may move and get away/under the mouse cursor (which is not moving). So we need to update at both location in order to always have an accurate list, which is needed for the hover state change.
  39138. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  39139. // Update the over status, same as above, it's could be done here or during rendering, but will be performed only once per render frame
  39140. this._updateOverStatus();
  39141. // Check if we have nothing to raise
  39142. if (!this._actualOverPrimitive && !capturedPrim) {
  39143. return;
  39144. }
  39145. // Update the relatedTarget info with the over primitive or the captured one (if any)
  39146. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  39147. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  39148. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  39149. // Analyze the pointer event type and fire proper events on the primitive
  39150. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  39151. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel);
  39152. }
  39153. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39154. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove);
  39155. }
  39156. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  39157. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown);
  39158. }
  39159. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  39160. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp);
  39161. }
  39162. };
  39163. Canvas2D.prototype._updatePointerInfo = function (eventData) {
  39164. var pii = this._primPointerInfo;
  39165. if (!pii.canvasPointerPos) {
  39166. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  39167. }
  39168. pii.canvasPointerPos.x = eventData.localPosition.x - this.position.x;
  39169. pii.canvasPointerPos.y = (this.engine.getRenderHeight() - eventData.localPosition.y) - this.position.y;
  39170. pii.mouseWheelDelta = 0;
  39171. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  39172. var event = eventData.event;
  39173. if (event.wheelDelta) {
  39174. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  39175. }
  39176. else if (event.detail) {
  39177. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  39178. }
  39179. }
  39180. else {
  39181. var pe = eventData.event;
  39182. pii.ctrlKey = pe.ctrlKey;
  39183. pii.altKey = pe.altKey;
  39184. pii.shiftKey = pe.shiftKey;
  39185. pii.metaKey = pe.metaKey;
  39186. pii.button = pe.button;
  39187. pii.buttons = pe.buttons;
  39188. pii.pointerId = pe.pointerId;
  39189. pii.width = pe.width;
  39190. pii.height = pe.height;
  39191. pii.presssure = pe.pressure;
  39192. pii.tilt.x = pe.tiltX;
  39193. pii.tilt.y = pe.tiltY;
  39194. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  39195. }
  39196. };
  39197. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  39198. if (this.scene.getRenderId() === this._intersectionRenderId) {
  39199. return;
  39200. }
  39201. var ii = Canvas2D._interInfo;
  39202. ii.pickPosition.x = mouseLocalPos.x;
  39203. ii.pickPosition.y = mouseLocalPos.y;
  39204. ii.findFirstOnly = false;
  39205. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  39206. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  39207. this._previousIntersectionList = this._actualIntersectionList;
  39208. this._actualIntersectionList = null;
  39209. this._previousOverPrimitive = this._actualOverPrimitive;
  39210. this._actualOverPrimitive = null;
  39211. return;
  39212. }
  39213. this._updateCanvasState();
  39214. this.intersect(ii);
  39215. this._previousIntersectionList = this._actualIntersectionList;
  39216. this._actualIntersectionList = ii.intersectedPrimitives;
  39217. this._previousOverPrimitive = this._actualOverPrimitive;
  39218. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  39219. this._intersectionRenderId = this.scene.getRenderId();
  39220. };
  39221. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  39222. Canvas2D.prototype._updateOverStatus = function () {
  39223. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  39224. return;
  39225. }
  39226. // Detect a change of over
  39227. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  39228. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  39229. if (prevPrim !== actualPrim) {
  39230. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  39231. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  39232. // Notify the previous "over" prim that the pointer is no longer over it
  39233. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  39234. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  39235. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut);
  39236. }
  39237. // Notify the new "over" prim that the pointer is over it
  39238. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  39239. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  39240. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver);
  39241. }
  39242. }
  39243. this._hoverStatusRenderId = this.scene.getRenderId();
  39244. };
  39245. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  39246. if (this._primPointerInfo.isCaptured) {
  39247. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  39248. }
  39249. else {
  39250. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  39251. var pii = _a[_i];
  39252. if (pii.prim === prim) {
  39253. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  39254. return;
  39255. }
  39256. }
  39257. }
  39258. };
  39259. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  39260. if (!this._notifDebugMode) {
  39261. return;
  39262. }
  39263. var debug = "";
  39264. for (var i = 0; i < prim.hierarchyDepth; i++) {
  39265. debug += " ";
  39266. }
  39267. var pii = this._primPointerInfo;
  39268. debug += "[RID:" + this.scene.getRenderId() + "] [" + prim.hierarchyDepth + "] event:" + BABYLON.PrimitivePointerInfo.getEventTypeName(mask) + ", id: " + prim.id + " (" + BABYLON.Tools.getClassName(prim) + "), primPos: " + pii.primitivePointerPos.toString() + ", canvasPos: " + pii.canvasPointerPos.toString();
  39269. console.log(debug);
  39270. };
  39271. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask) {
  39272. var pii = this._primPointerInfo;
  39273. // In case of PointerOver/Out we will first notify the children (but the deepest to the closest) with PointerEnter/Leave
  39274. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  39275. this._notifChildren(prim, mask);
  39276. }
  39277. var bubbleCancelled = false;
  39278. var cur = prim;
  39279. while (cur) {
  39280. // Only trigger the observers if the primitive is intersected (except for out)
  39281. if (!bubbleCancelled) {
  39282. this._updatePrimPointerPos(cur);
  39283. // Exec the observers
  39284. this._debugExecObserver(cur, mask);
  39285. cur._pointerEventObservable.notifyObservers(pii, mask);
  39286. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  39287. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  39288. if (pii.cancelBubble) {
  39289. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  39290. return;
  39291. }
  39292. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  39293. bubbleCancelled = true;
  39294. }
  39295. }
  39296. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  39297. if (bubbleCancelled) {
  39298. this._updatePrimPointerPos(cur);
  39299. }
  39300. // Trigger a PointerEnter corresponding to the PointerOver
  39301. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  39302. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  39303. cur._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  39304. }
  39305. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  39306. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  39307. cur._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  39308. }
  39309. // Loop to the parent
  39310. cur = cur.parent;
  39311. }
  39312. };
  39313. Canvas2D.prototype._notifChildren = function (prim, mask) {
  39314. var _this = this;
  39315. var pii = this._primPointerInfo;
  39316. prim.children.forEach(function (curChild) {
  39317. // Recurse first, we want the deepest to be notified first
  39318. _this._notifChildren(curChild, mask);
  39319. _this._updatePrimPointerPos(curChild);
  39320. // Fire the proper notification
  39321. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  39322. _this._debugExecObserver(curChild, BABYLON.PrimitivePointerInfo.PointerEnter);
  39323. curChild._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  39324. }
  39325. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  39326. _this._debugExecObserver(curChild, BABYLON.PrimitivePointerInfo.PointerLeave);
  39327. curChild._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  39328. }
  39329. });
  39330. };
  39331. /**
  39332. * Don't forget to call the dispose method when you're done with the Canvas instance.
  39333. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  39334. */
  39335. Canvas2D.prototype.dispose = function () {
  39336. if (!_super.prototype.dispose.call(this)) {
  39337. return false;
  39338. }
  39339. if (this.interactionEnabled) {
  39340. this._setupInteraction(false);
  39341. }
  39342. if (this._beforeRenderObserver) {
  39343. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  39344. this._beforeRenderObserver = null;
  39345. }
  39346. if (this._afterRenderObserver) {
  39347. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  39348. this._afterRenderObserver = null;
  39349. }
  39350. if (this._groupCacheMaps) {
  39351. this._groupCacheMaps.forEach(function (m) { return m.dispose(); });
  39352. this._groupCacheMaps = null;
  39353. }
  39354. };
  39355. Object.defineProperty(Canvas2D.prototype, "scene", {
  39356. /**
  39357. * Accessor to the Scene that owns the Canvas
  39358. * @returns The instance of the Scene object
  39359. */
  39360. get: function () {
  39361. return this._scene;
  39362. },
  39363. enumerable: true,
  39364. configurable: true
  39365. });
  39366. Object.defineProperty(Canvas2D.prototype, "engine", {
  39367. /**
  39368. * Accessor to the Engine that drives the Scene used by this Canvas
  39369. * @returns The instance of the Engine object
  39370. */
  39371. get: function () {
  39372. return this._engine;
  39373. },
  39374. enumerable: true,
  39375. configurable: true
  39376. });
  39377. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  39378. /**
  39379. * Accessor of the Caching Strategy used by this Canvas.
  39380. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  39381. * @returns the value corresponding to the used strategy.
  39382. */
  39383. get: function () {
  39384. return this._cachingStrategy;
  39385. },
  39386. enumerable: true,
  39387. configurable: true
  39388. });
  39389. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  39390. /**
  39391. * Only valid for World Space Canvas, returns the scene node that display the canvas
  39392. */
  39393. get: function () {
  39394. return this._worldSpaceNode;
  39395. },
  39396. enumerable: true,
  39397. configurable: true
  39398. });
  39399. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  39400. /**
  39401. * Check if the WebGL Instanced Array extension is supported or not
  39402. * @returns {}
  39403. */
  39404. get: function () {
  39405. return this._supprtInstancedArray;
  39406. },
  39407. enumerable: true,
  39408. configurable: true
  39409. });
  39410. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  39411. /**
  39412. * Property that defines the fill object used to draw the background of the Canvas.
  39413. * Note that Canvas with a Caching Strategy of
  39414. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  39415. */
  39416. get: function () {
  39417. if (!this._background || !this._background.isVisible) {
  39418. return null;
  39419. }
  39420. return this._background.fill;
  39421. },
  39422. set: function (value) {
  39423. this.checkBackgroundAvailability();
  39424. if (value === this._background.fill) {
  39425. return;
  39426. }
  39427. this._background.fill = value;
  39428. this._background.levelVisible = true;
  39429. },
  39430. enumerable: true,
  39431. configurable: true
  39432. });
  39433. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  39434. /**
  39435. * Property that defines the border object used to draw the background of the Canvas.
  39436. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  39437. */
  39438. get: function () {
  39439. if (!this._background || !this._background.isVisible) {
  39440. return null;
  39441. }
  39442. return this._background.border;
  39443. },
  39444. set: function (value) {
  39445. this.checkBackgroundAvailability();
  39446. if (value === this._background.border) {
  39447. return;
  39448. }
  39449. this._background.border = value;
  39450. this._background.levelVisible = true;
  39451. },
  39452. enumerable: true,
  39453. configurable: true
  39454. });
  39455. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  39456. /**
  39457. * You can set the roundRadius of the background
  39458. * @returns The current roundRadius
  39459. */
  39460. get: function () {
  39461. if (!this._background || !this._background.isVisible) {
  39462. return null;
  39463. }
  39464. return this._background.roundRadius;
  39465. },
  39466. set: function (value) {
  39467. this.checkBackgroundAvailability();
  39468. if (value === this._background.roundRadius) {
  39469. return;
  39470. }
  39471. this._background.roundRadius = value;
  39472. this._background.levelVisible = true;
  39473. },
  39474. enumerable: true,
  39475. configurable: true
  39476. });
  39477. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  39478. /**
  39479. * Enable/Disable interaction for this Canvas
  39480. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  39481. */
  39482. get: function () {
  39483. return this._interactionEnabled;
  39484. },
  39485. set: function (enable) {
  39486. this._setupInteraction(enable);
  39487. },
  39488. enumerable: true,
  39489. configurable: true
  39490. });
  39491. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  39492. get: function () {
  39493. return this.__engineData;
  39494. },
  39495. enumerable: true,
  39496. configurable: true
  39497. });
  39498. Canvas2D.prototype.checkBackgroundAvailability = function () {
  39499. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  39500. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  39501. }
  39502. };
  39503. Object.defineProperty(Canvas2D.prototype, "hierarchySiblingZDelta", {
  39504. /**
  39505. * Read-only property that return the Z delta to apply for each sibling primitives inside of a given one.
  39506. * Sibling Primitives are defined in a specific order, the first ones will be draw below the next ones.
  39507. * This property define the Z value to apply between each sibling Primitive. Current implementation allows 1000 Siblings Primitives per level.
  39508. * @returns The Z Delta
  39509. */
  39510. get: function () {
  39511. return this._hierarchySiblingZDelta;
  39512. },
  39513. enumerable: true,
  39514. configurable: true
  39515. });
  39516. Object.defineProperty(Canvas2D.prototype, "hierarchyLevelZFactor", {
  39517. /**
  39518. * Return the Z Factor that will be applied for each new hierarchy level.
  39519. * @returns The Z Factor
  39520. */
  39521. get: function () {
  39522. return this._hierarchyLevelZFactor;
  39523. },
  39524. enumerable: true,
  39525. configurable: true
  39526. });
  39527. Canvas2D.prototype._updateCanvasState = function () {
  39528. // Check if the update has already been made for this render Frame
  39529. if (this.scene.getRenderId() === this._updateRenderId) {
  39530. return;
  39531. }
  39532. this._renderingSize.width = this.engine.getRenderWidth();
  39533. this._renderingSize.height = this.engine.getRenderHeight();
  39534. if (this._fitRenderingDevice) {
  39535. this.size = this._renderingSize;
  39536. if (this._background) {
  39537. this._background.size = this.size;
  39538. }
  39539. }
  39540. var context = new BABYLON.Render2DContext();
  39541. context.forceRefreshPrimitive = false;
  39542. ++this._globalTransformProcessStep;
  39543. this.updateGlobalTransVis(false);
  39544. this._prepareGroupRender(context);
  39545. this._updateRenderId = this.scene.getRenderId();
  39546. };
  39547. /**
  39548. * Method that renders the Canvas, you should not invoke
  39549. */
  39550. Canvas2D.prototype._render = function () {
  39551. this._updateCanvasState();
  39552. if (this._primPointerInfo.canvasPointerPos) {
  39553. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  39554. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  39555. }
  39556. var context = new BABYLON.Render2DContext();
  39557. this._groupRender(context);
  39558. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  39559. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  39560. this._cachedCanvasGroup._renderCachedCanvas(context);
  39561. }
  39562. };
  39563. /**
  39564. * Internal method that allocate a cache for the given group.
  39565. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  39566. * @param group The group to allocate the cache of.
  39567. * @return custom type with the PackedRect instance giving information about the cache location into the texture and also the MapTexture instance that stores the cache.
  39568. */
  39569. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize) {
  39570. // Determine size
  39571. var size = group.actualSize;
  39572. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  39573. if (minSize) {
  39574. size.width = Math.max(minSize.width, size.width);
  39575. size.height = Math.max(minSize.height, size.height);
  39576. }
  39577. if (!this._groupCacheMaps) {
  39578. this._groupCacheMaps = new Array();
  39579. }
  39580. // Try to find a spot in one of the cached texture
  39581. var res = null;
  39582. for (var _i = 0, _a = this._groupCacheMaps; _i < _a.length; _i++) {
  39583. var map = _a[_i];
  39584. var node = map.allocateRect(size);
  39585. if (node) {
  39586. res = { node: node, texture: map };
  39587. break;
  39588. }
  39589. }
  39590. // Couldn't find a map that could fit the rect, create a new map for it
  39591. if (!res) {
  39592. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  39593. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  39594. if (size.width > mapSize.width || size.height > mapSize.height) {
  39595. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  39596. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  39597. }
  39598. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  39599. map = new BABYLON.MapTexture(id, this._scene, mapSize);
  39600. this._groupCacheMaps.push(map);
  39601. var node = map.allocateRect(size);
  39602. res = { node: node, texture: map };
  39603. }
  39604. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  39605. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  39606. if (group !== this || this._isScreeSpace) {
  39607. var node = res.node;
  39608. // Special case if the canvas is entirely cached: create a group that will have a single sprite it will be rendered specifically at the very end of the rendering process
  39609. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  39610. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  39611. var sprite = BABYLON.Sprite2D.Create(this._cachedCanvasGroup, "__cachedCanvasSprite__", 0, 0, map, node.contentSize, node.pos);
  39612. sprite.zOrder = 1;
  39613. sprite.origin = BABYLON.Vector2.Zero();
  39614. }
  39615. else {
  39616. var sprite = BABYLON.Sprite2D.Create(parent, "__cachedSpriteOfGroup__" + group.id, group.position.x, group.position.y, map, node.contentSize, node.pos, false);
  39617. sprite.origin = group.origin.clone();
  39618. res.sprite = sprite;
  39619. }
  39620. }
  39621. return res;
  39622. };
  39623. /**
  39624. * Get a Solid Color Brush instance matching the given color.
  39625. * @param color The color to retrieve
  39626. * @return A shared instance of the SolidColorBrush2D class that use the given color
  39627. */
  39628. Canvas2D.GetSolidColorBrush = function (color) {
  39629. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  39630. };
  39631. /**
  39632. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  39633. * @param color The color to retrieve
  39634. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  39635. */
  39636. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  39637. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  39638. };
  39639. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  39640. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  39641. if (rotation === void 0) { rotation = 0; }
  39642. if (scale === void 0) { scale = 1; }
  39643. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  39644. };
  39645. /**
  39646. * In this strategy only the direct children groups of the Canvas will be cached, their whole content (whatever the sub groups they have) into a single bitmap.
  39647. * This strategy doesn't allow primitives added directly as children of the Canvas.
  39648. * You typically want to use this strategy of a screenSpace fullscreen canvas: you don't want a bitmap cache taking the whole screen resolution but still want the main contents (say UI in the topLeft and rightBottom for instance) to be efficiently cached.
  39649. */
  39650. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  39651. /**
  39652. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  39653. * This strategy is typically used if the canvas has some groups that are frequently animated. Unchanged ones will have a steady cache and the others will be refreshed when they change, reducing the redraw operation count to their content only.
  39654. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  39655. * Note that in this mode the Canvas itself is not cached, it only contains the sprites of its direct children group to render, there's no point to cache the whole canvas, sprites will be rendered pretty efficiently, the memory cost would be too great for the value of it.
  39656. */
  39657. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  39658. /**
  39659. * In this strategy the whole canvas is cached into a single bitmap containing every primitives it owns, at the exception of the ones that are owned by a group having the DONTCACHEOVERRIDE behavior (these primitives will be directly drawn to the viewport at each render for screenSpace Canvas or be part of the Canvas cache bitmap for worldSpace Canvas).
  39660. */
  39661. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  39662. /**
  39663. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  39664. * Use this strategy if memory is a concern above rendering performances and/or if the canvas is frequently animated (hence reducing the benefits of caching).
  39665. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  39666. */
  39667. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  39668. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  39669. /**
  39670. * Define the default size used for both the width and height of a MapTexture to allocate.
  39671. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  39672. */
  39673. Canvas2D._groupTextureCacheSize = 1024;
  39674. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  39675. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  39676. Canvas2D = __decorate([
  39677. BABYLON.className("Canvas2D")
  39678. ], Canvas2D);
  39679. return Canvas2D;
  39680. })(BABYLON.Group2D);
  39681. BABYLON.Canvas2D = Canvas2D;
  39682. })(BABYLON || (BABYLON = {}));
  39683. var BABYLON;
  39684. (function (BABYLON) {
  39685. /**
  39686. * This is the class that is used to display a World Space Canvas into a scene
  39687. */
  39688. var WorldSpaceCanvas2d = (function (_super) {
  39689. __extends(WorldSpaceCanvas2d, _super);
  39690. function WorldSpaceCanvas2d(name, scene, canvas) {
  39691. _super.call(this, name, scene);
  39692. this._canvas = canvas;
  39693. }
  39694. WorldSpaceCanvas2d.prototype.dispose = function () {
  39695. _super.prototype.dispose.call(this);
  39696. if (this._canvas) {
  39697. this._canvas.dispose();
  39698. this._canvas = null;
  39699. }
  39700. };
  39701. return WorldSpaceCanvas2d;
  39702. })(BABYLON.Mesh);
  39703. BABYLON.WorldSpaceCanvas2d = WorldSpaceCanvas2d;
  39704. })(BABYLON || (BABYLON = {}));
  39705. var BABYLON;
  39706. (function (BABYLON) {
  39707. var ShaderMaterial = (function (_super) {
  39708. __extends(ShaderMaterial, _super);
  39709. function ShaderMaterial(name, scene, shaderPath, options) {
  39710. _super.call(this, name, scene);
  39711. this._textures = {};
  39712. this._floats = {};
  39713. this._floatsArrays = {};
  39714. this._colors3 = {};
  39715. this._colors4 = {};
  39716. this._vectors2 = {};
  39717. this._vectors3 = {};
  39718. this._vectors4 = {};
  39719. this._matrices = {};
  39720. this._matrices3x3 = {};
  39721. this._matrices2x2 = {};
  39722. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39723. this._shaderPath = shaderPath;
  39724. options.needAlphaBlending = options.needAlphaBlending || false;
  39725. options.needAlphaTesting = options.needAlphaTesting || false;
  39726. options.attributes = options.attributes || ["position", "normal", "uv"];
  39727. options.uniforms = options.uniforms || ["worldViewProjection"];
  39728. options.samplers = options.samplers || [];
  39729. options.defines = options.defines || [];
  39730. this._options = options;
  39731. }
  39732. ShaderMaterial.prototype.needAlphaBlending = function () {
  39733. return this._options.needAlphaBlending;
  39734. };
  39735. ShaderMaterial.prototype.needAlphaTesting = function () {
  39736. return this._options.needAlphaTesting;
  39737. };
  39738. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39739. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39740. this._options.uniforms.push(uniformName);
  39741. }
  39742. };
  39743. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39744. if (this._options.samplers.indexOf(name) === -1) {
  39745. this._options.samplers.push(name);
  39746. }
  39747. this._textures[name] = texture;
  39748. return this;
  39749. };
  39750. ShaderMaterial.prototype.setFloat = function (name, value) {
  39751. this._checkUniform(name);
  39752. this._floats[name] = value;
  39753. return this;
  39754. };
  39755. ShaderMaterial.prototype.setFloats = function (name, value) {
  39756. this._checkUniform(name);
  39757. this._floatsArrays[name] = value;
  39758. return this;
  39759. };
  39760. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39761. this._checkUniform(name);
  39762. this._colors3[name] = value;
  39763. return this;
  39764. };
  39765. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39766. this._checkUniform(name);
  39767. this._colors4[name] = value;
  39768. return this;
  39769. };
  39770. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39771. this._checkUniform(name);
  39772. this._vectors2[name] = value;
  39773. return this;
  39774. };
  39775. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39776. this._checkUniform(name);
  39777. this._vectors3[name] = value;
  39778. return this;
  39779. };
  39780. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39781. this._checkUniform(name);
  39782. this._vectors4[name] = value;
  39783. return this;
  39784. };
  39785. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39786. this._checkUniform(name);
  39787. this._matrices[name] = value;
  39788. return this;
  39789. };
  39790. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39791. this._checkUniform(name);
  39792. this._matrices3x3[name] = value;
  39793. return this;
  39794. };
  39795. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39796. this._checkUniform(name);
  39797. this._matrices2x2[name] = value;
  39798. return this;
  39799. };
  39800. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39801. var scene = this.getScene();
  39802. var engine = scene.getEngine();
  39803. if (!this.checkReadyOnEveryCall) {
  39804. if (this._renderId === scene.getRenderId()) {
  39805. return true;
  39806. }
  39807. }
  39808. // Instances
  39809. var defines = [];
  39810. var fallbacks = new BABYLON.EffectFallbacks();
  39811. if (useInstances) {
  39812. defines.push("#define INSTANCES");
  39813. }
  39814. for (var index = 0; index < this._options.defines.length; index++) {
  39815. defines.push(this._options.defines[index]);
  39816. }
  39817. // Bones
  39818. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39819. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39820. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39821. fallbacks.addCPUSkinningFallback(0, mesh);
  39822. }
  39823. // Alpha test
  39824. if (engine.getAlphaTesting()) {
  39825. defines.push("#define ALPHATEST");
  39826. }
  39827. var previousEffect = this._effect;
  39828. var join = defines.join("\n");
  39829. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  39830. if (!this._effect.isReady()) {
  39831. return false;
  39832. }
  39833. if (previousEffect !== this._effect) {
  39834. scene.resetCachedMaterial();
  39835. }
  39836. this._renderId = scene.getRenderId();
  39837. return true;
  39838. };
  39839. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39840. var scene = this.getScene();
  39841. if (this._options.uniforms.indexOf("world") !== -1) {
  39842. this._effect.setMatrix("world", world);
  39843. }
  39844. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39845. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39846. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39847. }
  39848. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39849. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39850. }
  39851. };
  39852. ShaderMaterial.prototype.bind = function (world, mesh) {
  39853. // Std values
  39854. this.bindOnlyWorldMatrix(world);
  39855. if (this.getScene().getCachedMaterial() !== this) {
  39856. if (this._options.uniforms.indexOf("view") !== -1) {
  39857. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39858. }
  39859. if (this._options.uniforms.indexOf("projection") !== -1) {
  39860. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39861. }
  39862. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39863. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39864. }
  39865. // Bones
  39866. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39867. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39868. }
  39869. // Texture
  39870. for (var name in this._textures) {
  39871. this._effect.setTexture(name, this._textures[name]);
  39872. }
  39873. // Float
  39874. for (name in this._floats) {
  39875. this._effect.setFloat(name, this._floats[name]);
  39876. }
  39877. // Float s
  39878. for (name in this._floatsArrays) {
  39879. this._effect.setArray(name, this._floatsArrays[name]);
  39880. }
  39881. // Color3
  39882. for (name in this._colors3) {
  39883. this._effect.setColor3(name, this._colors3[name]);
  39884. }
  39885. // Color4
  39886. for (name in this._colors4) {
  39887. var color = this._colors4[name];
  39888. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39889. }
  39890. // Vector2
  39891. for (name in this._vectors2) {
  39892. this._effect.setVector2(name, this._vectors2[name]);
  39893. }
  39894. // Vector3
  39895. for (name in this._vectors3) {
  39896. this._effect.setVector3(name, this._vectors3[name]);
  39897. }
  39898. // Vector4
  39899. for (name in this._vectors4) {
  39900. this._effect.setVector4(name, this._vectors4[name]);
  39901. }
  39902. // Matrix
  39903. for (name in this._matrices) {
  39904. this._effect.setMatrix(name, this._matrices[name]);
  39905. }
  39906. // Matrix 3x3
  39907. for (name in this._matrices3x3) {
  39908. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39909. }
  39910. // Matrix 2x2
  39911. for (name in this._matrices2x2) {
  39912. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39913. }
  39914. }
  39915. _super.prototype.bind.call(this, world, mesh);
  39916. };
  39917. ShaderMaterial.prototype.clone = function (name) {
  39918. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39919. return newShaderMaterial;
  39920. };
  39921. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39922. if (forceDisposeTextures) {
  39923. for (var name in this._textures) {
  39924. this._textures[name].dispose();
  39925. }
  39926. }
  39927. this._textures = {};
  39928. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39929. };
  39930. ShaderMaterial.prototype.serialize = function () {
  39931. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39932. serializationObject.customType = "BABYLON.ShaderMaterial";
  39933. serializationObject.options = this._options;
  39934. serializationObject.shaderPath = this._shaderPath;
  39935. // Texture
  39936. serializationObject.textures = {};
  39937. for (var name in this._textures) {
  39938. serializationObject.textures[name] = this._textures[name].serialize();
  39939. }
  39940. // Float
  39941. serializationObject.floats = {};
  39942. for (name in this._floats) {
  39943. serializationObject.floats[name] = this._floats[name];
  39944. }
  39945. // Float s
  39946. serializationObject.floatArrays = {};
  39947. for (name in this._floatsArrays) {
  39948. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39949. }
  39950. // Color3
  39951. serializationObject.colors3 = {};
  39952. for (name in this._colors3) {
  39953. serializationObject.colors3[name] = this._colors3[name].asArray();
  39954. }
  39955. // Color4
  39956. serializationObject.colors4 = {};
  39957. for (name in this._colors4) {
  39958. serializationObject.colors4[name] = this._colors4[name].asArray();
  39959. }
  39960. // Vector2
  39961. serializationObject.vectors2 = {};
  39962. for (name in this._vectors2) {
  39963. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39964. }
  39965. // Vector3
  39966. serializationObject.vectors3 = {};
  39967. for (name in this._vectors3) {
  39968. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39969. }
  39970. // Vector4
  39971. serializationObject.vectors4 = {};
  39972. for (name in this._vectors4) {
  39973. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39974. }
  39975. // Matrix
  39976. serializationObject.matrices = {};
  39977. for (name in this._matrices) {
  39978. serializationObject.matrices[name] = this._matrices[name].asArray();
  39979. }
  39980. // Matrix 3x3
  39981. serializationObject.matrices3x3 = {};
  39982. for (name in this._matrices3x3) {
  39983. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39984. }
  39985. // Matrix 2x2
  39986. serializationObject.matrices2x2 = {};
  39987. for (name in this._matrices2x2) {
  39988. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39989. }
  39990. return serializationObject;
  39991. };
  39992. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39993. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39994. // Texture
  39995. for (var name in source.textures) {
  39996. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39997. }
  39998. // Float
  39999. for (name in source.floats) {
  40000. material.setFloat(name, source.floats[name]);
  40001. }
  40002. // Float s
  40003. for (name in source.floatsArrays) {
  40004. material.setFloats(name, source.floatsArrays[name]);
  40005. }
  40006. // Color3
  40007. for (name in source.colors3) {
  40008. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40009. }
  40010. // Color4
  40011. for (name in source.colors4) {
  40012. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40013. }
  40014. // Vector2
  40015. for (name in source.vectors2) {
  40016. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40017. }
  40018. // Vector3
  40019. for (name in source.vectors3) {
  40020. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40021. }
  40022. // Vector4
  40023. for (name in source.vectors4) {
  40024. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40025. }
  40026. // Matrix
  40027. for (name in source.matrices) {
  40028. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40029. }
  40030. // Matrix 3x3
  40031. for (name in source.matrices3x3) {
  40032. material.setMatrix3x3(name, source.matrices3x3[name]);
  40033. }
  40034. // Matrix 2x2
  40035. for (name in source.matrices2x2) {
  40036. material.setMatrix2x2(name, source.matrices2x2[name]);
  40037. }
  40038. return material;
  40039. };
  40040. return ShaderMaterial;
  40041. })(BABYLON.Material);
  40042. BABYLON.ShaderMaterial = ShaderMaterial;
  40043. })(BABYLON || (BABYLON = {}));
  40044. var BABYLON;
  40045. (function (BABYLON) {
  40046. var Internals;
  40047. (function (Internals) {
  40048. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40049. // All values and structures referenced from:
  40050. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40051. var DDS_MAGIC = 0x20534444;
  40052. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  40053. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40054. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  40055. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40056. function FourCCToInt32(value) {
  40057. return value.charCodeAt(0) +
  40058. (value.charCodeAt(1) << 8) +
  40059. (value.charCodeAt(2) << 16) +
  40060. (value.charCodeAt(3) << 24);
  40061. }
  40062. function Int32ToFourCC(value) {
  40063. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  40064. }
  40065. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  40066. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  40067. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  40068. var headerLengthInt = 31; // The header length in 32 bit ints
  40069. // Offsets into the header array
  40070. var off_magic = 0;
  40071. var off_size = 1;
  40072. var off_flags = 2;
  40073. var off_height = 3;
  40074. var off_width = 4;
  40075. var off_mipmapCount = 7;
  40076. var off_pfFlags = 20;
  40077. var off_pfFourCC = 21;
  40078. var off_RGBbpp = 22;
  40079. var off_RMask = 23;
  40080. var off_GMask = 24;
  40081. var off_BMask = 25;
  40082. var off_AMask = 26;
  40083. var off_caps1 = 27;
  40084. var off_caps2 = 28;
  40085. ;
  40086. var DDSTools = (function () {
  40087. function DDSTools() {
  40088. }
  40089. DDSTools.GetDDSInfo = function (arrayBuffer) {
  40090. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  40091. var mipmapCount = 1;
  40092. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  40093. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40094. }
  40095. return {
  40096. width: header[off_width],
  40097. height: header[off_height],
  40098. mipmapCount: mipmapCount,
  40099. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  40100. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  40101. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  40102. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  40103. };
  40104. };
  40105. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40106. var byteArray = new Uint8Array(dataLength);
  40107. var srcData = new Uint8Array(arrayBuffer);
  40108. var index = 0;
  40109. for (var y = height - 1; y >= 0; y--) {
  40110. for (var x = 0; x < width; x++) {
  40111. var srcPos = dataOffset + (x + y * width) * 4;
  40112. byteArray[index + 2] = srcData[srcPos];
  40113. byteArray[index + 1] = srcData[srcPos + 1];
  40114. byteArray[index] = srcData[srcPos + 2];
  40115. byteArray[index + 3] = srcData[srcPos + 3];
  40116. index += 4;
  40117. }
  40118. }
  40119. return byteArray;
  40120. };
  40121. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40122. var byteArray = new Uint8Array(dataLength);
  40123. var srcData = new Uint8Array(arrayBuffer);
  40124. var index = 0;
  40125. for (var y = height - 1; y >= 0; y--) {
  40126. for (var x = 0; x < width; x++) {
  40127. var srcPos = dataOffset + (x + y * width) * 3;
  40128. byteArray[index + 2] = srcData[srcPos];
  40129. byteArray[index + 1] = srcData[srcPos + 1];
  40130. byteArray[index] = srcData[srcPos + 2];
  40131. index += 3;
  40132. }
  40133. }
  40134. return byteArray;
  40135. };
  40136. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40137. var byteArray = new Uint8Array(dataLength);
  40138. var srcData = new Uint8Array(arrayBuffer);
  40139. var index = 0;
  40140. for (var y = height - 1; y >= 0; y--) {
  40141. for (var x = 0; x < width; x++) {
  40142. var srcPos = dataOffset + (x + y * width);
  40143. byteArray[index] = srcData[srcPos];
  40144. index++;
  40145. }
  40146. }
  40147. return byteArray;
  40148. };
  40149. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  40150. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  40151. if (header[off_magic] != DDS_MAGIC) {
  40152. BABYLON.Tools.Error("Invalid magic number in DDS header");
  40153. return;
  40154. }
  40155. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  40156. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  40157. return;
  40158. }
  40159. if (info.isFourCC) {
  40160. fourCC = header[off_pfFourCC];
  40161. switch (fourCC) {
  40162. case FOURCC_DXT1:
  40163. blockBytes = 8;
  40164. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40165. break;
  40166. case FOURCC_DXT3:
  40167. blockBytes = 16;
  40168. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40169. break;
  40170. case FOURCC_DXT5:
  40171. blockBytes = 16;
  40172. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40173. break;
  40174. default:
  40175. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  40176. return;
  40177. }
  40178. }
  40179. mipmapCount = 1;
  40180. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  40181. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40182. }
  40183. var bpp = header[off_RGBbpp];
  40184. for (var face = 0; face < faces; face++) {
  40185. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  40186. width = header[off_width];
  40187. height = header[off_height];
  40188. dataOffset = header[off_size] + 4;
  40189. for (i = 0; i < mipmapCount; ++i) {
  40190. if (info.isRGB) {
  40191. if (bpp === 24) {
  40192. dataLength = width * height * 3;
  40193. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40194. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  40195. }
  40196. else {
  40197. dataLength = width * height * 4;
  40198. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40199. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  40200. }
  40201. }
  40202. else if (info.isLuminance) {
  40203. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  40204. var unpaddedRowSize = width;
  40205. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  40206. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  40207. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40208. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  40209. }
  40210. else {
  40211. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  40212. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  40213. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  40214. }
  40215. dataOffset += dataLength;
  40216. width *= 0.5;
  40217. height *= 0.5;
  40218. width = Math.max(1.0, width);
  40219. height = Math.max(1.0, height);
  40220. }
  40221. }
  40222. };
  40223. return DDSTools;
  40224. })();
  40225. Internals.DDSTools = DDSTools;
  40226. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40227. })(BABYLON || (BABYLON = {}));
  40228. var BABYLON;
  40229. (function (BABYLON) {
  40230. var CannonJSPlugin = (function () {
  40231. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  40232. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  40233. if (iterations === void 0) { iterations = 10; }
  40234. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  40235. this.name = "CannonJSPlugin";
  40236. this._physicsMaterials = [];
  40237. this._fixedTimeStep = 1 / 60;
  40238. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40239. this._currentCollisionGroup = 2;
  40240. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  40241. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  40242. this._tmpPosition = BABYLON.Vector3.Zero();
  40243. this._tmpQuaternion = new BABYLON.Quaternion();
  40244. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  40245. this._tmpDeltaRotation = new BABYLON.Quaternion();
  40246. this._tmpUnityRotation = new BABYLON.Quaternion();
  40247. if (!this.isSupported()) {
  40248. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  40249. return;
  40250. }
  40251. this.world = new CANNON.World();
  40252. this.world.broadphase = new CANNON.NaiveBroadphase();
  40253. this.world.solver.iterations = iterations;
  40254. }
  40255. CannonJSPlugin.prototype.setGravity = function (gravity) {
  40256. this.world.gravity.copy(gravity);
  40257. };
  40258. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  40259. this._fixedTimeStep = timeStep;
  40260. };
  40261. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  40262. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  40263. };
  40264. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40265. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40266. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  40267. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  40268. };
  40269. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  40270. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40271. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  40272. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  40273. };
  40274. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  40275. //parent-child relationship. Does this impostor has a parent impostor?
  40276. if (impostor.parent) {
  40277. if (impostor.physicsBody) {
  40278. this.removePhysicsBody(impostor);
  40279. //TODO is that needed?
  40280. impostor.forceUpdate();
  40281. }
  40282. return;
  40283. }
  40284. //should a new body be created for this impostor?
  40285. if (impostor.isBodyInitRequired()) {
  40286. var shape = this._createShape(impostor);
  40287. //unregister events, if body is being changed
  40288. var oldBody = impostor.physicsBody;
  40289. if (oldBody) {
  40290. this.removePhysicsBody(impostor);
  40291. }
  40292. //create the body and material
  40293. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  40294. var bodyCreationObject = {
  40295. mass: impostor.getParam("mass"),
  40296. material: material
  40297. };
  40298. // A simple extend, in case native options were used.
  40299. var nativeOptions = impostor.getParam("nativeOptions");
  40300. for (var key in nativeOptions) {
  40301. if (nativeOptions.hasOwnProperty(key)) {
  40302. bodyCreationObject[key] = nativeOptions[key];
  40303. }
  40304. }
  40305. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  40306. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  40307. this.world.addEventListener("preStep", impostor.beforeStep);
  40308. this.world.addEventListener("postStep", impostor.afterStep);
  40309. impostor.physicsBody.addShape(shape);
  40310. this.world.add(impostor.physicsBody);
  40311. //try to keep the body moving in the right direction by taking old properties.
  40312. //Should be tested!
  40313. if (oldBody) {
  40314. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  40315. impostor.physicsBody[param].copy(oldBody[param]);
  40316. });
  40317. }
  40318. this._processChildMeshes(impostor);
  40319. }
  40320. //now update the body's transformation
  40321. this._updatePhysicsBodyTransformation(impostor);
  40322. };
  40323. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  40324. var _this = this;
  40325. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  40326. if (meshChildren.length) {
  40327. var processMesh = function (localPosition, mesh) {
  40328. var childImpostor = mesh.getPhysicsImpostor();
  40329. if (childImpostor) {
  40330. var parent = childImpostor.parent;
  40331. if (parent !== mainImpostor) {
  40332. var localPosition = mesh.position;
  40333. if (childImpostor.physicsBody) {
  40334. _this.removePhysicsBody(childImpostor);
  40335. childImpostor.physicsBody = null;
  40336. }
  40337. childImpostor.parent = mainImpostor;
  40338. childImpostor.resetUpdateFlags();
  40339. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  40340. //Add the mass of the children.
  40341. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  40342. }
  40343. }
  40344. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  40345. };
  40346. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  40347. }
  40348. };
  40349. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40350. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  40351. this.world.removeEventListener("preStep", impostor.beforeStep);
  40352. this.world.removeEventListener("postStep", impostor.afterStep);
  40353. this.world.remove(impostor.physicsBody);
  40354. };
  40355. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40356. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40357. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40358. if (!mainBody || !connectedBody) {
  40359. return;
  40360. }
  40361. var constraint;
  40362. var jointData = impostorJoint.joint.jointData;
  40363. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40364. var constraintData = {
  40365. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  40366. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  40367. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  40368. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  40369. maxForce: jointData.nativeParams.maxForce,
  40370. collideConnected: !!jointData.collision
  40371. };
  40372. //Not needed, Cannon has a collideConnected flag
  40373. /*if (!jointData.collision) {
  40374. //add 1st body to a collision group of its own, if it is not in 1
  40375. if (mainBody.collisionFilterGroup === 1) {
  40376. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  40377. this._currentCollisionGroup <<= 1;
  40378. }
  40379. if (connectedBody.collisionFilterGroup === 1) {
  40380. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  40381. this._currentCollisionGroup <<= 1;
  40382. }
  40383. //add their mask to the collisionFilterMask of each other:
  40384. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  40385. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  40386. }*/
  40387. switch (impostorJoint.joint.type) {
  40388. case BABYLON.PhysicsJoint.HingeJoint:
  40389. case BABYLON.PhysicsJoint.Hinge2Joint:
  40390. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  40391. break;
  40392. case BABYLON.PhysicsJoint.DistanceJoint:
  40393. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  40394. break;
  40395. case BABYLON.PhysicsJoint.SpringJoint:
  40396. var springData = jointData;
  40397. constraint = new CANNON.Spring(mainBody, connectedBody, {
  40398. restLength: springData.length,
  40399. stiffness: springData.stiffness,
  40400. damping: springData.damping,
  40401. localAnchorA: constraintData.pivotA,
  40402. localAnchorB: constraintData.pivotB
  40403. });
  40404. break;
  40405. case BABYLON.PhysicsJoint.PointToPointJoint:
  40406. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40407. default:
  40408. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  40409. break;
  40410. }
  40411. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  40412. constraint.collideConnected = !!jointData.collision;
  40413. impostorJoint.joint.physicsJoint = constraint;
  40414. //don't add spring as constraint, as it is not one.
  40415. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  40416. this.world.addConstraint(constraint);
  40417. }
  40418. else {
  40419. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  40420. constraint.applyForce();
  40421. });
  40422. }
  40423. };
  40424. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40425. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  40426. };
  40427. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  40428. var index;
  40429. var mat;
  40430. for (index = 0; index < this._physicsMaterials.length; index++) {
  40431. mat = this._physicsMaterials[index];
  40432. if (mat.friction === friction && mat.restitution === restitution) {
  40433. return mat;
  40434. }
  40435. }
  40436. var currentMat = new CANNON.Material(name);
  40437. currentMat.friction = friction;
  40438. currentMat.restitution = restitution;
  40439. this._physicsMaterials.push(currentMat);
  40440. return currentMat;
  40441. };
  40442. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  40443. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  40444. };
  40445. CannonJSPlugin.prototype._createShape = function (impostor) {
  40446. var object = impostor.object;
  40447. var returnValue;
  40448. var extendSize = impostor.getObjectExtendSize();
  40449. switch (impostor.type) {
  40450. case BABYLON.PhysicsEngine.SphereImpostor:
  40451. var radiusX = extendSize.x;
  40452. var radiusY = extendSize.y;
  40453. var radiusZ = extendSize.z;
  40454. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  40455. break;
  40456. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  40457. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40458. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  40459. break;
  40460. case BABYLON.PhysicsImpostor.BoxImpostor:
  40461. var box = extendSize.scale(0.5);
  40462. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  40463. break;
  40464. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40465. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  40466. returnValue = new CANNON.Plane();
  40467. break;
  40468. case BABYLON.PhysicsImpostor.MeshImpostor:
  40469. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  40470. var rawFaces = object.getIndices ? object.getIndices() : [];
  40471. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  40472. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  40473. break;
  40474. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  40475. returnValue = this._createHeightmap(object);
  40476. break;
  40477. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40478. returnValue = new CANNON.Particle();
  40479. break;
  40480. }
  40481. return returnValue;
  40482. };
  40483. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  40484. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40485. var matrix = [];
  40486. //For now pointDepth will not be used and will be automatically calculated.
  40487. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  40488. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  40489. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  40490. var elementSize = dim * 2 / arraySize;
  40491. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  40492. for (var i = 0; i < pos.length; i = i + 3) {
  40493. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  40494. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  40495. var y = pos[i + 1] + minY;
  40496. if (!matrix[x]) {
  40497. matrix[x] = [];
  40498. }
  40499. if (!matrix[x][z]) {
  40500. matrix[x][z] = y;
  40501. }
  40502. matrix[x][z] = Math.max(y, matrix[x][z]);
  40503. }
  40504. for (var x = 0; x <= arraySize; ++x) {
  40505. if (!matrix[x]) {
  40506. var loc = 1;
  40507. while (!matrix[(x + loc) % arraySize]) {
  40508. loc++;
  40509. }
  40510. matrix[x] = matrix[(x + loc) % arraySize].slice();
  40511. }
  40512. for (var z = 0; z <= arraySize; ++z) {
  40513. if (!matrix[x][z]) {
  40514. var loc = 1;
  40515. var newValue;
  40516. while (newValue === undefined) {
  40517. newValue = matrix[x][(z + loc++) % arraySize];
  40518. }
  40519. matrix[x][z] = newValue;
  40520. }
  40521. }
  40522. }
  40523. var shape = new CANNON.Heightfield(matrix, {
  40524. elementSize: elementSize
  40525. });
  40526. //For future reference, needed for body transformation
  40527. shape.minY = minY;
  40528. return shape;
  40529. };
  40530. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  40531. var object = impostor.object;
  40532. //make sure it is updated...
  40533. object.computeWorldMatrix && object.computeWorldMatrix(true);
  40534. // The delta between the mesh position and the mesh bounding box center
  40535. var center = impostor.getObjectCenter();
  40536. var extendSize = impostor.getObjectExtendSize();
  40537. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  40538. this._tmpPosition.copyFrom(center);
  40539. var quaternion = object.rotationQuaternion;
  40540. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  40541. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  40542. //-90 DEG in X, precalculated
  40543. quaternion = quaternion.multiply(this._minus90X);
  40544. //Invert! (Precalculated, 90 deg in X)
  40545. //No need to clone. this will never change.
  40546. impostor.setDeltaRotation(this._plus90X);
  40547. }
  40548. //If it is a heightfield, if should be centered.
  40549. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  40550. var mesh = object;
  40551. //calculate the correct body position:
  40552. var rotationQuaternion = mesh.rotationQuaternion;
  40553. mesh.rotationQuaternion = this._tmpUnityRotation;
  40554. mesh.computeWorldMatrix(true);
  40555. //get original center with no rotation
  40556. var c = center.clone();
  40557. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  40558. //rotation is back
  40559. mesh.rotationQuaternion = rotationQuaternion;
  40560. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  40561. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  40562. mesh.setPivotMatrix(p);
  40563. mesh.computeWorldMatrix(true);
  40564. //calculate the translation
  40565. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  40566. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  40567. //add it inverted to the delta
  40568. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  40569. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  40570. mesh.setPivotMatrix(oldPivot);
  40571. mesh.computeWorldMatrix(true);
  40572. }
  40573. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  40574. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  40575. this._tmpPosition.copyFrom(object.position);
  40576. }
  40577. impostor.setDeltaPosition(this._tmpDeltaPosition);
  40578. //Now update the impostor object
  40579. impostor.physicsBody.position.copy(this._tmpPosition);
  40580. impostor.physicsBody.quaternion.copy(quaternion);
  40581. };
  40582. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40583. impostor.object.position.copyFrom(impostor.physicsBody.position);
  40584. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  40585. };
  40586. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40587. impostor.physicsBody.position.copy(newPosition);
  40588. impostor.physicsBody.quaternion.copy(newRotation);
  40589. };
  40590. CannonJSPlugin.prototype.isSupported = function () {
  40591. return window.CANNON !== undefined;
  40592. };
  40593. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40594. impostor.physicsBody.velocity.copy(velocity);
  40595. };
  40596. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40597. impostor.physicsBody.angularVelocity.copy(velocity);
  40598. };
  40599. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40600. var v = impostor.physicsBody.velocity;
  40601. if (!v)
  40602. return null;
  40603. return new BABYLON.Vector3(v.x, v.y, v.z);
  40604. };
  40605. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40606. var v = impostor.physicsBody.angularVelocity;
  40607. if (!v)
  40608. return null;
  40609. return new BABYLON.Vector3(v.x, v.y, v.z);
  40610. };
  40611. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40612. impostor.physicsBody.mass = mass;
  40613. impostor.physicsBody.updateMassProperties();
  40614. };
  40615. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  40616. impostor.physicsBody.sleep();
  40617. };
  40618. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  40619. impostor.physicsBody.wakeUp();
  40620. };
  40621. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40622. joint.physicsJoint.distance = maxDistance;
  40623. };
  40624. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  40625. if (!motorIndex) {
  40626. joint.physicsJoint.enableMotor();
  40627. }
  40628. };
  40629. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  40630. if (!motorIndex) {
  40631. joint.physicsJoint.disableMotor();
  40632. }
  40633. };
  40634. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40635. if (!motorIndex) {
  40636. joint.physicsJoint.enableMotor();
  40637. joint.physicsJoint.setMotorSpeed(speed);
  40638. if (maxForce) {
  40639. this.setLimit(joint, maxForce);
  40640. }
  40641. }
  40642. };
  40643. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  40644. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  40645. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  40646. };
  40647. CannonJSPlugin.prototype.dispose = function () {
  40648. //nothing to do, actually.
  40649. };
  40650. return CannonJSPlugin;
  40651. })();
  40652. BABYLON.CannonJSPlugin = CannonJSPlugin;
  40653. })(BABYLON || (BABYLON = {}));
  40654. var BABYLON;
  40655. (function (BABYLON) {
  40656. var OimoJSPlugin = (function () {
  40657. function OimoJSPlugin(iterations) {
  40658. this.name = "OimoJSPlugin";
  40659. this._tmpImpostorsArray = [];
  40660. this._tmpPositionVector = BABYLON.Vector3.Zero();
  40661. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  40662. this.world.clear();
  40663. //making sure no stats are calculated
  40664. this.world.isNoStat = true;
  40665. }
  40666. OimoJSPlugin.prototype.setGravity = function (gravity) {
  40667. this.world.gravity.copy(gravity);
  40668. };
  40669. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  40670. this.world.timeStep = timeStep;
  40671. };
  40672. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  40673. var _this = this;
  40674. impostors.forEach(function (impostor) {
  40675. impostor.beforeStep();
  40676. });
  40677. this.world.step();
  40678. impostors.forEach(function (impostor) {
  40679. impostor.afterStep();
  40680. //update the ordered impostors array
  40681. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  40682. });
  40683. //check for collisions
  40684. var contact = this.world.contacts;
  40685. while (contact !== null) {
  40686. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  40687. contact = contact.next;
  40688. continue;
  40689. }
  40690. //is this body colliding with any other? get the impostor
  40691. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  40692. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  40693. if (!mainImpostor || !collidingImpostor) {
  40694. contact = contact.next;
  40695. continue;
  40696. }
  40697. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  40698. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  40699. contact = contact.next;
  40700. }
  40701. };
  40702. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40703. var mass = impostor.physicsBody.massInfo.mass;
  40704. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  40705. };
  40706. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  40707. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  40708. this.applyImpulse(impostor, force, contactPoint);
  40709. };
  40710. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  40711. var _this = this;
  40712. //parent-child relationship. Does this impostor has a parent impostor?
  40713. if (impostor.parent) {
  40714. if (impostor.physicsBody) {
  40715. this.removePhysicsBody(impostor);
  40716. //TODO is that needed?
  40717. impostor.forceUpdate();
  40718. }
  40719. return;
  40720. }
  40721. if (impostor.isBodyInitRequired()) {
  40722. var bodyConfig = {
  40723. name: impostor.uniqueId,
  40724. //Oimo must have mass, also for static objects.
  40725. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  40726. size: [],
  40727. type: [],
  40728. pos: [],
  40729. rot: [],
  40730. move: impostor.getParam("mass") !== 0,
  40731. //Supporting older versions of Oimo
  40732. world: this.world
  40733. };
  40734. var impostors = [impostor];
  40735. function addToArray(parent) {
  40736. if (!parent.getChildMeshes)
  40737. return;
  40738. parent.getChildMeshes().forEach(function (m) {
  40739. if (m.physicsImpostor) {
  40740. impostors.push(m.physicsImpostor);
  40741. m.physicsImpostor._init();
  40742. }
  40743. });
  40744. }
  40745. addToArray(impostor.object);
  40746. function checkWithEpsilon(value) {
  40747. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  40748. }
  40749. impostors.forEach(function (i) {
  40750. //get the correct bounding box
  40751. var oldQuaternion = i.object.rotationQuaternion;
  40752. var rot = new OIMO.Euler().setFromQuaternion({
  40753. x: impostor.object.rotationQuaternion.x,
  40754. y: impostor.object.rotationQuaternion.y,
  40755. z: impostor.object.rotationQuaternion.z,
  40756. s: impostor.object.rotationQuaternion.w
  40757. });
  40758. var extendSize = i.getObjectExtendSize();
  40759. if (i === impostor) {
  40760. var center = impostor.getObjectCenter();
  40761. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  40762. //Can also use Array.prototype.push.apply
  40763. bodyConfig.pos.push(center.x);
  40764. bodyConfig.pos.push(center.y);
  40765. bodyConfig.pos.push(center.z);
  40766. //tmp solution
  40767. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  40768. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  40769. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  40770. }
  40771. else {
  40772. bodyConfig.pos.push(i.object.position.x);
  40773. bodyConfig.pos.push(i.object.position.y);
  40774. bodyConfig.pos.push(i.object.position.z);
  40775. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  40776. bodyConfig.rot.push(0);
  40777. bodyConfig.rot.push(0);
  40778. bodyConfig.rot.push(0);
  40779. }
  40780. // register mesh
  40781. switch (i.type) {
  40782. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40783. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  40784. case BABYLON.PhysicsImpostor.SphereImpostor:
  40785. var radiusX = extendSize.x;
  40786. var radiusY = extendSize.y;
  40787. var radiusZ = extendSize.z;
  40788. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  40789. bodyConfig.type.push('sphere');
  40790. //due to the way oimo works with compounds, add 3 times
  40791. bodyConfig.size.push(size);
  40792. bodyConfig.size.push(size);
  40793. bodyConfig.size.push(size);
  40794. break;
  40795. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40796. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  40797. var sizeY = checkWithEpsilon(extendSize.y);
  40798. bodyConfig.type.push('cylinder');
  40799. bodyConfig.size.push(sizeX);
  40800. bodyConfig.size.push(sizeY);
  40801. //due to the way oimo works with compounds, add one more value.
  40802. bodyConfig.size.push(sizeY);
  40803. break;
  40804. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40805. case BABYLON.PhysicsImpostor.BoxImpostor:
  40806. default:
  40807. var sizeX = checkWithEpsilon(extendSize.x);
  40808. var sizeY = checkWithEpsilon(extendSize.y);
  40809. var sizeZ = checkWithEpsilon(extendSize.z);
  40810. bodyConfig.type.push('box');
  40811. bodyConfig.size.push(sizeX);
  40812. bodyConfig.size.push(sizeY);
  40813. bodyConfig.size.push(sizeZ);
  40814. break;
  40815. }
  40816. //actually not needed, but hey...
  40817. i.object.rotationQuaternion = oldQuaternion;
  40818. });
  40819. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  40820. }
  40821. else {
  40822. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  40823. }
  40824. impostor.setDeltaPosition(this._tmpPositionVector);
  40825. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  40826. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  40827. };
  40828. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40829. //impostor.physicsBody.dispose();
  40830. //Same as : (older oimo versions)
  40831. this.world.removeRigidBody(impostor.physicsBody);
  40832. };
  40833. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40834. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40835. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40836. if (!mainBody || !connectedBody) {
  40837. return;
  40838. }
  40839. var jointData = impostorJoint.joint.jointData;
  40840. var options = jointData.nativeParams || {};
  40841. var type;
  40842. var nativeJointData = {
  40843. body1: mainBody,
  40844. body2: connectedBody,
  40845. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  40846. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  40847. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  40848. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  40849. min: options.min,
  40850. max: options.max,
  40851. collision: options.collision || jointData.collision,
  40852. spring: options.spring,
  40853. //supporting older version of Oimo
  40854. world: this.world
  40855. };
  40856. switch (impostorJoint.joint.type) {
  40857. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40858. type = "jointBall";
  40859. break;
  40860. case BABYLON.PhysicsJoint.SpringJoint:
  40861. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  40862. var springData = jointData;
  40863. nativeJointData.min = springData.length || nativeJointData.min;
  40864. //Max should also be set, just make sure it is at least min
  40865. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  40866. case BABYLON.PhysicsJoint.DistanceJoint:
  40867. type = "jointDistance";
  40868. nativeJointData.max = jointData.maxDistance;
  40869. break;
  40870. case BABYLON.PhysicsJoint.PrismaticJoint:
  40871. type = "jointPrisme";
  40872. break;
  40873. case BABYLON.PhysicsJoint.SliderJoint:
  40874. type = "jointSlide";
  40875. break;
  40876. case BABYLON.PhysicsJoint.WheelJoint:
  40877. type = "jointWheel";
  40878. break;
  40879. case BABYLON.PhysicsJoint.HingeJoint:
  40880. default:
  40881. type = "jointHinge";
  40882. break;
  40883. }
  40884. nativeJointData.type = type;
  40885. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  40886. };
  40887. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40888. //Bug in Oimo prevents us from disposing a joint in the playground
  40889. //joint.joint.physicsJoint.dispose();
  40890. //So we will bruteforce it!
  40891. try {
  40892. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  40893. }
  40894. catch (e) {
  40895. BABYLON.Tools.Warn(e);
  40896. }
  40897. };
  40898. OimoJSPlugin.prototype.isSupported = function () {
  40899. return OIMO !== undefined;
  40900. };
  40901. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40902. if (!impostor.physicsBody.sleeping) {
  40903. //TODO check that
  40904. if (impostor.physicsBody.shapes.next) {
  40905. var parentShape = this._getLastShape(impostor.physicsBody);
  40906. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  40907. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  40908. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  40909. }
  40910. else {
  40911. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  40912. }
  40913. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  40914. }
  40915. };
  40916. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40917. var body = impostor.physicsBody;
  40918. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  40919. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  40920. body.syncShapes();
  40921. body.awake();
  40922. };
  40923. OimoJSPlugin.prototype._getLastShape = function (body) {
  40924. var lastShape = body.shapes;
  40925. while (lastShape.next) {
  40926. lastShape = lastShape.next;
  40927. }
  40928. return lastShape;
  40929. };
  40930. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40931. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  40932. };
  40933. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40934. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  40935. };
  40936. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40937. var v = impostor.physicsBody.linearVelocity;
  40938. if (!v)
  40939. return null;
  40940. return new BABYLON.Vector3(v.x, v.y, v.z);
  40941. };
  40942. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40943. var v = impostor.physicsBody.angularVelocity;
  40944. if (!v)
  40945. return null;
  40946. return new BABYLON.Vector3(v.x, v.y, v.z);
  40947. };
  40948. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40949. var staticBody = mass === 0;
  40950. //this will actually set the body's density and not its mass.
  40951. //But this is how oimo treats the mass variable.
  40952. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  40953. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  40954. };
  40955. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  40956. impostor.physicsBody.sleep();
  40957. };
  40958. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  40959. impostor.physicsBody.awake();
  40960. };
  40961. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40962. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  40963. if (minDistance !== void 0) {
  40964. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  40965. }
  40966. };
  40967. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40968. //TODO separate rotational and transational motors.
  40969. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40970. if (motor) {
  40971. motor.setMotor(speed, maxForce);
  40972. }
  40973. };
  40974. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  40975. //TODO separate rotational and transational motors.
  40976. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40977. if (motor) {
  40978. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  40979. }
  40980. };
  40981. OimoJSPlugin.prototype.dispose = function () {
  40982. this.world.clear();
  40983. };
  40984. return OimoJSPlugin;
  40985. })();
  40986. BABYLON.OimoJSPlugin = OimoJSPlugin;
  40987. })(BABYLON || (BABYLON = {}));
  40988. var BABYLON;
  40989. (function (BABYLON) {
  40990. var DisplayPassPostProcess = (function (_super) {
  40991. __extends(DisplayPassPostProcess, _super);
  40992. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  40993. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  40994. }
  40995. return DisplayPassPostProcess;
  40996. })(BABYLON.PostProcess);
  40997. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  40998. })(BABYLON || (BABYLON = {}));
  40999. var BABYLON;
  41000. (function (BABYLON) {
  41001. var SimplificationSettings = (function () {
  41002. function SimplificationSettings(quality, distance, optimizeMesh) {
  41003. this.quality = quality;
  41004. this.distance = distance;
  41005. this.optimizeMesh = optimizeMesh;
  41006. }
  41007. return SimplificationSettings;
  41008. })();
  41009. BABYLON.SimplificationSettings = SimplificationSettings;
  41010. var SimplificationQueue = (function () {
  41011. function SimplificationQueue() {
  41012. this.running = false;
  41013. this._simplificationArray = [];
  41014. }
  41015. SimplificationQueue.prototype.addTask = function (task) {
  41016. this._simplificationArray.push(task);
  41017. };
  41018. SimplificationQueue.prototype.executeNext = function () {
  41019. var task = this._simplificationArray.pop();
  41020. if (task) {
  41021. this.running = true;
  41022. this.runSimplification(task);
  41023. }
  41024. else {
  41025. this.running = false;
  41026. }
  41027. };
  41028. SimplificationQueue.prototype.runSimplification = function (task) {
  41029. var _this = this;
  41030. if (task.parallelProcessing) {
  41031. //parallel simplifier
  41032. task.settings.forEach(function (setting) {
  41033. var simplifier = _this.getSimplifier(task);
  41034. simplifier.simplify(setting, function (newMesh) {
  41035. task.mesh.addLODLevel(setting.distance, newMesh);
  41036. newMesh.isVisible = true;
  41037. //check if it is the last
  41038. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41039. //all done, run the success callback.
  41040. task.successCallback();
  41041. }
  41042. _this.executeNext();
  41043. });
  41044. });
  41045. }
  41046. else {
  41047. //single simplifier.
  41048. var simplifier = this.getSimplifier(task);
  41049. var runDecimation = function (setting, callback) {
  41050. simplifier.simplify(setting, function (newMesh) {
  41051. task.mesh.addLODLevel(setting.distance, newMesh);
  41052. newMesh.isVisible = true;
  41053. //run the next quality level
  41054. callback();
  41055. });
  41056. };
  41057. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  41058. runDecimation(task.settings[loop.index], function () {
  41059. loop.executeNext();
  41060. });
  41061. }, function () {
  41062. //execution ended, run the success callback.
  41063. if (task.successCallback) {
  41064. task.successCallback();
  41065. }
  41066. _this.executeNext();
  41067. });
  41068. }
  41069. };
  41070. SimplificationQueue.prototype.getSimplifier = function (task) {
  41071. switch (task.simplificationType) {
  41072. case SimplificationType.QUADRATIC:
  41073. default:
  41074. return new QuadraticErrorSimplification(task.mesh);
  41075. }
  41076. };
  41077. return SimplificationQueue;
  41078. })();
  41079. BABYLON.SimplificationQueue = SimplificationQueue;
  41080. /**
  41081. * The implemented types of simplification.
  41082. * At the moment only Quadratic Error Decimation is implemented.
  41083. */
  41084. (function (SimplificationType) {
  41085. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  41086. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  41087. var SimplificationType = BABYLON.SimplificationType;
  41088. var DecimationTriangle = (function () {
  41089. function DecimationTriangle(vertices) {
  41090. this.vertices = vertices;
  41091. this.error = new Array(4);
  41092. this.deleted = false;
  41093. this.isDirty = false;
  41094. this.deletePending = false;
  41095. this.borderFactor = 0;
  41096. }
  41097. return DecimationTriangle;
  41098. })();
  41099. BABYLON.DecimationTriangle = DecimationTriangle;
  41100. var DecimationVertex = (function () {
  41101. function DecimationVertex(position, id) {
  41102. this.position = position;
  41103. this.id = id;
  41104. this.isBorder = true;
  41105. this.q = new QuadraticMatrix();
  41106. this.triangleCount = 0;
  41107. this.triangleStart = 0;
  41108. this.originalOffsets = [];
  41109. }
  41110. DecimationVertex.prototype.updatePosition = function (newPosition) {
  41111. this.position.copyFrom(newPosition);
  41112. };
  41113. return DecimationVertex;
  41114. })();
  41115. BABYLON.DecimationVertex = DecimationVertex;
  41116. var QuadraticMatrix = (function () {
  41117. function QuadraticMatrix(data) {
  41118. this.data = new Array(10);
  41119. for (var i = 0; i < 10; ++i) {
  41120. if (data && data[i]) {
  41121. this.data[i] = data[i];
  41122. }
  41123. else {
  41124. this.data[i] = 0;
  41125. }
  41126. }
  41127. }
  41128. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  41129. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  41130. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  41131. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  41132. return det;
  41133. };
  41134. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  41135. for (var i = 0; i < 10; ++i) {
  41136. this.data[i] += matrix.data[i];
  41137. }
  41138. };
  41139. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  41140. for (var i = 0; i < 10; ++i) {
  41141. this.data[i] += data[i];
  41142. }
  41143. };
  41144. QuadraticMatrix.prototype.add = function (matrix) {
  41145. var m = new QuadraticMatrix();
  41146. for (var i = 0; i < 10; ++i) {
  41147. m.data[i] = this.data[i] + matrix.data[i];
  41148. }
  41149. return m;
  41150. };
  41151. QuadraticMatrix.FromData = function (a, b, c, d) {
  41152. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  41153. };
  41154. //returning an array to avoid garbage collection
  41155. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  41156. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  41157. };
  41158. return QuadraticMatrix;
  41159. })();
  41160. BABYLON.QuadraticMatrix = QuadraticMatrix;
  41161. var Reference = (function () {
  41162. function Reference(vertexId, triangleId) {
  41163. this.vertexId = vertexId;
  41164. this.triangleId = triangleId;
  41165. }
  41166. return Reference;
  41167. })();
  41168. BABYLON.Reference = Reference;
  41169. /**
  41170. * An implementation of the Quadratic Error simplification algorithm.
  41171. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  41172. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  41173. * @author RaananW
  41174. */
  41175. var QuadraticErrorSimplification = (function () {
  41176. function QuadraticErrorSimplification(_mesh) {
  41177. this._mesh = _mesh;
  41178. this.initialized = false;
  41179. this.syncIterations = 5000;
  41180. this.aggressiveness = 7;
  41181. this.decimationIterations = 100;
  41182. this.boundingBoxEpsilon = BABYLON.Epsilon;
  41183. }
  41184. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  41185. var _this = this;
  41186. this.initDecimatedMesh();
  41187. //iterating through the submeshes array, one after the other.
  41188. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  41189. _this.initWithMesh(loop.index, function () {
  41190. _this.runDecimation(settings, loop.index, function () {
  41191. loop.executeNext();
  41192. });
  41193. }, settings.optimizeMesh);
  41194. }, function () {
  41195. setTimeout(function () {
  41196. successCallback(_this._reconstructedMesh);
  41197. }, 0);
  41198. });
  41199. };
  41200. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  41201. var _this = this;
  41202. var gCount = 0;
  41203. triangle.vertices.forEach(function (vertex) {
  41204. var count = 0;
  41205. var vPos = vertex.position;
  41206. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  41207. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  41208. ++count;
  41209. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  41210. ++count;
  41211. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  41212. ++count;
  41213. if (count > 1) {
  41214. ++gCount;
  41215. }
  41216. ;
  41217. });
  41218. if (gCount > 1) {
  41219. console.log(triangle, gCount);
  41220. }
  41221. return gCount > 1;
  41222. };
  41223. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  41224. var _this = this;
  41225. var targetCount = ~~(this.triangles.length * settings.quality);
  41226. var deletedTriangles = 0;
  41227. var triangleCount = this.triangles.length;
  41228. var iterationFunction = function (iteration, callback) {
  41229. setTimeout(function () {
  41230. if (iteration % 5 === 0) {
  41231. _this.updateMesh(iteration === 0);
  41232. }
  41233. for (var i = 0; i < _this.triangles.length; ++i) {
  41234. _this.triangles[i].isDirty = false;
  41235. }
  41236. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  41237. var trianglesIterator = function (i) {
  41238. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  41239. var t = _this.triangles[tIdx];
  41240. if (!t)
  41241. return;
  41242. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  41243. return;
  41244. }
  41245. for (var j = 0; j < 3; ++j) {
  41246. if (t.error[j] < threshold) {
  41247. var deleted0 = [];
  41248. var deleted1 = [];
  41249. var v0 = t.vertices[j];
  41250. var v1 = t.vertices[(j + 1) % 3];
  41251. if (v0.isBorder || v1.isBorder)
  41252. continue;
  41253. var p = BABYLON.Vector3.Zero();
  41254. var n = BABYLON.Vector3.Zero();
  41255. var uv = BABYLON.Vector2.Zero();
  41256. var color = new BABYLON.Color4(0, 0, 0, 1);
  41257. _this.calculateError(v0, v1, p, n, uv, color);
  41258. var delTr = [];
  41259. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  41260. continue;
  41261. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  41262. continue;
  41263. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  41264. continue;
  41265. var uniqueArray = [];
  41266. delTr.forEach(function (deletedT) {
  41267. if (uniqueArray.indexOf(deletedT) === -1) {
  41268. deletedT.deletePending = true;
  41269. uniqueArray.push(deletedT);
  41270. }
  41271. });
  41272. if (uniqueArray.length % 2 !== 0) {
  41273. continue;
  41274. }
  41275. v0.q = v1.q.add(v0.q);
  41276. v0.updatePosition(p);
  41277. var tStart = _this.references.length;
  41278. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  41279. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  41280. var tCount = _this.references.length - tStart;
  41281. if (tCount <= v0.triangleCount) {
  41282. if (tCount) {
  41283. for (var c = 0; c < tCount; c++) {
  41284. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  41285. }
  41286. }
  41287. }
  41288. else {
  41289. v0.triangleStart = tStart;
  41290. }
  41291. v0.triangleCount = tCount;
  41292. break;
  41293. }
  41294. }
  41295. };
  41296. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  41297. }, 0);
  41298. };
  41299. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  41300. if (triangleCount - deletedTriangles <= targetCount)
  41301. loop.breakLoop();
  41302. else {
  41303. iterationFunction(loop.index, function () {
  41304. loop.executeNext();
  41305. });
  41306. }
  41307. }, function () {
  41308. setTimeout(function () {
  41309. //reconstruct this part of the mesh
  41310. _this.reconstructMesh(submeshIndex);
  41311. successCallback();
  41312. }, 0);
  41313. });
  41314. };
  41315. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  41316. var _this = this;
  41317. this.vertices = [];
  41318. this.triangles = [];
  41319. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41320. var indices = this._mesh.getIndices();
  41321. var submesh = this._mesh.subMeshes[submeshIndex];
  41322. var findInVertices = function (positionToSearch) {
  41323. if (optimizeMesh) {
  41324. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  41325. if (_this.vertices[ii].position.equals(positionToSearch)) {
  41326. return _this.vertices[ii];
  41327. }
  41328. }
  41329. }
  41330. return null;
  41331. };
  41332. var vertexReferences = [];
  41333. var vertexInit = function (i) {
  41334. var offset = i + submesh.verticesStart;
  41335. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  41336. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  41337. vertex.originalOffsets.push(offset);
  41338. if (vertex.id === _this.vertices.length) {
  41339. _this.vertices.push(vertex);
  41340. }
  41341. vertexReferences.push(vertex.id);
  41342. };
  41343. //var totalVertices = mesh.getTotalVertices();
  41344. var totalVertices = submesh.verticesCount;
  41345. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  41346. var indicesInit = function (i) {
  41347. var offset = (submesh.indexStart / 3) + i;
  41348. var pos = (offset * 3);
  41349. var i0 = indices[pos + 0];
  41350. var i1 = indices[pos + 1];
  41351. var i2 = indices[pos + 2];
  41352. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  41353. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  41354. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  41355. var triangle = new DecimationTriangle([v0, v1, v2]);
  41356. triangle.originalOffset = pos;
  41357. _this.triangles.push(triangle);
  41358. };
  41359. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  41360. _this.init(callback);
  41361. });
  41362. });
  41363. };
  41364. QuadraticErrorSimplification.prototype.init = function (callback) {
  41365. var _this = this;
  41366. var triangleInit1 = function (i) {
  41367. var t = _this.triangles[i];
  41368. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  41369. for (var j = 0; j < 3; j++) {
  41370. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  41371. }
  41372. };
  41373. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  41374. var triangleInit2 = function (i) {
  41375. var t = _this.triangles[i];
  41376. for (var j = 0; j < 3; ++j) {
  41377. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  41378. }
  41379. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41380. };
  41381. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  41382. _this.initialized = true;
  41383. callback();
  41384. });
  41385. });
  41386. };
  41387. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  41388. var newTriangles = [];
  41389. var i;
  41390. for (i = 0; i < this.vertices.length; ++i) {
  41391. this.vertices[i].triangleCount = 0;
  41392. }
  41393. var t;
  41394. var j;
  41395. for (i = 0; i < this.triangles.length; ++i) {
  41396. if (!this.triangles[i].deleted) {
  41397. t = this.triangles[i];
  41398. for (j = 0; j < 3; ++j) {
  41399. t.vertices[j].triangleCount = 1;
  41400. }
  41401. newTriangles.push(t);
  41402. }
  41403. }
  41404. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  41405. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  41406. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  41407. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  41408. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41409. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41410. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41411. var vertexCount = 0;
  41412. for (i = 0; i < this.vertices.length; ++i) {
  41413. var vertex = this.vertices[i];
  41414. vertex.id = vertexCount;
  41415. if (vertex.triangleCount) {
  41416. vertex.originalOffsets.forEach(function (originalOffset) {
  41417. newPositionData.push(vertex.position.x);
  41418. newPositionData.push(vertex.position.y);
  41419. newPositionData.push(vertex.position.z);
  41420. newNormalData.push(normalData[originalOffset * 3]);
  41421. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  41422. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  41423. if (uvs && uvs.length) {
  41424. newUVsData.push(uvs[(originalOffset * 2)]);
  41425. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  41426. }
  41427. else if (colorsData && colorsData.length) {
  41428. newColorsData.push(colorsData[(originalOffset * 4)]);
  41429. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  41430. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  41431. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  41432. }
  41433. ++vertexCount;
  41434. });
  41435. }
  41436. }
  41437. var startingIndex = this._reconstructedMesh.getTotalIndices();
  41438. var startingVertex = this._reconstructedMesh.getTotalVertices();
  41439. var submeshesArray = this._reconstructedMesh.subMeshes;
  41440. this._reconstructedMesh.subMeshes = [];
  41441. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  41442. var originalIndices = this._mesh.getIndices();
  41443. for (i = 0; i < newTriangles.length; ++i) {
  41444. t = newTriangles[i]; //now get the new referencing point for each vertex
  41445. [0, 1, 2].forEach(function (idx) {
  41446. var id = originalIndices[t.originalOffset + idx];
  41447. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  41448. if (offset < 0)
  41449. offset = 0;
  41450. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  41451. });
  41452. }
  41453. //overwriting the old vertex buffers and indices.
  41454. this._reconstructedMesh.setIndices(newIndicesArray);
  41455. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  41456. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  41457. if (newUVsData.length > 0)
  41458. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  41459. if (newColorsData.length > 0)
  41460. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  41461. //create submesh
  41462. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  41463. if (submeshIndex > 0) {
  41464. this._reconstructedMesh.subMeshes = [];
  41465. submeshesArray.forEach(function (submesh) {
  41466. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  41467. });
  41468. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  41469. }
  41470. };
  41471. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  41472. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  41473. this._reconstructedMesh.material = this._mesh.material;
  41474. this._reconstructedMesh.parent = this._mesh.parent;
  41475. this._reconstructedMesh.isVisible = false;
  41476. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  41477. };
  41478. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  41479. for (var i = 0; i < vertex1.triangleCount; ++i) {
  41480. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  41481. if (t.deleted)
  41482. continue;
  41483. var s = this.references[vertex1.triangleStart + i].vertexId;
  41484. var v1 = t.vertices[(s + 1) % 3];
  41485. var v2 = t.vertices[(s + 2) % 3];
  41486. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  41487. deletedArray[i] = true;
  41488. delTr.push(t);
  41489. continue;
  41490. }
  41491. var d1 = v1.position.subtract(point);
  41492. d1 = d1.normalize();
  41493. var d2 = v2.position.subtract(point);
  41494. d2 = d2.normalize();
  41495. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  41496. return true;
  41497. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  41498. deletedArray[i] = false;
  41499. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  41500. return true;
  41501. }
  41502. return false;
  41503. };
  41504. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  41505. var newDeleted = deletedTriangles;
  41506. for (var i = 0; i < vertex.triangleCount; ++i) {
  41507. var ref = this.references[vertex.triangleStart + i];
  41508. var t = this.triangles[ref.triangleId];
  41509. if (t.deleted)
  41510. continue;
  41511. if (deletedArray[i] && t.deletePending) {
  41512. t.deleted = true;
  41513. newDeleted++;
  41514. continue;
  41515. }
  41516. t.vertices[ref.vertexId] = origVertex;
  41517. t.isDirty = true;
  41518. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  41519. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  41520. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  41521. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41522. this.references.push(ref);
  41523. }
  41524. return newDeleted;
  41525. };
  41526. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  41527. for (var i = 0; i < this.vertices.length; ++i) {
  41528. var vCount = [];
  41529. var vId = [];
  41530. var v = this.vertices[i];
  41531. var j;
  41532. for (j = 0; j < v.triangleCount; ++j) {
  41533. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  41534. for (var ii = 0; ii < 3; ii++) {
  41535. var ofs = 0;
  41536. var vv = triangle.vertices[ii];
  41537. while (ofs < vCount.length) {
  41538. if (vId[ofs] === vv.id)
  41539. break;
  41540. ++ofs;
  41541. }
  41542. if (ofs === vCount.length) {
  41543. vCount.push(1);
  41544. vId.push(vv.id);
  41545. }
  41546. else {
  41547. vCount[ofs]++;
  41548. }
  41549. }
  41550. }
  41551. for (j = 0; j < vCount.length; ++j) {
  41552. if (vCount[j] === 1) {
  41553. this.vertices[vId[j]].isBorder = true;
  41554. }
  41555. else {
  41556. this.vertices[vId[j]].isBorder = false;
  41557. }
  41558. }
  41559. }
  41560. };
  41561. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  41562. if (identifyBorders === void 0) { identifyBorders = false; }
  41563. var i;
  41564. if (!identifyBorders) {
  41565. var newTrianglesVector = [];
  41566. for (i = 0; i < this.triangles.length; ++i) {
  41567. if (!this.triangles[i].deleted) {
  41568. newTrianglesVector.push(this.triangles[i]);
  41569. }
  41570. }
  41571. this.triangles = newTrianglesVector;
  41572. }
  41573. for (i = 0; i < this.vertices.length; ++i) {
  41574. this.vertices[i].triangleCount = 0;
  41575. this.vertices[i].triangleStart = 0;
  41576. }
  41577. var t;
  41578. var j;
  41579. var v;
  41580. for (i = 0; i < this.triangles.length; ++i) {
  41581. t = this.triangles[i];
  41582. for (j = 0; j < 3; ++j) {
  41583. v = t.vertices[j];
  41584. v.triangleCount++;
  41585. }
  41586. }
  41587. var tStart = 0;
  41588. for (i = 0; i < this.vertices.length; ++i) {
  41589. this.vertices[i].triangleStart = tStart;
  41590. tStart += this.vertices[i].triangleCount;
  41591. this.vertices[i].triangleCount = 0;
  41592. }
  41593. var newReferences = new Array(this.triangles.length * 3);
  41594. for (i = 0; i < this.triangles.length; ++i) {
  41595. t = this.triangles[i];
  41596. for (j = 0; j < 3; ++j) {
  41597. v = t.vertices[j];
  41598. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  41599. v.triangleCount++;
  41600. }
  41601. }
  41602. this.references = newReferences;
  41603. if (identifyBorders) {
  41604. this.identifyBorder();
  41605. }
  41606. };
  41607. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  41608. var x = point.x;
  41609. var y = point.y;
  41610. var z = point.z;
  41611. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  41612. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  41613. };
  41614. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  41615. var q = vertex1.q.add(vertex2.q);
  41616. var border = vertex1.isBorder && vertex2.isBorder;
  41617. var error = 0;
  41618. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  41619. if (qDet !== 0 && !border) {
  41620. if (!pointResult) {
  41621. pointResult = BABYLON.Vector3.Zero();
  41622. }
  41623. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  41624. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  41625. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  41626. error = this.vertexError(q, pointResult);
  41627. }
  41628. else {
  41629. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  41630. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  41631. var error1 = this.vertexError(q, vertex1.position);
  41632. var error2 = this.vertexError(q, vertex2.position);
  41633. var error3 = this.vertexError(q, p3);
  41634. error = Math.min(error1, error2, error3);
  41635. if (error === error1) {
  41636. if (pointResult) {
  41637. pointResult.copyFrom(vertex1.position);
  41638. }
  41639. }
  41640. else if (error === error2) {
  41641. if (pointResult) {
  41642. pointResult.copyFrom(vertex2.position);
  41643. }
  41644. }
  41645. else {
  41646. if (pointResult) {
  41647. pointResult.copyFrom(p3);
  41648. }
  41649. }
  41650. }
  41651. return error;
  41652. };
  41653. return QuadraticErrorSimplification;
  41654. })();
  41655. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  41656. })(BABYLON || (BABYLON = {}));
  41657. var BABYLON;
  41658. (function (BABYLON) {
  41659. var serializedGeometries = [];
  41660. var serializeGeometry = function (geometry, serializationGeometries) {
  41661. if (serializedGeometries[geometry.id]) {
  41662. return;
  41663. }
  41664. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  41665. serializationGeometries.boxes.push(geometry.serialize());
  41666. }
  41667. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  41668. serializationGeometries.spheres.push(geometry.serialize());
  41669. }
  41670. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  41671. serializationGeometries.cylinders.push(geometry.serialize());
  41672. }
  41673. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  41674. serializationGeometries.toruses.push(geometry.serialize());
  41675. }
  41676. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  41677. serializationGeometries.grounds.push(geometry.serialize());
  41678. }
  41679. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  41680. serializationGeometries.planes.push(geometry.serialize());
  41681. }
  41682. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  41683. serializationGeometries.torusKnots.push(geometry.serialize());
  41684. }
  41685. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  41686. throw new Error("Unknown primitive type");
  41687. }
  41688. else {
  41689. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  41690. }
  41691. serializedGeometries[geometry.id] = true;
  41692. };
  41693. var serializeMesh = function (mesh, serializationScene) {
  41694. var serializationObject = {};
  41695. serializationObject.name = mesh.name;
  41696. serializationObject.id = mesh.id;
  41697. if (BABYLON.Tags.HasTags(mesh)) {
  41698. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  41699. }
  41700. serializationObject.position = mesh.position.asArray();
  41701. if (mesh.rotationQuaternion) {
  41702. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  41703. }
  41704. else if (mesh.rotation) {
  41705. serializationObject.rotation = mesh.rotation.asArray();
  41706. }
  41707. serializationObject.scaling = mesh.scaling.asArray();
  41708. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  41709. serializationObject.isEnabled = mesh.isEnabled();
  41710. serializationObject.isVisible = mesh.isVisible;
  41711. serializationObject.infiniteDistance = mesh.infiniteDistance;
  41712. serializationObject.pickable = mesh.isPickable;
  41713. serializationObject.receiveShadows = mesh.receiveShadows;
  41714. serializationObject.billboardMode = mesh.billboardMode;
  41715. serializationObject.visibility = mesh.visibility;
  41716. serializationObject.checkCollisions = mesh.checkCollisions;
  41717. // Parent
  41718. if (mesh.parent) {
  41719. serializationObject.parentId = mesh.parent.id;
  41720. }
  41721. // Geometry
  41722. var geometry = mesh._geometry;
  41723. if (geometry) {
  41724. var geometryId = geometry.id;
  41725. serializationObject.geometryId = geometryId;
  41726. if (!mesh.getScene().getGeometryByID(geometryId)) {
  41727. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  41728. serializeGeometry(geometry, serializationScene.geometries);
  41729. }
  41730. // SubMeshes
  41731. serializationObject.subMeshes = [];
  41732. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41733. var subMesh = mesh.subMeshes[subIndex];
  41734. serializationObject.subMeshes.push({
  41735. materialIndex: subMesh.materialIndex,
  41736. verticesStart: subMesh.verticesStart,
  41737. verticesCount: subMesh.verticesCount,
  41738. indexStart: subMesh.indexStart,
  41739. indexCount: subMesh.indexCount
  41740. });
  41741. }
  41742. }
  41743. // Material
  41744. if (mesh.material) {
  41745. serializationObject.materialId = mesh.material.id;
  41746. }
  41747. else {
  41748. mesh.material = null;
  41749. }
  41750. // Skeleton
  41751. if (mesh.skeleton) {
  41752. serializationObject.skeletonId = mesh.skeleton.id;
  41753. }
  41754. // Physics
  41755. //TODO implement correct serialization for physics impostors.
  41756. if (mesh.getPhysicsImpostor()) {
  41757. serializationObject.physicsMass = mesh.getPhysicsMass();
  41758. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  41759. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  41760. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  41761. }
  41762. // Instances
  41763. serializationObject.instances = [];
  41764. for (var index = 0; index < mesh.instances.length; index++) {
  41765. var instance = mesh.instances[index];
  41766. var serializationInstance = {
  41767. name: instance.name,
  41768. position: instance.position.asArray(),
  41769. scaling: instance.scaling.asArray()
  41770. };
  41771. if (instance.rotationQuaternion) {
  41772. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  41773. }
  41774. else if (instance.rotation) {
  41775. serializationInstance.rotation = instance.rotation.asArray();
  41776. }
  41777. serializationObject.instances.push(serializationInstance);
  41778. // Animations
  41779. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  41780. serializationInstance.ranges = instance.serializeAnimationRanges();
  41781. }
  41782. // Animations
  41783. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  41784. serializationObject.ranges = mesh.serializeAnimationRanges();
  41785. // Layer mask
  41786. serializationObject.layerMask = mesh.layerMask;
  41787. // Action Manager
  41788. if (mesh.actionManager) {
  41789. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  41790. }
  41791. return serializationObject;
  41792. };
  41793. var finalizeSingleMesh = function (mesh, serializationObject) {
  41794. //only works if the mesh is already loaded
  41795. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41796. //serialize material
  41797. if (mesh.material) {
  41798. if (mesh.material instanceof BABYLON.StandardMaterial) {
  41799. serializationObject.materials = serializationObject.materials || [];
  41800. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41801. serializationObject.materials.push(mesh.material.serialize());
  41802. }
  41803. }
  41804. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  41805. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  41806. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41807. serializationObject.multiMaterials.push(mesh.material.serialize());
  41808. }
  41809. }
  41810. }
  41811. //serialize geometry
  41812. var geometry = mesh._geometry;
  41813. if (geometry) {
  41814. if (!serializationObject.geometries) {
  41815. serializationObject.geometries = {};
  41816. serializationObject.geometries.boxes = [];
  41817. serializationObject.geometries.spheres = [];
  41818. serializationObject.geometries.cylinders = [];
  41819. serializationObject.geometries.toruses = [];
  41820. serializationObject.geometries.grounds = [];
  41821. serializationObject.geometries.planes = [];
  41822. serializationObject.geometries.torusKnots = [];
  41823. serializationObject.geometries.vertexData = [];
  41824. }
  41825. serializeGeometry(geometry, serializationObject.geometries);
  41826. }
  41827. // Skeletons
  41828. if (mesh.skeleton) {
  41829. serializationObject.skeletons = serializationObject.skeletons || [];
  41830. serializationObject.skeletons.push(mesh.skeleton.serialize());
  41831. }
  41832. //serialize the actual mesh
  41833. serializationObject.meshes = serializationObject.meshes || [];
  41834. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41835. }
  41836. };
  41837. var SceneSerializer = (function () {
  41838. function SceneSerializer() {
  41839. }
  41840. SceneSerializer.ClearCache = function () {
  41841. serializedGeometries = [];
  41842. };
  41843. SceneSerializer.Serialize = function (scene) {
  41844. var serializationObject = {};
  41845. // Scene
  41846. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  41847. serializationObject.autoClear = scene.autoClear;
  41848. serializationObject.clearColor = scene.clearColor.asArray();
  41849. serializationObject.ambientColor = scene.ambientColor.asArray();
  41850. serializationObject.gravity = scene.gravity.asArray();
  41851. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  41852. serializationObject.workerCollisions = scene.workerCollisions;
  41853. // Fog
  41854. if (scene.fogMode && scene.fogMode !== 0) {
  41855. serializationObject.fogMode = scene.fogMode;
  41856. serializationObject.fogColor = scene.fogColor.asArray();
  41857. serializationObject.fogStart = scene.fogStart;
  41858. serializationObject.fogEnd = scene.fogEnd;
  41859. serializationObject.fogDensity = scene.fogDensity;
  41860. }
  41861. //Physics
  41862. if (scene.isPhysicsEnabled()) {
  41863. serializationObject.physicsEnabled = true;
  41864. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  41865. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  41866. }
  41867. // Lights
  41868. serializationObject.lights = [];
  41869. var index;
  41870. var light;
  41871. for (index = 0; index < scene.lights.length; index++) {
  41872. light = scene.lights[index];
  41873. serializationObject.lights.push(light.serialize());
  41874. }
  41875. // Cameras
  41876. serializationObject.cameras = [];
  41877. for (index = 0; index < scene.cameras.length; index++) {
  41878. var camera = scene.cameras[index];
  41879. serializationObject.cameras.push(camera.serialize());
  41880. }
  41881. if (scene.activeCamera) {
  41882. serializationObject.activeCameraID = scene.activeCamera.id;
  41883. }
  41884. // Animations
  41885. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  41886. // Materials
  41887. serializationObject.materials = [];
  41888. serializationObject.multiMaterials = [];
  41889. var material;
  41890. for (index = 0; index < scene.materials.length; index++) {
  41891. material = scene.materials[index];
  41892. serializationObject.materials.push(material.serialize());
  41893. }
  41894. // MultiMaterials
  41895. serializationObject.multiMaterials = [];
  41896. for (index = 0; index < scene.multiMaterials.length; index++) {
  41897. var multiMaterial = scene.multiMaterials[index];
  41898. serializationObject.multiMaterials.push(multiMaterial.serialize());
  41899. }
  41900. // Skeletons
  41901. serializationObject.skeletons = [];
  41902. for (index = 0; index < scene.skeletons.length; index++) {
  41903. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  41904. }
  41905. // Geometries
  41906. serializationObject.geometries = {};
  41907. serializationObject.geometries.boxes = [];
  41908. serializationObject.geometries.spheres = [];
  41909. serializationObject.geometries.cylinders = [];
  41910. serializationObject.geometries.toruses = [];
  41911. serializationObject.geometries.grounds = [];
  41912. serializationObject.geometries.planes = [];
  41913. serializationObject.geometries.torusKnots = [];
  41914. serializationObject.geometries.vertexData = [];
  41915. serializedGeometries = [];
  41916. var geometries = scene.getGeometries();
  41917. for (index = 0; index < geometries.length; index++) {
  41918. var geometry = geometries[index];
  41919. if (geometry.isReady()) {
  41920. serializeGeometry(geometry, serializationObject.geometries);
  41921. }
  41922. }
  41923. // Meshes
  41924. serializationObject.meshes = [];
  41925. for (index = 0; index < scene.meshes.length; index++) {
  41926. var abstractMesh = scene.meshes[index];
  41927. if (abstractMesh instanceof BABYLON.Mesh) {
  41928. var mesh = abstractMesh;
  41929. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41930. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41931. }
  41932. }
  41933. }
  41934. // Particles Systems
  41935. serializationObject.particleSystems = [];
  41936. for (index = 0; index < scene.particleSystems.length; index++) {
  41937. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  41938. }
  41939. // Lens flares
  41940. serializationObject.lensFlareSystems = [];
  41941. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  41942. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  41943. }
  41944. // Shadows
  41945. serializationObject.shadowGenerators = [];
  41946. for (index = 0; index < scene.lights.length; index++) {
  41947. light = scene.lights[index];
  41948. if (light.getShadowGenerator()) {
  41949. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  41950. }
  41951. }
  41952. // Action Manager
  41953. if (scene.actionManager) {
  41954. serializationObject.actions = scene.actionManager.serialize("scene");
  41955. }
  41956. return serializationObject;
  41957. };
  41958. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  41959. if (withParents === void 0) { withParents = false; }
  41960. if (withChildren === void 0) { withChildren = false; }
  41961. var serializationObject = {};
  41962. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  41963. if (withParents || withChildren) {
  41964. //deliberate for loop! not for each, appended should be processed as well.
  41965. for (var i = 0; i < toSerialize.length; ++i) {
  41966. if (withChildren) {
  41967. toSerialize[i].getDescendants().forEach(function (node) {
  41968. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  41969. toSerialize.push(node);
  41970. }
  41971. });
  41972. }
  41973. //make sure the array doesn't contain the object already
  41974. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  41975. toSerialize.push(toSerialize[i].parent);
  41976. }
  41977. }
  41978. }
  41979. toSerialize.forEach(function (mesh) {
  41980. finalizeSingleMesh(mesh, serializationObject);
  41981. });
  41982. return serializationObject;
  41983. };
  41984. return SceneSerializer;
  41985. })();
  41986. BABYLON.SceneSerializer = SceneSerializer;
  41987. })(BABYLON || (BABYLON = {}));
  41988. var BABYLON;
  41989. (function (BABYLON) {
  41990. // Unique ID when we import meshes from Babylon to CSG
  41991. var currentCSGMeshId = 0;
  41992. // # class Vertex
  41993. // Represents a vertex of a polygon. Use your own vertex class instead of this
  41994. // one to provide additional features like texture coordinates and vertex
  41995. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  41996. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  41997. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  41998. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  41999. // is not used anywhere else.
  42000. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  42001. var Vertex = (function () {
  42002. function Vertex(pos, normal, uv) {
  42003. this.pos = pos;
  42004. this.normal = normal;
  42005. this.uv = uv;
  42006. }
  42007. Vertex.prototype.clone = function () {
  42008. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  42009. };
  42010. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  42011. // orientation of a polygon is flipped.
  42012. Vertex.prototype.flip = function () {
  42013. this.normal = this.normal.scale(-1);
  42014. };
  42015. // Create a new vertex between this vertex and `other` by linearly
  42016. // interpolating all properties using a parameter of `t`. Subclasses should
  42017. // override this to interpolate additional properties.
  42018. Vertex.prototype.interpolate = function (other, t) {
  42019. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  42020. };
  42021. return Vertex;
  42022. })();
  42023. // # class Plane
  42024. // Represents a plane in 3D space.
  42025. var Plane = (function () {
  42026. function Plane(normal, w) {
  42027. this.normal = normal;
  42028. this.w = w;
  42029. }
  42030. Plane.FromPoints = function (a, b, c) {
  42031. var v0 = c.subtract(a);
  42032. var v1 = b.subtract(a);
  42033. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  42034. return null;
  42035. }
  42036. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  42037. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  42038. };
  42039. Plane.prototype.clone = function () {
  42040. return new Plane(this.normal.clone(), this.w);
  42041. };
  42042. Plane.prototype.flip = function () {
  42043. this.normal.scaleInPlace(-1);
  42044. this.w = -this.w;
  42045. };
  42046. // Split `polygon` by this plane if needed, then put the polygon or polygon
  42047. // fragments in the appropriate lists. Coplanar polygons go into either
  42048. // `coplanarFront` or `coplanarBack` depending on their orientation with
  42049. // respect to this plane. Polygons in front or in back of this plane go into
  42050. // either `front` or `back`.
  42051. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  42052. var COPLANAR = 0;
  42053. var FRONT = 1;
  42054. var BACK = 2;
  42055. var SPANNING = 3;
  42056. // Classify each point as well as the entire polygon into one of the above
  42057. // four classes.
  42058. var polygonType = 0;
  42059. var types = [];
  42060. var i;
  42061. var t;
  42062. for (i = 0; i < polygon.vertices.length; i++) {
  42063. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  42064. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  42065. polygonType |= type;
  42066. types.push(type);
  42067. }
  42068. // Put the polygon in the correct list, splitting it when necessary.
  42069. switch (polygonType) {
  42070. case COPLANAR:
  42071. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  42072. break;
  42073. case FRONT:
  42074. front.push(polygon);
  42075. break;
  42076. case BACK:
  42077. back.push(polygon);
  42078. break;
  42079. case SPANNING:
  42080. var f = [], b = [];
  42081. for (i = 0; i < polygon.vertices.length; i++) {
  42082. var j = (i + 1) % polygon.vertices.length;
  42083. var ti = types[i], tj = types[j];
  42084. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  42085. if (ti !== BACK)
  42086. f.push(vi);
  42087. if (ti !== FRONT)
  42088. b.push(ti !== BACK ? vi.clone() : vi);
  42089. if ((ti | tj) === SPANNING) {
  42090. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  42091. var v = vi.interpolate(vj, t);
  42092. f.push(v);
  42093. b.push(v.clone());
  42094. }
  42095. }
  42096. var poly;
  42097. if (f.length >= 3) {
  42098. poly = new Polygon(f, polygon.shared);
  42099. if (poly.plane)
  42100. front.push(poly);
  42101. }
  42102. if (b.length >= 3) {
  42103. poly = new Polygon(b, polygon.shared);
  42104. if (poly.plane)
  42105. back.push(poly);
  42106. }
  42107. break;
  42108. }
  42109. };
  42110. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  42111. // point is on the plane.
  42112. Plane.EPSILON = 1e-5;
  42113. return Plane;
  42114. })();
  42115. // # class Polygon
  42116. // Represents a convex polygon. The vertices used to initialize a polygon must
  42117. // be coplanar and form a convex loop.
  42118. //
  42119. // Each convex polygon has a `shared` property, which is shared between all
  42120. // polygons that are clones of each other or were split from the same polygon.
  42121. // This can be used to define per-polygon properties (such as surface color).
  42122. var Polygon = (function () {
  42123. function Polygon(vertices, shared) {
  42124. this.vertices = vertices;
  42125. this.shared = shared;
  42126. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  42127. }
  42128. Polygon.prototype.clone = function () {
  42129. var vertices = this.vertices.map(function (v) { return v.clone(); });
  42130. return new Polygon(vertices, this.shared);
  42131. };
  42132. Polygon.prototype.flip = function () {
  42133. this.vertices.reverse().map(function (v) { v.flip(); });
  42134. this.plane.flip();
  42135. };
  42136. return Polygon;
  42137. })();
  42138. // # class Node
  42139. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  42140. // by picking a polygon to split along. That polygon (and all other coplanar
  42141. // polygons) are added directly to that node and the other polygons are added to
  42142. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  42143. // no distinction between internal and leaf nodes.
  42144. var Node = (function () {
  42145. function Node(polygons) {
  42146. this.plane = null;
  42147. this.front = null;
  42148. this.back = null;
  42149. this.polygons = [];
  42150. if (polygons) {
  42151. this.build(polygons);
  42152. }
  42153. }
  42154. Node.prototype.clone = function () {
  42155. var node = new Node();
  42156. node.plane = this.plane && this.plane.clone();
  42157. node.front = this.front && this.front.clone();
  42158. node.back = this.back && this.back.clone();
  42159. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  42160. return node;
  42161. };
  42162. // Convert solid space to empty space and empty space to solid space.
  42163. Node.prototype.invert = function () {
  42164. for (var i = 0; i < this.polygons.length; i++) {
  42165. this.polygons[i].flip();
  42166. }
  42167. if (this.plane) {
  42168. this.plane.flip();
  42169. }
  42170. if (this.front) {
  42171. this.front.invert();
  42172. }
  42173. if (this.back) {
  42174. this.back.invert();
  42175. }
  42176. var temp = this.front;
  42177. this.front = this.back;
  42178. this.back = temp;
  42179. };
  42180. // Recursively remove all polygons in `polygons` that are inside this BSP
  42181. // tree.
  42182. Node.prototype.clipPolygons = function (polygons) {
  42183. if (!this.plane)
  42184. return polygons.slice();
  42185. var front = [], back = [];
  42186. for (var i = 0; i < polygons.length; i++) {
  42187. this.plane.splitPolygon(polygons[i], front, back, front, back);
  42188. }
  42189. if (this.front) {
  42190. front = this.front.clipPolygons(front);
  42191. }
  42192. if (this.back) {
  42193. back = this.back.clipPolygons(back);
  42194. }
  42195. else {
  42196. back = [];
  42197. }
  42198. return front.concat(back);
  42199. };
  42200. // Remove all polygons in this BSP tree that are inside the other BSP tree
  42201. // `bsp`.
  42202. Node.prototype.clipTo = function (bsp) {
  42203. this.polygons = bsp.clipPolygons(this.polygons);
  42204. if (this.front)
  42205. this.front.clipTo(bsp);
  42206. if (this.back)
  42207. this.back.clipTo(bsp);
  42208. };
  42209. // Return a list of all polygons in this BSP tree.
  42210. Node.prototype.allPolygons = function () {
  42211. var polygons = this.polygons.slice();
  42212. if (this.front)
  42213. polygons = polygons.concat(this.front.allPolygons());
  42214. if (this.back)
  42215. polygons = polygons.concat(this.back.allPolygons());
  42216. return polygons;
  42217. };
  42218. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  42219. // new polygons are filtered down to the bottom of the tree and become new
  42220. // nodes there. Each set of polygons is partitioned using the first polygon
  42221. // (no heuristic is used to pick a good split).
  42222. Node.prototype.build = function (polygons) {
  42223. if (!polygons.length)
  42224. return;
  42225. if (!this.plane)
  42226. this.plane = polygons[0].plane.clone();
  42227. var front = [], back = [];
  42228. for (var i = 0; i < polygons.length; i++) {
  42229. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  42230. }
  42231. if (front.length) {
  42232. if (!this.front)
  42233. this.front = new Node();
  42234. this.front.build(front);
  42235. }
  42236. if (back.length) {
  42237. if (!this.back)
  42238. this.back = new Node();
  42239. this.back.build(back);
  42240. }
  42241. };
  42242. return Node;
  42243. })();
  42244. var CSG = (function () {
  42245. function CSG() {
  42246. this.polygons = new Array();
  42247. }
  42248. // Convert BABYLON.Mesh to BABYLON.CSG
  42249. CSG.FromMesh = function (mesh) {
  42250. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  42251. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  42252. if (mesh instanceof BABYLON.Mesh) {
  42253. mesh.computeWorldMatrix(true);
  42254. matrix = mesh.getWorldMatrix();
  42255. meshPosition = mesh.position.clone();
  42256. meshRotation = mesh.rotation.clone();
  42257. if (mesh.rotationQuaternion) {
  42258. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  42259. }
  42260. meshScaling = mesh.scaling.clone();
  42261. }
  42262. else {
  42263. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  42264. }
  42265. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42266. var subMeshes = mesh.subMeshes;
  42267. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  42268. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  42269. vertices = [];
  42270. for (var j = 0; j < 3; j++) {
  42271. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  42272. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  42273. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  42274. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  42275. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  42276. vertex = new Vertex(position, normal, uv);
  42277. vertices.push(vertex);
  42278. }
  42279. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  42280. // To handle the case of degenerated triangle
  42281. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  42282. if (polygon.plane)
  42283. polygons.push(polygon);
  42284. }
  42285. }
  42286. var csg = CSG.FromPolygons(polygons);
  42287. csg.matrix = matrix;
  42288. csg.position = meshPosition;
  42289. csg.rotation = meshRotation;
  42290. csg.scaling = meshScaling;
  42291. csg.rotationQuaternion = meshRotationQuaternion;
  42292. currentCSGMeshId++;
  42293. return csg;
  42294. };
  42295. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  42296. CSG.FromPolygons = function (polygons) {
  42297. var csg = new CSG();
  42298. csg.polygons = polygons;
  42299. return csg;
  42300. };
  42301. CSG.prototype.clone = function () {
  42302. var csg = new CSG();
  42303. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  42304. csg.copyTransformAttributes(this);
  42305. return csg;
  42306. };
  42307. CSG.prototype.toPolygons = function () {
  42308. return this.polygons;
  42309. };
  42310. CSG.prototype.union = function (csg) {
  42311. var a = new Node(this.clone().polygons);
  42312. var b = new Node(csg.clone().polygons);
  42313. a.clipTo(b);
  42314. b.clipTo(a);
  42315. b.invert();
  42316. b.clipTo(a);
  42317. b.invert();
  42318. a.build(b.allPolygons());
  42319. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42320. };
  42321. CSG.prototype.unionInPlace = function (csg) {
  42322. var a = new Node(this.polygons);
  42323. var b = new Node(csg.polygons);
  42324. a.clipTo(b);
  42325. b.clipTo(a);
  42326. b.invert();
  42327. b.clipTo(a);
  42328. b.invert();
  42329. a.build(b.allPolygons());
  42330. this.polygons = a.allPolygons();
  42331. };
  42332. CSG.prototype.subtract = function (csg) {
  42333. var a = new Node(this.clone().polygons);
  42334. var b = new Node(csg.clone().polygons);
  42335. a.invert();
  42336. a.clipTo(b);
  42337. b.clipTo(a);
  42338. b.invert();
  42339. b.clipTo(a);
  42340. b.invert();
  42341. a.build(b.allPolygons());
  42342. a.invert();
  42343. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42344. };
  42345. CSG.prototype.subtractInPlace = function (csg) {
  42346. var a = new Node(this.polygons);
  42347. var b = new Node(csg.polygons);
  42348. a.invert();
  42349. a.clipTo(b);
  42350. b.clipTo(a);
  42351. b.invert();
  42352. b.clipTo(a);
  42353. b.invert();
  42354. a.build(b.allPolygons());
  42355. a.invert();
  42356. this.polygons = a.allPolygons();
  42357. };
  42358. CSG.prototype.intersect = function (csg) {
  42359. var a = new Node(this.clone().polygons);
  42360. var b = new Node(csg.clone().polygons);
  42361. a.invert();
  42362. b.clipTo(a);
  42363. b.invert();
  42364. a.clipTo(b);
  42365. b.clipTo(a);
  42366. a.build(b.allPolygons());
  42367. a.invert();
  42368. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42369. };
  42370. CSG.prototype.intersectInPlace = function (csg) {
  42371. var a = new Node(this.polygons);
  42372. var b = new Node(csg.polygons);
  42373. a.invert();
  42374. b.clipTo(a);
  42375. b.invert();
  42376. a.clipTo(b);
  42377. b.clipTo(a);
  42378. a.build(b.allPolygons());
  42379. a.invert();
  42380. this.polygons = a.allPolygons();
  42381. };
  42382. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  42383. // not modified.
  42384. CSG.prototype.inverse = function () {
  42385. var csg = this.clone();
  42386. csg.inverseInPlace();
  42387. return csg;
  42388. };
  42389. CSG.prototype.inverseInPlace = function () {
  42390. this.polygons.map(function (p) { p.flip(); });
  42391. };
  42392. // This is used to keep meshes transformations so they can be restored
  42393. // when we build back a Babylon Mesh
  42394. // NB : All CSG operations are performed in world coordinates
  42395. CSG.prototype.copyTransformAttributes = function (csg) {
  42396. this.matrix = csg.matrix;
  42397. this.position = csg.position;
  42398. this.rotation = csg.rotation;
  42399. this.scaling = csg.scaling;
  42400. this.rotationQuaternion = csg.rotationQuaternion;
  42401. return this;
  42402. };
  42403. // Build Raw mesh from CSG
  42404. // Coordinates here are in world space
  42405. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  42406. var matrix = this.matrix.clone();
  42407. matrix.invert();
  42408. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  42409. if (keepSubMeshes) {
  42410. // Sort Polygons, since subMeshes are indices range
  42411. polygons.sort(function (a, b) {
  42412. if (a.shared.meshId === b.shared.meshId) {
  42413. return a.shared.subMeshId - b.shared.subMeshId;
  42414. }
  42415. else {
  42416. return a.shared.meshId - b.shared.meshId;
  42417. }
  42418. });
  42419. }
  42420. for (var i = 0, il = polygons.length; i < il; i++) {
  42421. polygon = polygons[i];
  42422. // Building SubMeshes
  42423. if (!subMesh_dict[polygon.shared.meshId]) {
  42424. subMesh_dict[polygon.shared.meshId] = {};
  42425. }
  42426. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  42427. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  42428. indexStart: +Infinity,
  42429. indexEnd: -Infinity,
  42430. materialIndex: polygon.shared.materialIndex
  42431. };
  42432. }
  42433. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  42434. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  42435. polygonIndices[0] = 0;
  42436. polygonIndices[1] = j - 1;
  42437. polygonIndices[2] = j;
  42438. for (var k = 0; k < 3; k++) {
  42439. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  42440. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  42441. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  42442. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  42443. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  42444. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  42445. // Check if 2 points can be merged
  42446. if (!(typeof vertex_idx !== 'undefined' &&
  42447. normals[vertex_idx * 3] === localNormal.x &&
  42448. normals[vertex_idx * 3 + 1] === localNormal.y &&
  42449. normals[vertex_idx * 3 + 2] === localNormal.z &&
  42450. uvs[vertex_idx * 2] === uv.x &&
  42451. uvs[vertex_idx * 2 + 1] === uv.y)) {
  42452. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  42453. uvs.push(uv.x, uv.y);
  42454. normals.push(normal.x, normal.y, normal.z);
  42455. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  42456. }
  42457. indices.push(vertex_idx);
  42458. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  42459. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  42460. currentIndex++;
  42461. }
  42462. }
  42463. }
  42464. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  42465. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  42466. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  42467. mesh.setIndices(indices);
  42468. if (keepSubMeshes) {
  42469. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  42470. var materialIndexOffset = 0, materialMaxIndex;
  42471. mesh.subMeshes = new Array();
  42472. for (var m in subMesh_dict) {
  42473. materialMaxIndex = -1;
  42474. for (var sm in subMesh_dict[m]) {
  42475. subMesh_obj = subMesh_dict[m][sm];
  42476. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  42477. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  42478. }
  42479. materialIndexOffset += ++materialMaxIndex;
  42480. }
  42481. }
  42482. return mesh;
  42483. };
  42484. // Build Mesh from CSG taking material and transforms into account
  42485. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  42486. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  42487. mesh.material = material;
  42488. mesh.position.copyFrom(this.position);
  42489. mesh.rotation.copyFrom(this.rotation);
  42490. if (this.rotationQuaternion) {
  42491. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  42492. }
  42493. mesh.scaling.copyFrom(this.scaling);
  42494. mesh.computeWorldMatrix(true);
  42495. return mesh;
  42496. };
  42497. return CSG;
  42498. })();
  42499. BABYLON.CSG = CSG;
  42500. })(BABYLON || (BABYLON = {}));
  42501. var BABYLON;
  42502. (function (BABYLON) {
  42503. var VRDistortionCorrectionPostProcess = (function (_super) {
  42504. __extends(VRDistortionCorrectionPostProcess, _super);
  42505. //ANY
  42506. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  42507. var _this = this;
  42508. _super.call(this, name, "vrDistortionCorrection", [
  42509. 'LensCenter',
  42510. 'Scale',
  42511. 'ScaleIn',
  42512. 'HmdWarpParam'
  42513. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  42514. this._isRightEye = isRightEye;
  42515. this._distortionFactors = vrMetrics.distortionK;
  42516. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  42517. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  42518. this.onSizeChangedObservable.add(function () {
  42519. _this.aspectRatio = _this.width * .5 / _this.height;
  42520. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  42521. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  42522. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  42523. });
  42524. this.onApplyObservable.add(function (effect) {
  42525. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  42526. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  42527. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  42528. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  42529. });
  42530. }
  42531. return VRDistortionCorrectionPostProcess;
  42532. })(BABYLON.PostProcess);
  42533. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  42534. })(BABYLON || (BABYLON = {}));
  42535. // Mainly based on these 2 articles :
  42536. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  42537. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  42538. var BABYLON;
  42539. (function (BABYLON) {
  42540. (function (JoystickAxis) {
  42541. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  42542. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  42543. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  42544. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  42545. var JoystickAxis = BABYLON.JoystickAxis;
  42546. var VirtualJoystick = (function () {
  42547. function VirtualJoystick(leftJoystick) {
  42548. var _this = this;
  42549. if (leftJoystick) {
  42550. this._leftJoystick = true;
  42551. }
  42552. else {
  42553. this._leftJoystick = false;
  42554. }
  42555. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  42556. VirtualJoystick._globalJoystickIndex++;
  42557. // By default left & right arrow keys are moving the X
  42558. // and up & down keys are moving the Y
  42559. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42560. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42561. this.reverseLeftRight = false;
  42562. this.reverseUpDown = false;
  42563. // collections of pointers
  42564. this._touches = new BABYLON.StringDictionary();
  42565. this.deltaPosition = BABYLON.Vector3.Zero();
  42566. this._joystickSensibility = 25;
  42567. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42568. this._rotationSpeed = 25;
  42569. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  42570. this._rotateOnAxisRelativeToMesh = false;
  42571. this._onResize = function (evt) {
  42572. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42573. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42574. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  42575. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  42576. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  42577. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  42578. };
  42579. // injecting a canvas element on top of the canvas 3D game
  42580. if (!VirtualJoystick.vjCanvas) {
  42581. window.addEventListener("resize", this._onResize, false);
  42582. VirtualJoystick.vjCanvas = document.createElement("canvas");
  42583. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42584. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42585. VirtualJoystick.vjCanvas.width = window.innerWidth;
  42586. VirtualJoystick.vjCanvas.height = window.innerHeight;
  42587. VirtualJoystick.vjCanvas.style.width = "100%";
  42588. VirtualJoystick.vjCanvas.style.height = "100%";
  42589. VirtualJoystick.vjCanvas.style.position = "absolute";
  42590. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  42591. VirtualJoystick.vjCanvas.style.top = "0px";
  42592. VirtualJoystick.vjCanvas.style.left = "0px";
  42593. VirtualJoystick.vjCanvas.style.zIndex = "5";
  42594. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  42595. // Support for jQuery PEP polyfill
  42596. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  42597. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  42598. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  42599. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42600. document.body.appendChild(VirtualJoystick.vjCanvas);
  42601. }
  42602. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  42603. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  42604. this.pressed = false;
  42605. // default joystick color
  42606. this._joystickColor = "cyan";
  42607. this._joystickPointerID = -1;
  42608. // current joystick position
  42609. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  42610. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  42611. // origin joystick position
  42612. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  42613. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  42614. this._onPointerDownHandlerRef = function (evt) {
  42615. _this._onPointerDown(evt);
  42616. };
  42617. this._onPointerMoveHandlerRef = function (evt) {
  42618. _this._onPointerMove(evt);
  42619. };
  42620. this._onPointerOutHandlerRef = function (evt) {
  42621. _this._onPointerUp(evt);
  42622. };
  42623. this._onPointerUpHandlerRef = function (evt) {
  42624. _this._onPointerUp(evt);
  42625. };
  42626. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  42627. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  42628. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  42629. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  42630. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  42631. evt.preventDefault(); // Disables system menu
  42632. }, false);
  42633. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42634. }
  42635. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  42636. this._joystickSensibility = newJoystickSensibility;
  42637. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42638. };
  42639. VirtualJoystick.prototype._onPointerDown = function (e) {
  42640. var positionOnScreenCondition;
  42641. e.preventDefault();
  42642. if (this._leftJoystick === true) {
  42643. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  42644. }
  42645. else {
  42646. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  42647. }
  42648. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  42649. // First contact will be dedicated to the virtual joystick
  42650. this._joystickPointerID = e.pointerId;
  42651. this._joystickPointerStartPos.x = e.clientX;
  42652. this._joystickPointerStartPos.y = e.clientY;
  42653. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  42654. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  42655. this._deltaJoystickVector.x = 0;
  42656. this._deltaJoystickVector.y = 0;
  42657. this.pressed = true;
  42658. this._touches.add(e.pointerId.toString(), e);
  42659. }
  42660. else {
  42661. // You can only trigger the action buttons with a joystick declared
  42662. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  42663. this._action();
  42664. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  42665. }
  42666. }
  42667. };
  42668. VirtualJoystick.prototype._onPointerMove = function (e) {
  42669. // If the current pointer is the one associated to the joystick (first touch contact)
  42670. if (this._joystickPointerID == e.pointerId) {
  42671. this._joystickPointerPos.x = e.clientX;
  42672. this._joystickPointerPos.y = e.clientY;
  42673. this._deltaJoystickVector = this._joystickPointerPos.clone();
  42674. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  42675. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  42676. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  42677. switch (this._axisTargetedByLeftAndRight) {
  42678. case JoystickAxis.X:
  42679. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  42680. break;
  42681. case JoystickAxis.Y:
  42682. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  42683. break;
  42684. case JoystickAxis.Z:
  42685. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  42686. break;
  42687. }
  42688. var directionUpDown = this.reverseUpDown ? 1 : -1;
  42689. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  42690. switch (this._axisTargetedByUpAndDown) {
  42691. case JoystickAxis.X:
  42692. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  42693. break;
  42694. case JoystickAxis.Y:
  42695. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  42696. break;
  42697. case JoystickAxis.Z:
  42698. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  42699. break;
  42700. }
  42701. }
  42702. else {
  42703. var data = this._touches.get(e.pointerId.toString());
  42704. if (data) {
  42705. data.x = e.clientX;
  42706. data.y = e.clientY;
  42707. }
  42708. }
  42709. };
  42710. VirtualJoystick.prototype._onPointerUp = function (e) {
  42711. if (this._joystickPointerID == e.pointerId) {
  42712. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  42713. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  42714. this._joystickPointerID = -1;
  42715. this.pressed = false;
  42716. }
  42717. else {
  42718. var touch = this._touches.get(e.pointerId.toString());
  42719. if (touch) {
  42720. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42721. }
  42722. }
  42723. this._deltaJoystickVector.x = 0;
  42724. this._deltaJoystickVector.y = 0;
  42725. this._touches.remove(e.pointerId.toString());
  42726. };
  42727. /**
  42728. * Change the color of the virtual joystick
  42729. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  42730. */
  42731. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  42732. this._joystickColor = newColor;
  42733. };
  42734. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  42735. this._action = action;
  42736. };
  42737. // Define which axis you'd like to control for left & right
  42738. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  42739. switch (axis) {
  42740. case JoystickAxis.X:
  42741. case JoystickAxis.Y:
  42742. case JoystickAxis.Z:
  42743. this._axisTargetedByLeftAndRight = axis;
  42744. break;
  42745. default:
  42746. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42747. break;
  42748. }
  42749. };
  42750. // Define which axis you'd like to control for up & down
  42751. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  42752. switch (axis) {
  42753. case JoystickAxis.X:
  42754. case JoystickAxis.Y:
  42755. case JoystickAxis.Z:
  42756. this._axisTargetedByUpAndDown = axis;
  42757. break;
  42758. default:
  42759. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42760. break;
  42761. }
  42762. };
  42763. VirtualJoystick.prototype._clearCanvas = function () {
  42764. if (this._leftJoystick) {
  42765. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  42766. }
  42767. else {
  42768. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  42769. }
  42770. };
  42771. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  42772. var _this = this;
  42773. if (this.pressed) {
  42774. this._touches.forEach(function (touch) {
  42775. if (touch.pointerId === _this._joystickPointerID) {
  42776. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  42777. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  42778. VirtualJoystick.vjCanvasContext.beginPath();
  42779. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42780. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42781. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  42782. VirtualJoystick.vjCanvasContext.stroke();
  42783. VirtualJoystick.vjCanvasContext.closePath();
  42784. VirtualJoystick.vjCanvasContext.beginPath();
  42785. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42786. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42787. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  42788. VirtualJoystick.vjCanvasContext.stroke();
  42789. VirtualJoystick.vjCanvasContext.closePath();
  42790. VirtualJoystick.vjCanvasContext.beginPath();
  42791. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42792. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  42793. VirtualJoystick.vjCanvasContext.stroke();
  42794. VirtualJoystick.vjCanvasContext.closePath();
  42795. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  42796. }
  42797. else {
  42798. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42799. VirtualJoystick.vjCanvasContext.beginPath();
  42800. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  42801. VirtualJoystick.vjCanvasContext.beginPath();
  42802. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  42803. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42804. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  42805. VirtualJoystick.vjCanvasContext.stroke();
  42806. VirtualJoystick.vjCanvasContext.closePath();
  42807. touch.prevX = touch.x;
  42808. touch.prevY = touch.y;
  42809. }
  42810. ;
  42811. });
  42812. }
  42813. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42814. };
  42815. VirtualJoystick.prototype.releaseCanvas = function () {
  42816. if (VirtualJoystick.vjCanvas) {
  42817. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  42818. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  42819. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  42820. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  42821. window.removeEventListener("resize", this._onResize);
  42822. document.body.removeChild(VirtualJoystick.vjCanvas);
  42823. VirtualJoystick.vjCanvas = null;
  42824. }
  42825. };
  42826. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  42827. VirtualJoystick._globalJoystickIndex = 0;
  42828. return VirtualJoystick;
  42829. })();
  42830. BABYLON.VirtualJoystick = VirtualJoystick;
  42831. })(BABYLON || (BABYLON = {}));
  42832. var BABYLON;
  42833. (function (BABYLON) {
  42834. // We're mainly based on the logic defined into the FreeCamera code
  42835. var VirtualJoysticksCamera = (function (_super) {
  42836. __extends(VirtualJoysticksCamera, _super);
  42837. function VirtualJoysticksCamera(name, position, scene) {
  42838. _super.call(this, name, position, scene);
  42839. this.inputs.addVirtualJoystick();
  42840. }
  42841. return VirtualJoysticksCamera;
  42842. })(BABYLON.FreeCamera);
  42843. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  42844. })(BABYLON || (BABYLON = {}));
  42845. var BABYLON;
  42846. (function (BABYLON) {
  42847. var FreeCameraVirtualJoystickInput = (function () {
  42848. function FreeCameraVirtualJoystickInput() {
  42849. }
  42850. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  42851. return this._leftjoystick;
  42852. };
  42853. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  42854. return this._rightjoystick;
  42855. };
  42856. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  42857. if (this._leftjoystick) {
  42858. var camera = this.camera;
  42859. var speed = camera._computeLocalCameraSpeed() * 50;
  42860. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  42861. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  42862. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  42863. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  42864. if (!this._leftjoystick.pressed) {
  42865. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  42866. }
  42867. if (!this._rightjoystick.pressed) {
  42868. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  42869. }
  42870. }
  42871. };
  42872. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  42873. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  42874. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  42875. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  42876. this._leftjoystick.setJoystickSensibility(0.15);
  42877. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  42878. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  42879. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  42880. this._rightjoystick.reverseUpDown = true;
  42881. this._rightjoystick.setJoystickSensibility(0.05);
  42882. this._rightjoystick.setJoystickColor("yellow");
  42883. };
  42884. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  42885. this._leftjoystick.releaseCanvas();
  42886. this._rightjoystick.releaseCanvas();
  42887. };
  42888. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  42889. return "FreeCameraVirtualJoystickInput";
  42890. };
  42891. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  42892. return "virtualJoystick";
  42893. };
  42894. return FreeCameraVirtualJoystickInput;
  42895. })();
  42896. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  42897. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  42898. })(BABYLON || (BABYLON = {}));
  42899. var BABYLON;
  42900. (function (BABYLON) {
  42901. var AnaglyphPostProcess = (function (_super) {
  42902. __extends(AnaglyphPostProcess, _super);
  42903. function AnaglyphPostProcess(name, ratio, rigCameras, samplingMode, engine, reusable) {
  42904. var _this = this;
  42905. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, rigCameras[1], samplingMode, engine, reusable);
  42906. this._passedProcess = rigCameras[0]._rigPostProcess;
  42907. this.onApplyObservable.add(function (effect) {
  42908. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  42909. });
  42910. }
  42911. return AnaglyphPostProcess;
  42912. })(BABYLON.PostProcess);
  42913. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  42914. })(BABYLON || (BABYLON = {}));
  42915. var BABYLON;
  42916. (function (BABYLON) {
  42917. var OutlineRenderer = (function () {
  42918. function OutlineRenderer(scene) {
  42919. this._scene = scene;
  42920. }
  42921. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  42922. var _this = this;
  42923. if (useOverlay === void 0) { useOverlay = false; }
  42924. var scene = this._scene;
  42925. var engine = this._scene.getEngine();
  42926. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  42927. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  42928. return;
  42929. }
  42930. var mesh = subMesh.getRenderingMesh();
  42931. var material = subMesh.getMaterial();
  42932. engine.enableEffect(this._effect);
  42933. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  42934. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  42935. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  42936. // Bones
  42937. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42938. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  42939. }
  42940. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  42941. // Alpha test
  42942. if (material && material.needAlphaTesting()) {
  42943. var alphaTexture = material.getAlphaTestTexture();
  42944. this._effect.setTexture("diffuseSampler", alphaTexture);
  42945. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  42946. }
  42947. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  42948. };
  42949. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  42950. var defines = [];
  42951. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  42952. var mesh = subMesh.getMesh();
  42953. var material = subMesh.getMaterial();
  42954. // Alpha test
  42955. if (material && material.needAlphaTesting()) {
  42956. defines.push("#define ALPHATEST");
  42957. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42958. attribs.push(BABYLON.VertexBuffer.UVKind);
  42959. defines.push("#define UV1");
  42960. }
  42961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42962. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42963. defines.push("#define UV2");
  42964. }
  42965. }
  42966. // Bones
  42967. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42970. if (mesh.numBoneInfluencers > 4) {
  42971. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42972. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42973. }
  42974. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42975. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42976. }
  42977. else {
  42978. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42979. }
  42980. // Instances
  42981. if (useInstances) {
  42982. defines.push("#define INSTANCES");
  42983. attribs.push("world0");
  42984. attribs.push("world1");
  42985. attribs.push("world2");
  42986. attribs.push("world3");
  42987. }
  42988. // Get correct effect
  42989. var join = defines.join("\n");
  42990. if (this._cachedDefines !== join) {
  42991. this._cachedDefines = join;
  42992. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  42993. }
  42994. return this._effect.isReady();
  42995. };
  42996. return OutlineRenderer;
  42997. })();
  42998. BABYLON.OutlineRenderer = OutlineRenderer;
  42999. })(BABYLON || (BABYLON = {}));
  43000. var BABYLON;
  43001. (function (BABYLON) {
  43002. var MeshAssetTask = (function () {
  43003. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  43004. this.name = name;
  43005. this.meshesNames = meshesNames;
  43006. this.rootUrl = rootUrl;
  43007. this.sceneFilename = sceneFilename;
  43008. this.isCompleted = false;
  43009. }
  43010. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43011. var _this = this;
  43012. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  43013. _this.loadedMeshes = meshes;
  43014. _this.loadedParticleSystems = particleSystems;
  43015. _this.loadedSkeletons = skeletons;
  43016. _this.isCompleted = true;
  43017. if (_this.onSuccess) {
  43018. _this.onSuccess(_this);
  43019. }
  43020. onSuccess();
  43021. }, null, function () {
  43022. if (_this.onError) {
  43023. _this.onError(_this);
  43024. }
  43025. onError();
  43026. });
  43027. };
  43028. return MeshAssetTask;
  43029. })();
  43030. BABYLON.MeshAssetTask = MeshAssetTask;
  43031. var TextFileAssetTask = (function () {
  43032. function TextFileAssetTask(name, url) {
  43033. this.name = name;
  43034. this.url = url;
  43035. this.isCompleted = false;
  43036. }
  43037. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43038. var _this = this;
  43039. BABYLON.Tools.LoadFile(this.url, function (data) {
  43040. _this.text = data;
  43041. _this.isCompleted = true;
  43042. if (_this.onSuccess) {
  43043. _this.onSuccess(_this);
  43044. }
  43045. onSuccess();
  43046. }, null, scene.database, false, function () {
  43047. if (_this.onError) {
  43048. _this.onError(_this);
  43049. }
  43050. onError();
  43051. });
  43052. };
  43053. return TextFileAssetTask;
  43054. })();
  43055. BABYLON.TextFileAssetTask = TextFileAssetTask;
  43056. var BinaryFileAssetTask = (function () {
  43057. function BinaryFileAssetTask(name, url) {
  43058. this.name = name;
  43059. this.url = url;
  43060. this.isCompleted = false;
  43061. }
  43062. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43063. var _this = this;
  43064. BABYLON.Tools.LoadFile(this.url, function (data) {
  43065. _this.data = data;
  43066. _this.isCompleted = true;
  43067. if (_this.onSuccess) {
  43068. _this.onSuccess(_this);
  43069. }
  43070. onSuccess();
  43071. }, null, scene.database, true, function () {
  43072. if (_this.onError) {
  43073. _this.onError(_this);
  43074. }
  43075. onError();
  43076. });
  43077. };
  43078. return BinaryFileAssetTask;
  43079. })();
  43080. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  43081. var ImageAssetTask = (function () {
  43082. function ImageAssetTask(name, url) {
  43083. this.name = name;
  43084. this.url = url;
  43085. this.isCompleted = false;
  43086. }
  43087. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43088. var _this = this;
  43089. var img = new Image();
  43090. img.onload = function () {
  43091. _this.image = img;
  43092. _this.isCompleted = true;
  43093. if (_this.onSuccess) {
  43094. _this.onSuccess(_this);
  43095. }
  43096. onSuccess();
  43097. };
  43098. img.onerror = function () {
  43099. if (_this.onError) {
  43100. _this.onError(_this);
  43101. }
  43102. onError();
  43103. };
  43104. img.src = this.url;
  43105. };
  43106. return ImageAssetTask;
  43107. })();
  43108. BABYLON.ImageAssetTask = ImageAssetTask;
  43109. var TextureAssetTask = (function () {
  43110. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  43111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43112. this.name = name;
  43113. this.url = url;
  43114. this.noMipmap = noMipmap;
  43115. this.invertY = invertY;
  43116. this.samplingMode = samplingMode;
  43117. this.isCompleted = false;
  43118. }
  43119. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43120. var _this = this;
  43121. var onload = function () {
  43122. _this.isCompleted = true;
  43123. if (_this.onSuccess) {
  43124. _this.onSuccess(_this);
  43125. }
  43126. onSuccess();
  43127. };
  43128. var onerror = function () {
  43129. if (_this.onError) {
  43130. _this.onError(_this);
  43131. }
  43132. onError();
  43133. };
  43134. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  43135. };
  43136. return TextureAssetTask;
  43137. })();
  43138. BABYLON.TextureAssetTask = TextureAssetTask;
  43139. var AssetsManager = (function () {
  43140. function AssetsManager(scene) {
  43141. this._tasks = new Array();
  43142. this._waitingTasksCount = 0;
  43143. this.useDefaultLoadingScreen = true;
  43144. this._scene = scene;
  43145. }
  43146. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  43147. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  43148. this._tasks.push(task);
  43149. return task;
  43150. };
  43151. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  43152. var task = new TextFileAssetTask(taskName, url);
  43153. this._tasks.push(task);
  43154. return task;
  43155. };
  43156. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  43157. var task = new BinaryFileAssetTask(taskName, url);
  43158. this._tasks.push(task);
  43159. return task;
  43160. };
  43161. AssetsManager.prototype.addImageTask = function (taskName, url) {
  43162. var task = new ImageAssetTask(taskName, url);
  43163. this._tasks.push(task);
  43164. return task;
  43165. };
  43166. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  43167. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43168. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  43169. this._tasks.push(task);
  43170. return task;
  43171. };
  43172. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  43173. this._waitingTasksCount--;
  43174. if (this._waitingTasksCount === 0) {
  43175. if (this.onFinish) {
  43176. this.onFinish(this._tasks);
  43177. }
  43178. this._scene.getEngine().hideLoadingUI();
  43179. }
  43180. };
  43181. AssetsManager.prototype._runTask = function (task) {
  43182. var _this = this;
  43183. task.run(this._scene, function () {
  43184. if (_this.onTaskSuccess) {
  43185. _this.onTaskSuccess(task);
  43186. }
  43187. _this._decreaseWaitingTasksCount();
  43188. }, function () {
  43189. if (_this.onTaskError) {
  43190. _this.onTaskError(task);
  43191. }
  43192. _this._decreaseWaitingTasksCount();
  43193. });
  43194. };
  43195. AssetsManager.prototype.reset = function () {
  43196. this._tasks = new Array();
  43197. return this;
  43198. };
  43199. AssetsManager.prototype.load = function () {
  43200. this._waitingTasksCount = this._tasks.length;
  43201. if (this._waitingTasksCount === 0) {
  43202. if (this.onFinish) {
  43203. this.onFinish(this._tasks);
  43204. }
  43205. return this;
  43206. }
  43207. if (this.useDefaultLoadingScreen) {
  43208. this._scene.getEngine().displayLoadingUI();
  43209. }
  43210. for (var index = 0; index < this._tasks.length; index++) {
  43211. var task = this._tasks[index];
  43212. this._runTask(task);
  43213. }
  43214. return this;
  43215. };
  43216. return AssetsManager;
  43217. })();
  43218. BABYLON.AssetsManager = AssetsManager;
  43219. })(BABYLON || (BABYLON = {}));
  43220. var BABYLON;
  43221. (function (BABYLON) {
  43222. var VRCameraMetrics = (function () {
  43223. function VRCameraMetrics() {
  43224. this.compensateDistortion = true;
  43225. }
  43226. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  43227. get: function () {
  43228. return this.hResolution / (2 * this.vResolution);
  43229. },
  43230. enumerable: true,
  43231. configurable: true
  43232. });
  43233. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  43234. get: function () {
  43235. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  43236. },
  43237. enumerable: true,
  43238. configurable: true
  43239. });
  43240. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  43241. get: function () {
  43242. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43243. var h = (4 * meters) / this.hScreenSize;
  43244. return BABYLON.Matrix.Translation(h, 0, 0);
  43245. },
  43246. enumerable: true,
  43247. configurable: true
  43248. });
  43249. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  43250. get: function () {
  43251. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43252. var h = (4 * meters) / this.hScreenSize;
  43253. return BABYLON.Matrix.Translation(-h, 0, 0);
  43254. },
  43255. enumerable: true,
  43256. configurable: true
  43257. });
  43258. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  43259. get: function () {
  43260. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  43261. },
  43262. enumerable: true,
  43263. configurable: true
  43264. });
  43265. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  43266. get: function () {
  43267. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  43268. },
  43269. enumerable: true,
  43270. configurable: true
  43271. });
  43272. VRCameraMetrics.GetDefault = function () {
  43273. var result = new VRCameraMetrics();
  43274. result.hResolution = 1280;
  43275. result.vResolution = 800;
  43276. result.hScreenSize = 0.149759993;
  43277. result.vScreenSize = 0.0935999975;
  43278. result.vScreenCenter = 0.0467999987,
  43279. result.eyeToScreenDistance = 0.0410000011;
  43280. result.lensSeparationDistance = 0.0635000020;
  43281. result.interpupillaryDistance = 0.0640000030;
  43282. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  43283. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  43284. result.postProcessScaleFactor = 1.714605507808412;
  43285. result.lensCenterOffset = 0.151976421;
  43286. return result;
  43287. };
  43288. return VRCameraMetrics;
  43289. })();
  43290. BABYLON.VRCameraMetrics = VRCameraMetrics;
  43291. })(BABYLON || (BABYLON = {}));
  43292. var BABYLON;
  43293. (function (BABYLON) {
  43294. var VRDeviceOrientationFreeCamera = (function (_super) {
  43295. __extends(VRDeviceOrientationFreeCamera, _super);
  43296. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  43297. if (compensateDistortion === void 0) { compensateDistortion = true; }
  43298. _super.call(this, name, position, scene);
  43299. this.rotationQuaternion = new BABYLON.Quaternion();
  43300. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  43301. metrics.compensateDistortion = compensateDistortion;
  43302. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  43303. this.inputs.addDeviceOrientation();
  43304. }
  43305. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  43306. return "VRDeviceOrientationFreeCamera";
  43307. };
  43308. return VRDeviceOrientationFreeCamera;
  43309. })(BABYLON.FreeCamera);
  43310. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  43311. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  43312. __extends(VRDeviceOrientationArcRotateCamera, _super);
  43313. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  43314. if (compensateDistortion === void 0) { compensateDistortion = true; }
  43315. _super.call(this, name, alpha, beta, radius, target, scene);
  43316. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  43317. metrics.compensateDistortion = compensateDistortion;
  43318. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  43319. this.inputs.addVRDeviceOrientation();
  43320. }
  43321. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  43322. return "VRDeviceOrientationArcRotateCamera";
  43323. };
  43324. return VRDeviceOrientationArcRotateCamera;
  43325. })(BABYLON.ArcRotateCamera);
  43326. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  43327. })(BABYLON || (BABYLON = {}));
  43328. var BABYLON;
  43329. (function (BABYLON) {
  43330. var WebVRFreeCamera = (function (_super) {
  43331. __extends(WebVRFreeCamera, _super);
  43332. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  43333. if (compensateDistortion === void 0) { compensateDistortion = true; }
  43334. _super.call(this, name, position, scene);
  43335. this._hmdDevice = null;
  43336. this._sensorDevice = null;
  43337. this._cacheState = null;
  43338. this._cacheQuaternion = new BABYLON.Quaternion();
  43339. this._cacheRotation = BABYLON.Vector3.Zero();
  43340. this._vrEnabled = false;
  43341. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  43342. metrics.compensateDistortion = compensateDistortion;
  43343. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  43344. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  43345. }
  43346. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  43347. var size = devices.length;
  43348. var i = 0;
  43349. // Reset devices.
  43350. this._sensorDevice = null;
  43351. this._hmdDevice = null;
  43352. // Search for a HmdDevice.
  43353. while (i < size && this._hmdDevice === null) {
  43354. if (devices[i] instanceof HMDVRDevice) {
  43355. this._hmdDevice = devices[i];
  43356. }
  43357. i++;
  43358. }
  43359. i = 0;
  43360. while (i < size && this._sensorDevice === null) {
  43361. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  43362. this._sensorDevice = devices[i];
  43363. }
  43364. i++;
  43365. }
  43366. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  43367. };
  43368. WebVRFreeCamera.prototype._checkInputs = function () {
  43369. if (this._vrEnabled) {
  43370. this._cacheState = this._sensorDevice.getState();
  43371. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  43372. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  43373. this.rotation.x = -this._cacheRotation.x;
  43374. this.rotation.y = -this._cacheRotation.y;
  43375. this.rotation.z = this._cacheRotation.z;
  43376. }
  43377. _super.prototype._checkInputs.call(this);
  43378. };
  43379. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43380. _super.prototype.attachControl.call(this, element, noPreventDefault);
  43381. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43382. if (navigator.getVRDevices) {
  43383. navigator.getVRDevices().then(this._getWebVRDevices);
  43384. }
  43385. else if (navigator.mozGetVRDevices) {
  43386. navigator.mozGetVRDevices(this._getWebVRDevices);
  43387. }
  43388. };
  43389. WebVRFreeCamera.prototype.detachControl = function (element) {
  43390. _super.prototype.detachControl.call(this, element);
  43391. this._vrEnabled = false;
  43392. };
  43393. WebVRFreeCamera.prototype.getTypeName = function () {
  43394. return "WebVRFreeCamera";
  43395. };
  43396. return WebVRFreeCamera;
  43397. })(BABYLON.FreeCamera);
  43398. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  43399. })(BABYLON || (BABYLON = {}));
  43400. var BABYLON;
  43401. (function (BABYLON) {
  43402. // Standard optimizations
  43403. var SceneOptimization = (function () {
  43404. function SceneOptimization(priority) {
  43405. if (priority === void 0) { priority = 0; }
  43406. this.priority = priority;
  43407. this.apply = function (scene) {
  43408. return true; // Return true if everything that can be done was applied
  43409. };
  43410. }
  43411. return SceneOptimization;
  43412. })();
  43413. BABYLON.SceneOptimization = SceneOptimization;
  43414. var TextureOptimization = (function (_super) {
  43415. __extends(TextureOptimization, _super);
  43416. function TextureOptimization(priority, maximumSize) {
  43417. var _this = this;
  43418. if (priority === void 0) { priority = 0; }
  43419. if (maximumSize === void 0) { maximumSize = 1024; }
  43420. _super.call(this, priority);
  43421. this.priority = priority;
  43422. this.maximumSize = maximumSize;
  43423. this.apply = function (scene) {
  43424. var allDone = true;
  43425. for (var index = 0; index < scene.textures.length; index++) {
  43426. var texture = scene.textures[index];
  43427. if (!texture.canRescale) {
  43428. continue;
  43429. }
  43430. var currentSize = texture.getSize();
  43431. var maxDimension = Math.max(currentSize.width, currentSize.height);
  43432. if (maxDimension > _this.maximumSize) {
  43433. texture.scale(0.5);
  43434. allDone = false;
  43435. }
  43436. }
  43437. return allDone;
  43438. };
  43439. }
  43440. return TextureOptimization;
  43441. })(SceneOptimization);
  43442. BABYLON.TextureOptimization = TextureOptimization;
  43443. var HardwareScalingOptimization = (function (_super) {
  43444. __extends(HardwareScalingOptimization, _super);
  43445. function HardwareScalingOptimization(priority, maximumScale) {
  43446. var _this = this;
  43447. if (priority === void 0) { priority = 0; }
  43448. if (maximumScale === void 0) { maximumScale = 2; }
  43449. _super.call(this, priority);
  43450. this.priority = priority;
  43451. this.maximumScale = maximumScale;
  43452. this._currentScale = 1;
  43453. this.apply = function (scene) {
  43454. _this._currentScale++;
  43455. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  43456. return _this._currentScale >= _this.maximumScale;
  43457. };
  43458. }
  43459. return HardwareScalingOptimization;
  43460. })(SceneOptimization);
  43461. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  43462. var ShadowsOptimization = (function (_super) {
  43463. __extends(ShadowsOptimization, _super);
  43464. function ShadowsOptimization() {
  43465. _super.apply(this, arguments);
  43466. this.apply = function (scene) {
  43467. scene.shadowsEnabled = false;
  43468. return true;
  43469. };
  43470. }
  43471. return ShadowsOptimization;
  43472. })(SceneOptimization);
  43473. BABYLON.ShadowsOptimization = ShadowsOptimization;
  43474. var PostProcessesOptimization = (function (_super) {
  43475. __extends(PostProcessesOptimization, _super);
  43476. function PostProcessesOptimization() {
  43477. _super.apply(this, arguments);
  43478. this.apply = function (scene) {
  43479. scene.postProcessesEnabled = false;
  43480. return true;
  43481. };
  43482. }
  43483. return PostProcessesOptimization;
  43484. })(SceneOptimization);
  43485. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  43486. var LensFlaresOptimization = (function (_super) {
  43487. __extends(LensFlaresOptimization, _super);
  43488. function LensFlaresOptimization() {
  43489. _super.apply(this, arguments);
  43490. this.apply = function (scene) {
  43491. scene.lensFlaresEnabled = false;
  43492. return true;
  43493. };
  43494. }
  43495. return LensFlaresOptimization;
  43496. })(SceneOptimization);
  43497. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  43498. var ParticlesOptimization = (function (_super) {
  43499. __extends(ParticlesOptimization, _super);
  43500. function ParticlesOptimization() {
  43501. _super.apply(this, arguments);
  43502. this.apply = function (scene) {
  43503. scene.particlesEnabled = false;
  43504. return true;
  43505. };
  43506. }
  43507. return ParticlesOptimization;
  43508. })(SceneOptimization);
  43509. BABYLON.ParticlesOptimization = ParticlesOptimization;
  43510. var RenderTargetsOptimization = (function (_super) {
  43511. __extends(RenderTargetsOptimization, _super);
  43512. function RenderTargetsOptimization() {
  43513. _super.apply(this, arguments);
  43514. this.apply = function (scene) {
  43515. scene.renderTargetsEnabled = false;
  43516. return true;
  43517. };
  43518. }
  43519. return RenderTargetsOptimization;
  43520. })(SceneOptimization);
  43521. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  43522. var MergeMeshesOptimization = (function (_super) {
  43523. __extends(MergeMeshesOptimization, _super);
  43524. function MergeMeshesOptimization() {
  43525. var _this = this;
  43526. _super.apply(this, arguments);
  43527. this._canBeMerged = function (abstractMesh) {
  43528. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  43529. return false;
  43530. }
  43531. var mesh = abstractMesh;
  43532. if (!mesh.isVisible || !mesh.isEnabled()) {
  43533. return false;
  43534. }
  43535. if (mesh.instances.length > 0) {
  43536. return false;
  43537. }
  43538. if (mesh.skeleton || mesh.hasLODLevels) {
  43539. return false;
  43540. }
  43541. if (mesh.parent) {
  43542. return false;
  43543. }
  43544. return true;
  43545. };
  43546. this.apply = function (scene, updateSelectionTree) {
  43547. var globalPool = scene.meshes.slice(0);
  43548. var globalLength = globalPool.length;
  43549. for (var index = 0; index < globalLength; index++) {
  43550. var currentPool = new Array();
  43551. var current = globalPool[index];
  43552. // Checks
  43553. if (!_this._canBeMerged(current)) {
  43554. continue;
  43555. }
  43556. currentPool.push(current);
  43557. // Find compatible meshes
  43558. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  43559. var otherMesh = globalPool[subIndex];
  43560. if (!_this._canBeMerged(otherMesh)) {
  43561. continue;
  43562. }
  43563. if (otherMesh.material !== current.material) {
  43564. continue;
  43565. }
  43566. if (otherMesh.checkCollisions !== current.checkCollisions) {
  43567. continue;
  43568. }
  43569. currentPool.push(otherMesh);
  43570. globalLength--;
  43571. globalPool.splice(subIndex, 1);
  43572. subIndex--;
  43573. }
  43574. if (currentPool.length < 2) {
  43575. continue;
  43576. }
  43577. // Merge meshes
  43578. BABYLON.Mesh.MergeMeshes(currentPool);
  43579. }
  43580. if (updateSelectionTree != undefined) {
  43581. if (updateSelectionTree) {
  43582. scene.createOrUpdateSelectionOctree();
  43583. }
  43584. }
  43585. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  43586. scene.createOrUpdateSelectionOctree();
  43587. }
  43588. return true;
  43589. };
  43590. }
  43591. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  43592. get: function () {
  43593. return MergeMeshesOptimization._UpdateSelectionTree;
  43594. },
  43595. set: function (value) {
  43596. MergeMeshesOptimization._UpdateSelectionTree = value;
  43597. },
  43598. enumerable: true,
  43599. configurable: true
  43600. });
  43601. MergeMeshesOptimization._UpdateSelectionTree = false;
  43602. return MergeMeshesOptimization;
  43603. })(SceneOptimization);
  43604. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  43605. // Options
  43606. var SceneOptimizerOptions = (function () {
  43607. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  43608. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  43609. if (trackerDuration === void 0) { trackerDuration = 2000; }
  43610. this.targetFrameRate = targetFrameRate;
  43611. this.trackerDuration = trackerDuration;
  43612. this.optimizations = new Array();
  43613. }
  43614. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  43615. var result = new SceneOptimizerOptions(targetFrameRate);
  43616. var priority = 0;
  43617. result.optimizations.push(new MergeMeshesOptimization(priority));
  43618. result.optimizations.push(new ShadowsOptimization(priority));
  43619. result.optimizations.push(new LensFlaresOptimization(priority));
  43620. // Next priority
  43621. priority++;
  43622. result.optimizations.push(new PostProcessesOptimization(priority));
  43623. result.optimizations.push(new ParticlesOptimization(priority));
  43624. // Next priority
  43625. priority++;
  43626. result.optimizations.push(new TextureOptimization(priority, 1024));
  43627. return result;
  43628. };
  43629. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  43630. var result = new SceneOptimizerOptions(targetFrameRate);
  43631. var priority = 0;
  43632. result.optimizations.push(new MergeMeshesOptimization(priority));
  43633. result.optimizations.push(new ShadowsOptimization(priority));
  43634. result.optimizations.push(new LensFlaresOptimization(priority));
  43635. // Next priority
  43636. priority++;
  43637. result.optimizations.push(new PostProcessesOptimization(priority));
  43638. result.optimizations.push(new ParticlesOptimization(priority));
  43639. // Next priority
  43640. priority++;
  43641. result.optimizations.push(new TextureOptimization(priority, 512));
  43642. // Next priority
  43643. priority++;
  43644. result.optimizations.push(new RenderTargetsOptimization(priority));
  43645. // Next priority
  43646. priority++;
  43647. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  43648. return result;
  43649. };
  43650. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  43651. var result = new SceneOptimizerOptions(targetFrameRate);
  43652. var priority = 0;
  43653. result.optimizations.push(new MergeMeshesOptimization(priority));
  43654. result.optimizations.push(new ShadowsOptimization(priority));
  43655. result.optimizations.push(new LensFlaresOptimization(priority));
  43656. // Next priority
  43657. priority++;
  43658. result.optimizations.push(new PostProcessesOptimization(priority));
  43659. result.optimizations.push(new ParticlesOptimization(priority));
  43660. // Next priority
  43661. priority++;
  43662. result.optimizations.push(new TextureOptimization(priority, 256));
  43663. // Next priority
  43664. priority++;
  43665. result.optimizations.push(new RenderTargetsOptimization(priority));
  43666. // Next priority
  43667. priority++;
  43668. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  43669. return result;
  43670. };
  43671. return SceneOptimizerOptions;
  43672. })();
  43673. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  43674. // Scene optimizer tool
  43675. var SceneOptimizer = (function () {
  43676. function SceneOptimizer() {
  43677. }
  43678. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  43679. // TODO: add an epsilon
  43680. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  43681. if (onSuccess) {
  43682. onSuccess();
  43683. }
  43684. return;
  43685. }
  43686. // Apply current level of optimizations
  43687. var allDone = true;
  43688. var noOptimizationApplied = true;
  43689. for (var index = 0; index < options.optimizations.length; index++) {
  43690. var optimization = options.optimizations[index];
  43691. if (optimization.priority === currentPriorityLevel) {
  43692. noOptimizationApplied = false;
  43693. allDone = allDone && optimization.apply(scene);
  43694. }
  43695. }
  43696. // If no optimization was applied, this is a failure :(
  43697. if (noOptimizationApplied) {
  43698. if (onFailure) {
  43699. onFailure();
  43700. }
  43701. return;
  43702. }
  43703. // If all optimizations were done, move to next level
  43704. if (allDone) {
  43705. currentPriorityLevel++;
  43706. }
  43707. // Let's the system running for a specific amount of time before checking FPS
  43708. scene.executeWhenReady(function () {
  43709. setTimeout(function () {
  43710. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  43711. }, options.trackerDuration);
  43712. });
  43713. };
  43714. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  43715. if (!options) {
  43716. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  43717. }
  43718. // Let's the system running for a specific amount of time before checking FPS
  43719. scene.executeWhenReady(function () {
  43720. setTimeout(function () {
  43721. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  43722. }, options.trackerDuration);
  43723. });
  43724. };
  43725. return SceneOptimizer;
  43726. })();
  43727. BABYLON.SceneOptimizer = SceneOptimizer;
  43728. })(BABYLON || (BABYLON = {}));
  43729. var BABYLON;
  43730. (function (BABYLON) {
  43731. var Internals;
  43732. (function (Internals) {
  43733. var MeshLODLevel = (function () {
  43734. function MeshLODLevel(distance, mesh) {
  43735. this.distance = distance;
  43736. this.mesh = mesh;
  43737. }
  43738. return MeshLODLevel;
  43739. })();
  43740. Internals.MeshLODLevel = MeshLODLevel;
  43741. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43742. })(BABYLON || (BABYLON = {}));
  43743. var BABYLON;
  43744. (function (BABYLON) {
  43745. var RawTexture = (function (_super) {
  43746. __extends(RawTexture, _super);
  43747. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  43748. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43749. if (invertY === void 0) { invertY = false; }
  43750. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43751. _super.call(this, null, scene, !generateMipMaps, invertY);
  43752. this.format = format;
  43753. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  43754. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43755. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43756. }
  43757. RawTexture.prototype.update = function (data) {
  43758. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  43759. };
  43760. // Statics
  43761. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43762. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43763. if (invertY === void 0) { invertY = false; }
  43764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43765. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  43766. };
  43767. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43768. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43769. if (invertY === void 0) { invertY = false; }
  43770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43771. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43772. };
  43773. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43774. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43775. if (invertY === void 0) { invertY = false; }
  43776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43777. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43778. };
  43779. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43780. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43781. if (invertY === void 0) { invertY = false; }
  43782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43783. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  43784. };
  43785. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43786. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43787. if (invertY === void 0) { invertY = false; }
  43788. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43789. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  43790. };
  43791. return RawTexture;
  43792. })(BABYLON.Texture);
  43793. BABYLON.RawTexture = RawTexture;
  43794. })(BABYLON || (BABYLON = {}));
  43795. var BABYLON;
  43796. (function (BABYLON) {
  43797. var IndexedVector2 = (function (_super) {
  43798. __extends(IndexedVector2, _super);
  43799. function IndexedVector2(original, index) {
  43800. _super.call(this, original.x, original.y);
  43801. this.index = index;
  43802. }
  43803. return IndexedVector2;
  43804. })(BABYLON.Vector2);
  43805. var PolygonPoints = (function () {
  43806. function PolygonPoints() {
  43807. this.elements = new Array();
  43808. }
  43809. PolygonPoints.prototype.add = function (originalPoints) {
  43810. var _this = this;
  43811. var result = new Array();
  43812. originalPoints.forEach(function (point) {
  43813. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  43814. var newPoint = new IndexedVector2(point, _this.elements.length);
  43815. result.push(newPoint);
  43816. _this.elements.push(newPoint);
  43817. }
  43818. });
  43819. return result;
  43820. };
  43821. PolygonPoints.prototype.computeBounds = function () {
  43822. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  43823. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  43824. this.elements.forEach(function (point) {
  43825. // x
  43826. if (point.x < lmin.x) {
  43827. lmin.x = point.x;
  43828. }
  43829. else if (point.x > lmax.x) {
  43830. lmax.x = point.x;
  43831. }
  43832. // y
  43833. if (point.y < lmin.y) {
  43834. lmin.y = point.y;
  43835. }
  43836. else if (point.y > lmax.y) {
  43837. lmax.y = point.y;
  43838. }
  43839. });
  43840. return {
  43841. min: lmin,
  43842. max: lmax,
  43843. width: lmax.x - lmin.x,
  43844. height: lmax.y - lmin.y
  43845. };
  43846. };
  43847. return PolygonPoints;
  43848. })();
  43849. var Polygon = (function () {
  43850. function Polygon() {
  43851. }
  43852. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  43853. return [
  43854. new BABYLON.Vector2(xmin, ymin),
  43855. new BABYLON.Vector2(xmax, ymin),
  43856. new BABYLON.Vector2(xmax, ymax),
  43857. new BABYLON.Vector2(xmin, ymax)
  43858. ];
  43859. };
  43860. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  43861. if (cx === void 0) { cx = 0; }
  43862. if (cy === void 0) { cy = 0; }
  43863. if (numberOfSides === void 0) { numberOfSides = 32; }
  43864. var result = new Array();
  43865. var angle = 0;
  43866. var increment = (Math.PI * 2) / numberOfSides;
  43867. for (var i = 0; i < numberOfSides; i++) {
  43868. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  43869. angle -= increment;
  43870. }
  43871. return result;
  43872. };
  43873. Polygon.Parse = function (input) {
  43874. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  43875. var i, result = [];
  43876. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  43877. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  43878. }
  43879. return result;
  43880. };
  43881. Polygon.StartingAt = function (x, y) {
  43882. return BABYLON.Path2.StartingAt(x, y);
  43883. };
  43884. return Polygon;
  43885. })();
  43886. BABYLON.Polygon = Polygon;
  43887. var PolygonMeshBuilder = (function () {
  43888. function PolygonMeshBuilder(name, contours, scene) {
  43889. this._points = new PolygonPoints();
  43890. this._outlinepoints = new PolygonPoints();
  43891. this._holes = [];
  43892. if (!("poly2tri" in window)) {
  43893. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  43894. }
  43895. this._name = name;
  43896. this._scene = scene;
  43897. var points;
  43898. if (contours instanceof BABYLON.Path2) {
  43899. points = contours.getPoints();
  43900. }
  43901. else {
  43902. points = contours;
  43903. }
  43904. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  43905. this._outlinepoints.add(points);
  43906. }
  43907. PolygonMeshBuilder.prototype.addHole = function (hole) {
  43908. this._swctx.addHole(this._points.add(hole));
  43909. var holepoints = new PolygonPoints();
  43910. holepoints.add(hole);
  43911. this._holes.push(holepoints);
  43912. return this;
  43913. };
  43914. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  43915. var _this = this;
  43916. if (updatable === void 0) { updatable = false; }
  43917. var result = new BABYLON.Mesh(this._name, this._scene);
  43918. var normals = [];
  43919. var positions = [];
  43920. var uvs = [];
  43921. var bounds = this._points.computeBounds();
  43922. this._points.elements.forEach(function (p) {
  43923. normals.push(0, 1.0, 0);
  43924. positions.push(p.x, 0, p.y);
  43925. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  43926. });
  43927. var indices = [];
  43928. this._swctx.triangulate();
  43929. this._swctx.getTriangles().forEach(function (triangle) {
  43930. triangle.getPoints().forEach(function (point) {
  43931. indices.push(point.index);
  43932. });
  43933. });
  43934. if (depth > 0) {
  43935. var positionscount = (positions.length / 3); //get the current pointcount
  43936. this._points.elements.forEach(function (p) {
  43937. normals.push(0, -1.0, 0);
  43938. positions.push(p.x, -depth, p.y);
  43939. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  43940. });
  43941. var p1; //we need to change order of point so the triangles are made in the rigth way.
  43942. var p2;
  43943. var poscounter = 0;
  43944. this._swctx.getTriangles().forEach(function (triangle) {
  43945. triangle.getPoints().forEach(function (point) {
  43946. switch (poscounter) {
  43947. case 0:
  43948. p1 = point;
  43949. break;
  43950. case 1:
  43951. p2 = point;
  43952. break;
  43953. case 2:
  43954. indices.push(point.index + positionscount);
  43955. indices.push(p2.index + positionscount);
  43956. indices.push(p1.index + positionscount);
  43957. poscounter = -1;
  43958. break;
  43959. }
  43960. poscounter++;
  43961. //indices.push((<IndexedVector2>point).index + positionscount);
  43962. });
  43963. });
  43964. //Add the sides
  43965. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  43966. this._holes.forEach(function (hole) {
  43967. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  43968. });
  43969. }
  43970. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  43971. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  43972. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  43973. result.setIndices(indices);
  43974. return result;
  43975. };
  43976. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  43977. var StartIndex = positions.length / 3;
  43978. var ulength = 0;
  43979. for (var i = 0; i < points.elements.length; i++) {
  43980. var p = points.elements[i];
  43981. var p1;
  43982. if ((i + 1) > points.elements.length - 1) {
  43983. p1 = points.elements[0];
  43984. }
  43985. else {
  43986. p1 = points.elements[i + 1];
  43987. }
  43988. positions.push(p.x, 0, p.y);
  43989. positions.push(p.x, -depth, p.y);
  43990. positions.push(p1.x, 0, p1.y);
  43991. positions.push(p1.x, -depth, p1.y);
  43992. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  43993. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  43994. var v3 = v2.subtract(v1);
  43995. var v4 = new BABYLON.Vector3(0, 1, 0);
  43996. var vn = BABYLON.Vector3.Cross(v3, v4);
  43997. vn = vn.normalize();
  43998. uvs.push(ulength / bounds.width, 0);
  43999. uvs.push(ulength / bounds.width, 1);
  44000. ulength += v3.length();
  44001. uvs.push((ulength / bounds.width), 0);
  44002. uvs.push((ulength / bounds.width), 1);
  44003. if (!flip) {
  44004. normals.push(-vn.x, -vn.y, -vn.z);
  44005. normals.push(-vn.x, -vn.y, -vn.z);
  44006. normals.push(-vn.x, -vn.y, -vn.z);
  44007. normals.push(-vn.x, -vn.y, -vn.z);
  44008. indices.push(StartIndex);
  44009. indices.push(StartIndex + 1);
  44010. indices.push(StartIndex + 2);
  44011. indices.push(StartIndex + 1);
  44012. indices.push(StartIndex + 3);
  44013. indices.push(StartIndex + 2);
  44014. }
  44015. else {
  44016. normals.push(vn.x, vn.y, vn.z);
  44017. normals.push(vn.x, vn.y, vn.z);
  44018. normals.push(vn.x, vn.y, vn.z);
  44019. normals.push(vn.x, vn.y, vn.z);
  44020. indices.push(StartIndex);
  44021. indices.push(StartIndex + 2);
  44022. indices.push(StartIndex + 1);
  44023. indices.push(StartIndex + 1);
  44024. indices.push(StartIndex + 2);
  44025. indices.push(StartIndex + 3);
  44026. }
  44027. StartIndex += 4;
  44028. }
  44029. ;
  44030. };
  44031. return PolygonMeshBuilder;
  44032. })();
  44033. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  44034. })(BABYLON || (BABYLON = {}));
  44035. var BABYLON;
  44036. (function (BABYLON) {
  44037. var Octree = (function () {
  44038. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  44039. if (maxDepth === void 0) { maxDepth = 2; }
  44040. this.maxDepth = maxDepth;
  44041. this.dynamicContent = new Array();
  44042. this._maxBlockCapacity = maxBlockCapacity || 64;
  44043. this._selectionContent = new BABYLON.SmartArray(1024);
  44044. this._creationFunc = creationFunc;
  44045. }
  44046. // Methods
  44047. Octree.prototype.update = function (worldMin, worldMax, entries) {
  44048. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  44049. };
  44050. Octree.prototype.addMesh = function (entry) {
  44051. for (var index = 0; index < this.blocks.length; index++) {
  44052. var block = this.blocks[index];
  44053. block.addEntry(entry);
  44054. }
  44055. };
  44056. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  44057. this._selectionContent.reset();
  44058. for (var index = 0; index < this.blocks.length; index++) {
  44059. var block = this.blocks[index];
  44060. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  44061. }
  44062. if (allowDuplicate) {
  44063. this._selectionContent.concat(this.dynamicContent);
  44064. }
  44065. else {
  44066. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44067. }
  44068. return this._selectionContent;
  44069. };
  44070. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  44071. this._selectionContent.reset();
  44072. for (var index = 0; index < this.blocks.length; index++) {
  44073. var block = this.blocks[index];
  44074. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  44075. }
  44076. if (allowDuplicate) {
  44077. this._selectionContent.concat(this.dynamicContent);
  44078. }
  44079. else {
  44080. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44081. }
  44082. return this._selectionContent;
  44083. };
  44084. Octree.prototype.intersectsRay = function (ray) {
  44085. this._selectionContent.reset();
  44086. for (var index = 0; index < this.blocks.length; index++) {
  44087. var block = this.blocks[index];
  44088. block.intersectsRay(ray, this._selectionContent);
  44089. }
  44090. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44091. return this._selectionContent;
  44092. };
  44093. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  44094. target.blocks = new Array();
  44095. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  44096. // Segmenting space
  44097. for (var x = 0; x < 2; x++) {
  44098. for (var y = 0; y < 2; y++) {
  44099. for (var z = 0; z < 2; z++) {
  44100. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  44101. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  44102. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  44103. block.addEntries(entries);
  44104. target.blocks.push(block);
  44105. }
  44106. }
  44107. }
  44108. };
  44109. Octree.CreationFuncForMeshes = function (entry, block) {
  44110. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44111. block.entries.push(entry);
  44112. }
  44113. };
  44114. Octree.CreationFuncForSubMeshes = function (entry, block) {
  44115. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44116. block.entries.push(entry);
  44117. }
  44118. };
  44119. return Octree;
  44120. })();
  44121. BABYLON.Octree = Octree;
  44122. })(BABYLON || (BABYLON = {}));
  44123. var BABYLON;
  44124. (function (BABYLON) {
  44125. var OctreeBlock = (function () {
  44126. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  44127. this.entries = new Array();
  44128. this._boundingVectors = new Array();
  44129. this._capacity = capacity;
  44130. this._depth = depth;
  44131. this._maxDepth = maxDepth;
  44132. this._creationFunc = creationFunc;
  44133. this._minPoint = minPoint;
  44134. this._maxPoint = maxPoint;
  44135. this._boundingVectors.push(minPoint.clone());
  44136. this._boundingVectors.push(maxPoint.clone());
  44137. this._boundingVectors.push(minPoint.clone());
  44138. this._boundingVectors[2].x = maxPoint.x;
  44139. this._boundingVectors.push(minPoint.clone());
  44140. this._boundingVectors[3].y = maxPoint.y;
  44141. this._boundingVectors.push(minPoint.clone());
  44142. this._boundingVectors[4].z = maxPoint.z;
  44143. this._boundingVectors.push(maxPoint.clone());
  44144. this._boundingVectors[5].z = minPoint.z;
  44145. this._boundingVectors.push(maxPoint.clone());
  44146. this._boundingVectors[6].x = minPoint.x;
  44147. this._boundingVectors.push(maxPoint.clone());
  44148. this._boundingVectors[7].y = minPoint.y;
  44149. }
  44150. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  44151. // Property
  44152. get: function () {
  44153. return this._capacity;
  44154. },
  44155. enumerable: true,
  44156. configurable: true
  44157. });
  44158. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  44159. get: function () {
  44160. return this._minPoint;
  44161. },
  44162. enumerable: true,
  44163. configurable: true
  44164. });
  44165. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  44166. get: function () {
  44167. return this._maxPoint;
  44168. },
  44169. enumerable: true,
  44170. configurable: true
  44171. });
  44172. // Methods
  44173. OctreeBlock.prototype.addEntry = function (entry) {
  44174. if (this.blocks) {
  44175. for (var index = 0; index < this.blocks.length; index++) {
  44176. var block = this.blocks[index];
  44177. block.addEntry(entry);
  44178. }
  44179. return;
  44180. }
  44181. this._creationFunc(entry, this);
  44182. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  44183. this.createInnerBlocks();
  44184. }
  44185. };
  44186. OctreeBlock.prototype.addEntries = function (entries) {
  44187. for (var index = 0; index < entries.length; index++) {
  44188. var mesh = entries[index];
  44189. this.addEntry(mesh);
  44190. }
  44191. };
  44192. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  44193. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  44194. if (this.blocks) {
  44195. for (var index = 0; index < this.blocks.length; index++) {
  44196. var block = this.blocks[index];
  44197. block.select(frustumPlanes, selection, allowDuplicate);
  44198. }
  44199. return;
  44200. }
  44201. if (allowDuplicate) {
  44202. selection.concat(this.entries);
  44203. }
  44204. else {
  44205. selection.concatWithNoDuplicate(this.entries);
  44206. }
  44207. }
  44208. };
  44209. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  44210. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  44211. if (this.blocks) {
  44212. for (var index = 0; index < this.blocks.length; index++) {
  44213. var block = this.blocks[index];
  44214. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  44215. }
  44216. return;
  44217. }
  44218. if (allowDuplicate) {
  44219. selection.concat(this.entries);
  44220. }
  44221. else {
  44222. selection.concatWithNoDuplicate(this.entries);
  44223. }
  44224. }
  44225. };
  44226. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  44227. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  44228. if (this.blocks) {
  44229. for (var index = 0; index < this.blocks.length; index++) {
  44230. var block = this.blocks[index];
  44231. block.intersectsRay(ray, selection);
  44232. }
  44233. return;
  44234. }
  44235. selection.concatWithNoDuplicate(this.entries);
  44236. }
  44237. };
  44238. OctreeBlock.prototype.createInnerBlocks = function () {
  44239. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  44240. };
  44241. return OctreeBlock;
  44242. })();
  44243. BABYLON.OctreeBlock = OctreeBlock;
  44244. })(BABYLON || (BABYLON = {}));
  44245. var BABYLON;
  44246. (function (BABYLON) {
  44247. var BlurPostProcess = (function (_super) {
  44248. __extends(BlurPostProcess, _super);
  44249. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  44250. var _this = this;
  44251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44252. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  44253. this.direction = direction;
  44254. this.blurWidth = blurWidth;
  44255. this.onApplyObservable.add(function (effect) {
  44256. effect.setFloat2("screenSize", _this.width, _this.height);
  44257. effect.setVector2("direction", _this.direction);
  44258. effect.setFloat("blurWidth", _this.blurWidth);
  44259. });
  44260. }
  44261. return BlurPostProcess;
  44262. })(BABYLON.PostProcess);
  44263. BABYLON.BlurPostProcess = BlurPostProcess;
  44264. })(BABYLON || (BABYLON = {}));
  44265. var BABYLON;
  44266. (function (BABYLON) {
  44267. var RefractionPostProcess = (function (_super) {
  44268. __extends(RefractionPostProcess, _super);
  44269. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  44270. var _this = this;
  44271. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  44272. this.color = color;
  44273. this.depth = depth;
  44274. this.colorLevel = colorLevel;
  44275. this.onActivateObservable.add(function (cam) {
  44276. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  44277. });
  44278. this.onApplyObservable.add(function (effect) {
  44279. effect.setColor3("baseColor", _this.color);
  44280. effect.setFloat("depth", _this.depth);
  44281. effect.setFloat("colorLevel", _this.colorLevel);
  44282. effect.setTexture("refractionSampler", _this._refRexture);
  44283. });
  44284. }
  44285. // Methods
  44286. RefractionPostProcess.prototype.dispose = function (camera) {
  44287. if (this._refRexture) {
  44288. this._refRexture.dispose();
  44289. }
  44290. _super.prototype.dispose.call(this, camera);
  44291. };
  44292. return RefractionPostProcess;
  44293. })(BABYLON.PostProcess);
  44294. BABYLON.RefractionPostProcess = RefractionPostProcess;
  44295. })(BABYLON || (BABYLON = {}));
  44296. var BABYLON;
  44297. (function (BABYLON) {
  44298. var BlackAndWhitePostProcess = (function (_super) {
  44299. __extends(BlackAndWhitePostProcess, _super);
  44300. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  44301. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  44302. }
  44303. return BlackAndWhitePostProcess;
  44304. })(BABYLON.PostProcess);
  44305. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  44306. })(BABYLON || (BABYLON = {}));
  44307. var BABYLON;
  44308. (function (BABYLON) {
  44309. var ConvolutionPostProcess = (function (_super) {
  44310. __extends(ConvolutionPostProcess, _super);
  44311. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  44312. var _this = this;
  44313. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  44314. this.kernel = kernel;
  44315. this.onApply = function (effect) {
  44316. effect.setFloat2("screenSize", _this.width, _this.height);
  44317. effect.setArray("kernel", _this.kernel);
  44318. };
  44319. }
  44320. // Statics
  44321. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  44322. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  44323. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  44324. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  44325. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  44326. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  44327. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  44328. return ConvolutionPostProcess;
  44329. })(BABYLON.PostProcess);
  44330. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  44331. })(BABYLON || (BABYLON = {}));
  44332. var BABYLON;
  44333. (function (BABYLON) {
  44334. var FilterPostProcess = (function (_super) {
  44335. __extends(FilterPostProcess, _super);
  44336. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  44337. var _this = this;
  44338. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  44339. this.kernelMatrix = kernelMatrix;
  44340. this.onApply = function (effect) {
  44341. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  44342. };
  44343. }
  44344. return FilterPostProcess;
  44345. })(BABYLON.PostProcess);
  44346. BABYLON.FilterPostProcess = FilterPostProcess;
  44347. })(BABYLON || (BABYLON = {}));
  44348. var BABYLON;
  44349. (function (BABYLON) {
  44350. var FxaaPostProcess = (function (_super) {
  44351. __extends(FxaaPostProcess, _super);
  44352. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  44353. var _this = this;
  44354. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  44355. this.onSizeChangedObservable.add(function () {
  44356. _this.texelWidth = 1.0 / _this.width;
  44357. _this.texelHeight = 1.0 / _this.height;
  44358. });
  44359. this.onApplyObservable.add(function (effect) {
  44360. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  44361. });
  44362. }
  44363. return FxaaPostProcess;
  44364. })(BABYLON.PostProcess);
  44365. BABYLON.FxaaPostProcess = FxaaPostProcess;
  44366. })(BABYLON || (BABYLON = {}));
  44367. var BABYLON;
  44368. (function (BABYLON) {
  44369. var StereoscopicInterlacePostProcess = (function (_super) {
  44370. __extends(StereoscopicInterlacePostProcess, _super);
  44371. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  44372. var _this = this;
  44373. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  44374. this._passedProcess = rigCameras[0]._rigPostProcess;
  44375. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  44376. this.onSizeChangedObservable.add(function () {
  44377. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  44378. });
  44379. this.onApplyObservable.add(function (effect) {
  44380. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  44381. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  44382. });
  44383. }
  44384. return StereoscopicInterlacePostProcess;
  44385. })(BABYLON.PostProcess);
  44386. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  44387. })(BABYLON || (BABYLON = {}));
  44388. var BABYLON;
  44389. (function (BABYLON) {
  44390. var LensFlare = (function () {
  44391. function LensFlare(size, position, color, imgUrl, system) {
  44392. this.size = size;
  44393. this.position = position;
  44394. this.dispose = function () {
  44395. if (this.texture) {
  44396. this.texture.dispose();
  44397. }
  44398. // Remove from scene
  44399. var index = this._system.lensFlares.indexOf(this);
  44400. this._system.lensFlares.splice(index, 1);
  44401. };
  44402. this.color = color || new BABYLON.Color3(1, 1, 1);
  44403. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  44404. this._system = system;
  44405. system.lensFlares.push(this);
  44406. }
  44407. return LensFlare;
  44408. })();
  44409. BABYLON.LensFlare = LensFlare;
  44410. })(BABYLON || (BABYLON = {}));
  44411. var BABYLON;
  44412. (function (BABYLON) {
  44413. var LensFlareSystem = (function () {
  44414. function LensFlareSystem(name, emitter, scene) {
  44415. this.name = name;
  44416. this.lensFlares = new Array();
  44417. this.borderLimit = 300;
  44418. this.layerMask = 0x0FFFFFFF;
  44419. this._vertexDeclaration = [2];
  44420. this._vertexStrideSize = 2 * 4;
  44421. this._isEnabled = true;
  44422. this._scene = scene;
  44423. this._emitter = emitter;
  44424. this.id = name;
  44425. scene.lensFlareSystems.push(this);
  44426. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  44427. // VBO
  44428. var vertices = [];
  44429. vertices.push(1, 1);
  44430. vertices.push(-1, 1);
  44431. vertices.push(-1, -1);
  44432. vertices.push(1, -1);
  44433. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  44434. // Indices
  44435. var indices = [];
  44436. indices.push(0);
  44437. indices.push(1);
  44438. indices.push(2);
  44439. indices.push(0);
  44440. indices.push(2);
  44441. indices.push(3);
  44442. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44443. // Effects
  44444. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  44445. }
  44446. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  44447. get: function () {
  44448. return this._isEnabled;
  44449. },
  44450. set: function (value) {
  44451. this._isEnabled = value;
  44452. },
  44453. enumerable: true,
  44454. configurable: true
  44455. });
  44456. LensFlareSystem.prototype.getScene = function () {
  44457. return this._scene;
  44458. };
  44459. LensFlareSystem.prototype.getEmitter = function () {
  44460. return this._emitter;
  44461. };
  44462. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  44463. this._emitter = newEmitter;
  44464. };
  44465. LensFlareSystem.prototype.getEmitterPosition = function () {
  44466. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  44467. };
  44468. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  44469. var position = this.getEmitterPosition();
  44470. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  44471. this._positionX = position.x;
  44472. this._positionY = position.y;
  44473. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  44474. if (position.z > 0) {
  44475. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  44476. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  44477. return true;
  44478. }
  44479. }
  44480. return false;
  44481. };
  44482. LensFlareSystem.prototype._isVisible = function () {
  44483. if (!this._isEnabled) {
  44484. return false;
  44485. }
  44486. var emitterPosition = this.getEmitterPosition();
  44487. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  44488. var distance = direction.length();
  44489. direction.normalize();
  44490. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  44491. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  44492. return !pickInfo.hit || pickInfo.distance > distance;
  44493. };
  44494. LensFlareSystem.prototype.render = function () {
  44495. if (!this._effect.isReady())
  44496. return false;
  44497. var engine = this._scene.getEngine();
  44498. var viewport = this._scene.activeCamera.viewport;
  44499. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  44500. // Position
  44501. if (!this.computeEffectivePosition(globalViewport)) {
  44502. return false;
  44503. }
  44504. // Visibility
  44505. if (!this._isVisible()) {
  44506. return false;
  44507. }
  44508. // Intensity
  44509. var awayX;
  44510. var awayY;
  44511. if (this._positionX < this.borderLimit + globalViewport.x) {
  44512. awayX = this.borderLimit + globalViewport.x - this._positionX;
  44513. }
  44514. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  44515. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  44516. }
  44517. else {
  44518. awayX = 0;
  44519. }
  44520. if (this._positionY < this.borderLimit + globalViewport.y) {
  44521. awayY = this.borderLimit + globalViewport.y - this._positionY;
  44522. }
  44523. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  44524. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  44525. }
  44526. else {
  44527. awayY = 0;
  44528. }
  44529. var away = (awayX > awayY) ? awayX : awayY;
  44530. if (away > this.borderLimit) {
  44531. away = this.borderLimit;
  44532. }
  44533. var intensity = 1.0 - (away / this.borderLimit);
  44534. if (intensity < 0) {
  44535. return false;
  44536. }
  44537. if (intensity > 1.0) {
  44538. intensity = 1.0;
  44539. }
  44540. // Position
  44541. var centerX = globalViewport.x + globalViewport.width / 2;
  44542. var centerY = globalViewport.y + globalViewport.height / 2;
  44543. var distX = centerX - this._positionX;
  44544. var distY = centerY - this._positionY;
  44545. // Effects
  44546. engine.enableEffect(this._effect);
  44547. engine.setState(false);
  44548. engine.setDepthBuffer(false);
  44549. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44550. // VBOs
  44551. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  44552. // Flares
  44553. for (var index = 0; index < this.lensFlares.length; index++) {
  44554. var flare = this.lensFlares[index];
  44555. var x = centerX - (distX * flare.position);
  44556. var y = centerY - (distY * flare.position);
  44557. var cw = flare.size;
  44558. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  44559. var cx = 2 * (x / globalViewport.width) - 1.0;
  44560. var cy = 1.0 - 2 * (y / globalViewport.height);
  44561. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  44562. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  44563. // Texture
  44564. this._effect.setTexture("textureSampler", flare.texture);
  44565. // Color
  44566. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  44567. // Draw order
  44568. engine.draw(true, 0, 6);
  44569. }
  44570. engine.setDepthBuffer(true);
  44571. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44572. return true;
  44573. };
  44574. LensFlareSystem.prototype.dispose = function () {
  44575. if (this._vertexBuffer) {
  44576. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  44577. this._vertexBuffer = null;
  44578. }
  44579. if (this._indexBuffer) {
  44580. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44581. this._indexBuffer = null;
  44582. }
  44583. while (this.lensFlares.length) {
  44584. this.lensFlares[0].dispose();
  44585. }
  44586. // Remove from scene
  44587. var index = this._scene.lensFlareSystems.indexOf(this);
  44588. this._scene.lensFlareSystems.splice(index, 1);
  44589. };
  44590. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  44591. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  44592. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  44593. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  44594. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  44595. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  44596. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  44597. var parsedFlare = parsedLensFlareSystem.flares[index];
  44598. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  44599. }
  44600. return lensFlareSystem;
  44601. };
  44602. LensFlareSystem.prototype.serialize = function () {
  44603. var serializationObject = {};
  44604. serializationObject.id = this.id;
  44605. serializationObject.name = this.name;
  44606. serializationObject.emitterId = this.getEmitter().id;
  44607. serializationObject.borderLimit = this.borderLimit;
  44608. serializationObject.flares = [];
  44609. for (var index = 0; index < this.lensFlares.length; index++) {
  44610. var flare = this.lensFlares[index];
  44611. serializationObject.flares.push({
  44612. size: flare.size,
  44613. position: flare.position,
  44614. color: flare.color.asArray(),
  44615. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  44616. });
  44617. }
  44618. return serializationObject;
  44619. };
  44620. return LensFlareSystem;
  44621. })();
  44622. BABYLON.LensFlareSystem = LensFlareSystem;
  44623. })(BABYLON || (BABYLON = {}));
  44624. var BABYLON;
  44625. (function (BABYLON) {
  44626. // We're mainly based on the logic defined into the FreeCamera code
  44627. var DeviceOrientationCamera = (function (_super) {
  44628. __extends(DeviceOrientationCamera, _super);
  44629. //-- end properties for backward compatibility for inputs
  44630. function DeviceOrientationCamera(name, position, scene) {
  44631. _super.call(this, name, position, scene);
  44632. this.inputs.addDeviceOrientation();
  44633. }
  44634. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  44635. //-- Begin properties for backward compatibility for inputs
  44636. get: function () {
  44637. return 0;
  44638. },
  44639. set: function (value) {
  44640. },
  44641. enumerable: true,
  44642. configurable: true
  44643. });
  44644. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  44645. get: function () {
  44646. return 0;
  44647. },
  44648. set: function (value) {
  44649. },
  44650. enumerable: true,
  44651. configurable: true
  44652. });
  44653. DeviceOrientationCamera.prototype.getTypeName = function () {
  44654. return "DeviceOrientationCamera";
  44655. };
  44656. return DeviceOrientationCamera;
  44657. })(BABYLON.FreeCamera);
  44658. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  44659. })(BABYLON || (BABYLON = {}));
  44660. var BABYLON;
  44661. (function (BABYLON) {
  44662. // We're mainly based on the logic defined into the FreeCamera code
  44663. var UniversalCamera = (function (_super) {
  44664. __extends(UniversalCamera, _super);
  44665. //-- end properties for backward compatibility for inputs
  44666. function UniversalCamera(name, position, scene) {
  44667. _super.call(this, name, position, scene);
  44668. this.inputs.addGamepad();
  44669. }
  44670. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  44671. //-- Begin properties for backward compatibility for inputs
  44672. get: function () {
  44673. var gamepad = this.inputs.attached["gamepad"];
  44674. if (gamepad)
  44675. return gamepad.gamepadAngularSensibility;
  44676. },
  44677. set: function (value) {
  44678. var gamepad = this.inputs.attached["gamepad"];
  44679. if (gamepad)
  44680. gamepad.gamepadAngularSensibility = value;
  44681. },
  44682. enumerable: true,
  44683. configurable: true
  44684. });
  44685. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  44686. get: function () {
  44687. var gamepad = this.inputs.attached["gamepad"];
  44688. if (gamepad)
  44689. return gamepad.gamepadMoveSensibility;
  44690. },
  44691. set: function (value) {
  44692. var gamepad = this.inputs.attached["gamepad"];
  44693. if (gamepad)
  44694. gamepad.gamepadMoveSensibility = value;
  44695. },
  44696. enumerable: true,
  44697. configurable: true
  44698. });
  44699. UniversalCamera.prototype.getTypeName = function () {
  44700. return "UniversalCamera";
  44701. };
  44702. return UniversalCamera;
  44703. })(BABYLON.TouchCamera);
  44704. BABYLON.UniversalCamera = UniversalCamera;
  44705. })(BABYLON || (BABYLON = {}));
  44706. var BABYLON;
  44707. (function (BABYLON) {
  44708. var Gamepads = (function () {
  44709. function Gamepads(ongamedpadconnected) {
  44710. var _this = this;
  44711. this.babylonGamepads = [];
  44712. this.oneGamepadConnected = false;
  44713. this.isMonitoring = false;
  44714. this.gamepadEventSupported = 'GamepadEvent' in window;
  44715. this.gamepadSupportAvailable = (navigator.getGamepads ||
  44716. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  44717. this._callbackGamepadConnected = ongamedpadconnected;
  44718. if (this.gamepadSupportAvailable) {
  44719. // Checking if the gamepad connected event is supported (like in Firefox)
  44720. if (this.gamepadEventSupported) {
  44721. this._onGamepadConnectedEvent = function (evt) {
  44722. _this._onGamepadConnected(evt);
  44723. };
  44724. this._onGamepadDisonnectedEvent = function (evt) {
  44725. _this._onGamepadDisconnected(evt);
  44726. };
  44727. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44728. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44729. }
  44730. else {
  44731. this._startMonitoringGamepads();
  44732. }
  44733. }
  44734. }
  44735. Gamepads.prototype.dispose = function () {
  44736. if (Gamepads.gamepadDOMInfo) {
  44737. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44738. }
  44739. if (this._onGamepadConnectedEvent) {
  44740. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44741. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44742. this._onGamepadConnectedEvent = null;
  44743. this._onGamepadDisonnectedEvent = null;
  44744. }
  44745. };
  44746. Gamepads.prototype._onGamepadConnected = function (evt) {
  44747. var newGamepad = this._addNewGamepad(evt.gamepad);
  44748. if (this._callbackGamepadConnected)
  44749. this._callbackGamepadConnected(newGamepad);
  44750. this._startMonitoringGamepads();
  44751. };
  44752. Gamepads.prototype._addNewGamepad = function (gamepad) {
  44753. if (!this.oneGamepadConnected) {
  44754. this.oneGamepadConnected = true;
  44755. if (Gamepads.gamepadDOMInfo) {
  44756. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44757. Gamepads.gamepadDOMInfo = null;
  44758. }
  44759. }
  44760. var newGamepad;
  44761. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  44762. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  44763. }
  44764. else {
  44765. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  44766. }
  44767. this.babylonGamepads.push(newGamepad);
  44768. return newGamepad;
  44769. };
  44770. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  44771. // Remove the gamepad from the list of gamepads to monitor.
  44772. for (var i in this.babylonGamepads) {
  44773. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  44774. this.babylonGamepads.splice(+i, 1);
  44775. break;
  44776. }
  44777. }
  44778. // If no gamepads are left, stop the polling loop.
  44779. if (this.babylonGamepads.length == 0) {
  44780. this._stopMonitoringGamepads();
  44781. }
  44782. };
  44783. Gamepads.prototype._startMonitoringGamepads = function () {
  44784. if (!this.isMonitoring) {
  44785. this.isMonitoring = true;
  44786. this._checkGamepadsStatus();
  44787. }
  44788. };
  44789. Gamepads.prototype._stopMonitoringGamepads = function () {
  44790. this.isMonitoring = false;
  44791. };
  44792. Gamepads.prototype._checkGamepadsStatus = function () {
  44793. var _this = this;
  44794. // updating gamepad objects
  44795. this._updateGamepadObjects();
  44796. for (var i in this.babylonGamepads) {
  44797. this.babylonGamepads[i].update();
  44798. }
  44799. if (this.isMonitoring) {
  44800. if (window.requestAnimationFrame) {
  44801. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44802. }
  44803. else if (window.mozRequestAnimationFrame) {
  44804. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44805. }
  44806. else if (window.webkitRequestAnimationFrame) {
  44807. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44808. }
  44809. }
  44810. };
  44811. // This function is called only on Chrome, which does not yet support
  44812. // connection/disconnection events, but requires you to monitor
  44813. // an array for changes.
  44814. Gamepads.prototype._updateGamepadObjects = function () {
  44815. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  44816. for (var i = 0; i < gamepads.length; i++) {
  44817. if (gamepads[i]) {
  44818. if (!(gamepads[i].index in this.babylonGamepads)) {
  44819. var newGamepad = this._addNewGamepad(gamepads[i]);
  44820. if (this._callbackGamepadConnected) {
  44821. this._callbackGamepadConnected(newGamepad);
  44822. }
  44823. }
  44824. else {
  44825. this.babylonGamepads[i].browserGamepad = gamepads[i];
  44826. }
  44827. }
  44828. }
  44829. };
  44830. return Gamepads;
  44831. })();
  44832. BABYLON.Gamepads = Gamepads;
  44833. var StickValues = (function () {
  44834. function StickValues(x, y) {
  44835. this.x = x;
  44836. this.y = y;
  44837. }
  44838. return StickValues;
  44839. })();
  44840. BABYLON.StickValues = StickValues;
  44841. var Gamepad = (function () {
  44842. function Gamepad(id, index, browserGamepad) {
  44843. this.id = id;
  44844. this.index = index;
  44845. this.browserGamepad = browserGamepad;
  44846. if (this.browserGamepad.axes.length >= 2) {
  44847. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  44848. }
  44849. if (this.browserGamepad.axes.length >= 4) {
  44850. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  44851. }
  44852. }
  44853. Gamepad.prototype.onleftstickchanged = function (callback) {
  44854. this._onleftstickchanged = callback;
  44855. };
  44856. Gamepad.prototype.onrightstickchanged = function (callback) {
  44857. this._onrightstickchanged = callback;
  44858. };
  44859. Object.defineProperty(Gamepad.prototype, "leftStick", {
  44860. get: function () {
  44861. return this._leftStick;
  44862. },
  44863. set: function (newValues) {
  44864. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  44865. this._onleftstickchanged(newValues);
  44866. }
  44867. this._leftStick = newValues;
  44868. },
  44869. enumerable: true,
  44870. configurable: true
  44871. });
  44872. Object.defineProperty(Gamepad.prototype, "rightStick", {
  44873. get: function () {
  44874. return this._rightStick;
  44875. },
  44876. set: function (newValues) {
  44877. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  44878. this._onrightstickchanged(newValues);
  44879. }
  44880. this._rightStick = newValues;
  44881. },
  44882. enumerable: true,
  44883. configurable: true
  44884. });
  44885. Gamepad.prototype.update = function () {
  44886. if (this._leftStick) {
  44887. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  44888. }
  44889. if (this._rightStick) {
  44890. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  44891. }
  44892. };
  44893. return Gamepad;
  44894. })();
  44895. BABYLON.Gamepad = Gamepad;
  44896. var GenericPad = (function (_super) {
  44897. __extends(GenericPad, _super);
  44898. function GenericPad(id, index, gamepad) {
  44899. _super.call(this, id, index, gamepad);
  44900. this.id = id;
  44901. this.index = index;
  44902. this.gamepad = gamepad;
  44903. this._buttons = new Array(gamepad.buttons.length);
  44904. }
  44905. GenericPad.prototype.onbuttondown = function (callback) {
  44906. this._onbuttondown = callback;
  44907. };
  44908. GenericPad.prototype.onbuttonup = function (callback) {
  44909. this._onbuttonup = callback;
  44910. };
  44911. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  44912. if (newValue !== currentValue) {
  44913. if (this._onbuttondown && newValue === 1) {
  44914. this._onbuttondown(buttonIndex);
  44915. }
  44916. if (this._onbuttonup && newValue === 0) {
  44917. this._onbuttonup(buttonIndex);
  44918. }
  44919. }
  44920. return newValue;
  44921. };
  44922. GenericPad.prototype.update = function () {
  44923. _super.prototype.update.call(this);
  44924. for (var index = 0; index < this._buttons.length; index++) {
  44925. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  44926. }
  44927. };
  44928. return GenericPad;
  44929. })(Gamepad);
  44930. BABYLON.GenericPad = GenericPad;
  44931. (function (Xbox360Button) {
  44932. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  44933. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  44934. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  44935. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  44936. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  44937. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  44938. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  44939. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  44940. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  44941. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  44942. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  44943. var Xbox360Button = BABYLON.Xbox360Button;
  44944. (function (Xbox360Dpad) {
  44945. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  44946. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  44947. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  44948. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  44949. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  44950. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  44951. var Xbox360Pad = (function (_super) {
  44952. __extends(Xbox360Pad, _super);
  44953. function Xbox360Pad() {
  44954. _super.apply(this, arguments);
  44955. this._leftTrigger = 0;
  44956. this._rightTrigger = 0;
  44957. this._buttonA = 0;
  44958. this._buttonB = 0;
  44959. this._buttonX = 0;
  44960. this._buttonY = 0;
  44961. this._buttonBack = 0;
  44962. this._buttonStart = 0;
  44963. this._buttonLB = 0;
  44964. this._buttonRB = 0;
  44965. this._buttonLeftStick = 0;
  44966. this._buttonRightStick = 0;
  44967. this._dPadUp = 0;
  44968. this._dPadDown = 0;
  44969. this._dPadLeft = 0;
  44970. this._dPadRight = 0;
  44971. }
  44972. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  44973. this._onlefttriggerchanged = callback;
  44974. };
  44975. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  44976. this._onrighttriggerchanged = callback;
  44977. };
  44978. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  44979. get: function () {
  44980. return this._leftTrigger;
  44981. },
  44982. set: function (newValue) {
  44983. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  44984. this._onlefttriggerchanged(newValue);
  44985. }
  44986. this._leftTrigger = newValue;
  44987. },
  44988. enumerable: true,
  44989. configurable: true
  44990. });
  44991. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  44992. get: function () {
  44993. return this._rightTrigger;
  44994. },
  44995. set: function (newValue) {
  44996. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  44997. this._onrighttriggerchanged(newValue);
  44998. }
  44999. this._rightTrigger = newValue;
  45000. },
  45001. enumerable: true,
  45002. configurable: true
  45003. });
  45004. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45005. this._onbuttondown = callback;
  45006. };
  45007. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45008. this._onbuttonup = callback;
  45009. };
  45010. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45011. this._ondpaddown = callback;
  45012. };
  45013. Xbox360Pad.prototype.ondpadup = function (callback) {
  45014. this._ondpadup = callback;
  45015. };
  45016. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45017. if (newValue !== currentValue) {
  45018. if (this._onbuttondown && newValue === 1) {
  45019. this._onbuttondown(buttonType);
  45020. }
  45021. if (this._onbuttonup && newValue === 0) {
  45022. this._onbuttonup(buttonType);
  45023. }
  45024. }
  45025. return newValue;
  45026. };
  45027. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45028. if (newValue !== currentValue) {
  45029. if (this._ondpaddown && newValue === 1) {
  45030. this._ondpaddown(buttonType);
  45031. }
  45032. if (this._ondpadup && newValue === 0) {
  45033. this._ondpadup(buttonType);
  45034. }
  45035. }
  45036. return newValue;
  45037. };
  45038. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45039. get: function () {
  45040. return this._buttonA;
  45041. },
  45042. set: function (value) {
  45043. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45044. },
  45045. enumerable: true,
  45046. configurable: true
  45047. });
  45048. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45049. get: function () {
  45050. return this._buttonB;
  45051. },
  45052. set: function (value) {
  45053. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45054. },
  45055. enumerable: true,
  45056. configurable: true
  45057. });
  45058. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45059. get: function () {
  45060. return this._buttonX;
  45061. },
  45062. set: function (value) {
  45063. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45064. },
  45065. enumerable: true,
  45066. configurable: true
  45067. });
  45068. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45069. get: function () {
  45070. return this._buttonY;
  45071. },
  45072. set: function (value) {
  45073. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45074. },
  45075. enumerable: true,
  45076. configurable: true
  45077. });
  45078. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45079. get: function () {
  45080. return this._buttonStart;
  45081. },
  45082. set: function (value) {
  45083. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45084. },
  45085. enumerable: true,
  45086. configurable: true
  45087. });
  45088. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45089. get: function () {
  45090. return this._buttonBack;
  45091. },
  45092. set: function (value) {
  45093. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45094. },
  45095. enumerable: true,
  45096. configurable: true
  45097. });
  45098. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45099. get: function () {
  45100. return this._buttonLB;
  45101. },
  45102. set: function (value) {
  45103. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45104. },
  45105. enumerable: true,
  45106. configurable: true
  45107. });
  45108. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45109. get: function () {
  45110. return this._buttonRB;
  45111. },
  45112. set: function (value) {
  45113. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45114. },
  45115. enumerable: true,
  45116. configurable: true
  45117. });
  45118. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45119. get: function () {
  45120. return this._buttonLeftStick;
  45121. },
  45122. set: function (value) {
  45123. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45124. },
  45125. enumerable: true,
  45126. configurable: true
  45127. });
  45128. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45129. get: function () {
  45130. return this._buttonRightStick;
  45131. },
  45132. set: function (value) {
  45133. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45134. },
  45135. enumerable: true,
  45136. configurable: true
  45137. });
  45138. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45139. get: function () {
  45140. return this._dPadUp;
  45141. },
  45142. set: function (value) {
  45143. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45144. },
  45145. enumerable: true,
  45146. configurable: true
  45147. });
  45148. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45149. get: function () {
  45150. return this._dPadDown;
  45151. },
  45152. set: function (value) {
  45153. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45154. },
  45155. enumerable: true,
  45156. configurable: true
  45157. });
  45158. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45159. get: function () {
  45160. return this._dPadLeft;
  45161. },
  45162. set: function (value) {
  45163. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45164. },
  45165. enumerable: true,
  45166. configurable: true
  45167. });
  45168. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45169. get: function () {
  45170. return this._dPadRight;
  45171. },
  45172. set: function (value) {
  45173. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45174. },
  45175. enumerable: true,
  45176. configurable: true
  45177. });
  45178. Xbox360Pad.prototype.update = function () {
  45179. _super.prototype.update.call(this);
  45180. this.buttonA = this.browserGamepad.buttons[0].value;
  45181. this.buttonB = this.browserGamepad.buttons[1].value;
  45182. this.buttonX = this.browserGamepad.buttons[2].value;
  45183. this.buttonY = this.browserGamepad.buttons[3].value;
  45184. this.buttonLB = this.browserGamepad.buttons[4].value;
  45185. this.buttonRB = this.browserGamepad.buttons[5].value;
  45186. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45187. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45188. this.buttonBack = this.browserGamepad.buttons[8].value;
  45189. this.buttonStart = this.browserGamepad.buttons[9].value;
  45190. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45191. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45192. this.dPadUp = this.browserGamepad.buttons[12].value;
  45193. this.dPadDown = this.browserGamepad.buttons[13].value;
  45194. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45195. this.dPadRight = this.browserGamepad.buttons[15].value;
  45196. };
  45197. return Xbox360Pad;
  45198. })(Gamepad);
  45199. BABYLON.Xbox360Pad = Xbox360Pad;
  45200. })(BABYLON || (BABYLON = {}));
  45201. var BABYLON;
  45202. (function (BABYLON) {
  45203. // We're mainly based on the logic defined into the FreeCamera code
  45204. var GamepadCamera = (function (_super) {
  45205. __extends(GamepadCamera, _super);
  45206. //-- end properties for backward compatibility for inputs
  45207. function GamepadCamera(name, position, scene) {
  45208. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  45209. _super.call(this, name, position, scene);
  45210. }
  45211. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  45212. //-- Begin properties for backward compatibility for inputs
  45213. get: function () {
  45214. var gamepad = this.inputs.attached["gamepad"];
  45215. if (gamepad)
  45216. return gamepad.gamepadAngularSensibility;
  45217. },
  45218. set: function (value) {
  45219. var gamepad = this.inputs.attached["gamepad"];
  45220. if (gamepad)
  45221. gamepad.gamepadAngularSensibility = value;
  45222. },
  45223. enumerable: true,
  45224. configurable: true
  45225. });
  45226. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  45227. get: function () {
  45228. var gamepad = this.inputs.attached["gamepad"];
  45229. if (gamepad)
  45230. return gamepad.gamepadMoveSensibility;
  45231. },
  45232. set: function (value) {
  45233. var gamepad = this.inputs.attached["gamepad"];
  45234. if (gamepad)
  45235. gamepad.gamepadMoveSensibility = value;
  45236. },
  45237. enumerable: true,
  45238. configurable: true
  45239. });
  45240. GamepadCamera.prototype.getTypeName = function () {
  45241. return "GamepadCamera";
  45242. };
  45243. return GamepadCamera;
  45244. })(BABYLON.UniversalCamera);
  45245. BABYLON.GamepadCamera = GamepadCamera;
  45246. })(BABYLON || (BABYLON = {}));
  45247. var BABYLON;
  45248. (function (BABYLON) {
  45249. var Analyser = (function () {
  45250. function Analyser(scene) {
  45251. this.SMOOTHING = 0.75;
  45252. this.FFT_SIZE = 512;
  45253. this.BARGRAPHAMPLITUDE = 256;
  45254. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45255. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45256. this._scene = scene;
  45257. this._audioEngine = BABYLON.Engine.audioEngine;
  45258. if (this._audioEngine.canUseWebAudio) {
  45259. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45260. this._webAudioAnalyser.minDecibels = -140;
  45261. this._webAudioAnalyser.maxDecibels = 0;
  45262. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45263. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45264. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45265. }
  45266. }
  45267. Analyser.prototype.getFrequencyBinCount = function () {
  45268. if (this._audioEngine.canUseWebAudio) {
  45269. return this._webAudioAnalyser.frequencyBinCount;
  45270. }
  45271. else {
  45272. return 0;
  45273. }
  45274. };
  45275. Analyser.prototype.getByteFrequencyData = function () {
  45276. if (this._audioEngine.canUseWebAudio) {
  45277. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45278. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45279. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45280. }
  45281. return this._byteFreqs;
  45282. };
  45283. Analyser.prototype.getByteTimeDomainData = function () {
  45284. if (this._audioEngine.canUseWebAudio) {
  45285. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45286. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45287. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45288. }
  45289. return this._byteTime;
  45290. };
  45291. Analyser.prototype.getFloatFrequencyData = function () {
  45292. if (this._audioEngine.canUseWebAudio) {
  45293. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45294. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45295. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45296. }
  45297. return this._floatFreqs;
  45298. };
  45299. Analyser.prototype.drawDebugCanvas = function () {
  45300. var _this = this;
  45301. if (this._audioEngine.canUseWebAudio) {
  45302. if (!this._debugCanvas) {
  45303. this._debugCanvas = document.createElement("canvas");
  45304. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45305. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45306. this._debugCanvas.style.position = "absolute";
  45307. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45308. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45309. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45310. document.body.appendChild(this._debugCanvas);
  45311. this._registerFunc = function () {
  45312. _this.drawDebugCanvas();
  45313. };
  45314. this._scene.registerBeforeRender(this._registerFunc);
  45315. }
  45316. if (this._registerFunc) {
  45317. var workingArray = this.getByteFrequencyData();
  45318. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45319. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45320. // Draw the frequency domain chart.
  45321. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45322. var value = workingArray[i];
  45323. var percent = value / this.BARGRAPHAMPLITUDE;
  45324. var height = this.DEBUGCANVASSIZE.height * percent;
  45325. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45326. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45327. var hue = i / this.getFrequencyBinCount() * 360;
  45328. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45329. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45330. }
  45331. }
  45332. }
  45333. };
  45334. Analyser.prototype.stopDebugCanvas = function () {
  45335. if (this._debugCanvas) {
  45336. this._scene.unregisterBeforeRender(this._registerFunc);
  45337. this._registerFunc = null;
  45338. document.body.removeChild(this._debugCanvas);
  45339. this._debugCanvas = null;
  45340. this._debugCanvasContext = null;
  45341. }
  45342. };
  45343. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45344. if (this._audioEngine.canUseWebAudio) {
  45345. inputAudioNode.connect(this._webAudioAnalyser);
  45346. this._webAudioAnalyser.connect(outputAudioNode);
  45347. }
  45348. };
  45349. Analyser.prototype.dispose = function () {
  45350. if (this._audioEngine.canUseWebAudio) {
  45351. this._webAudioAnalyser.disconnect();
  45352. }
  45353. };
  45354. return Analyser;
  45355. })();
  45356. BABYLON.Analyser = Analyser;
  45357. })(BABYLON || (BABYLON = {}));
  45358. var BABYLON;
  45359. (function (BABYLON) {
  45360. var DepthRenderer = (function () {
  45361. function DepthRenderer(scene, type) {
  45362. var _this = this;
  45363. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  45364. this._viewMatrix = BABYLON.Matrix.Zero();
  45365. this._projectionMatrix = BABYLON.Matrix.Zero();
  45366. this._transformMatrix = BABYLON.Matrix.Zero();
  45367. this._worldViewProjection = BABYLON.Matrix.Zero();
  45368. this._scene = scene;
  45369. var engine = scene.getEngine();
  45370. // Render target
  45371. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  45372. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45373. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45374. this._depthMap.refreshRate = 1;
  45375. this._depthMap.renderParticles = false;
  45376. this._depthMap.renderList = null;
  45377. // set default depth value to 1.0 (far away)
  45378. this._depthMap.onClearObservable.add(function (engine) {
  45379. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  45380. });
  45381. // Custom render function
  45382. var renderSubMesh = function (subMesh) {
  45383. var mesh = subMesh.getRenderingMesh();
  45384. var scene = _this._scene;
  45385. var engine = scene.getEngine();
  45386. // Culling
  45387. engine.setState(subMesh.getMaterial().backFaceCulling);
  45388. // Managing instances
  45389. var batch = mesh._getInstancesRenderList(subMesh._id);
  45390. if (batch.mustReturn) {
  45391. return;
  45392. }
  45393. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45394. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45395. engine.enableEffect(_this._effect);
  45396. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  45397. var material = subMesh.getMaterial();
  45398. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45399. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  45400. // Alpha test
  45401. if (material && material.needAlphaTesting()) {
  45402. var alphaTexture = material.getAlphaTestTexture();
  45403. _this._effect.setTexture("diffuseSampler", alphaTexture);
  45404. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45405. }
  45406. // Bones
  45407. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45408. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45409. }
  45410. // Draw
  45411. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  45412. }
  45413. };
  45414. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  45415. var index;
  45416. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45417. renderSubMesh(opaqueSubMeshes.data[index]);
  45418. }
  45419. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45420. renderSubMesh(alphaTestSubMeshes.data[index]);
  45421. }
  45422. };
  45423. }
  45424. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  45425. var material = subMesh.getMaterial();
  45426. if (material.disableDepthWrite) {
  45427. return false;
  45428. }
  45429. var defines = [];
  45430. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45431. var mesh = subMesh.getMesh();
  45432. var scene = mesh.getScene();
  45433. // Alpha test
  45434. if (material && material.needAlphaTesting()) {
  45435. defines.push("#define ALPHATEST");
  45436. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45437. attribs.push(BABYLON.VertexBuffer.UVKind);
  45438. defines.push("#define UV1");
  45439. }
  45440. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45441. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45442. defines.push("#define UV2");
  45443. }
  45444. }
  45445. // Bones
  45446. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45447. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45448. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45449. if (mesh.numBoneInfluencers > 4) {
  45450. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45451. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45452. }
  45453. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45454. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45455. }
  45456. else {
  45457. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45458. }
  45459. // Instances
  45460. if (useInstances) {
  45461. defines.push("#define INSTANCES");
  45462. attribs.push("world0");
  45463. attribs.push("world1");
  45464. attribs.push("world2");
  45465. attribs.push("world3");
  45466. }
  45467. // Get correct effect
  45468. var join = defines.join("\n");
  45469. if (this._cachedDefines !== join) {
  45470. this._cachedDefines = join;
  45471. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  45472. }
  45473. return this._effect.isReady();
  45474. };
  45475. DepthRenderer.prototype.getDepthMap = function () {
  45476. return this._depthMap;
  45477. };
  45478. // Methods
  45479. DepthRenderer.prototype.dispose = function () {
  45480. this._depthMap.dispose();
  45481. };
  45482. return DepthRenderer;
  45483. })();
  45484. BABYLON.DepthRenderer = DepthRenderer;
  45485. })(BABYLON || (BABYLON = {}));
  45486. var BABYLON;
  45487. (function (BABYLON) {
  45488. var SSAORenderingPipeline = (function (_super) {
  45489. __extends(SSAORenderingPipeline, _super);
  45490. /**
  45491. * @constructor
  45492. * @param {string} name - The rendering pipeline name
  45493. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45494. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  45495. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45496. */
  45497. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  45498. var _this = this;
  45499. _super.call(this, scene.getEngine(), name);
  45500. // Members
  45501. /**
  45502. * The PassPostProcess id in the pipeline that contains the original scene color
  45503. * @type {string}
  45504. */
  45505. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  45506. /**
  45507. * The SSAO PostProcess id in the pipeline
  45508. * @type {string}
  45509. */
  45510. this.SSAORenderEffect = "SSAORenderEffect";
  45511. /**
  45512. * The horizontal blur PostProcess id in the pipeline
  45513. * @type {string}
  45514. */
  45515. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  45516. /**
  45517. * The vertical blur PostProcess id in the pipeline
  45518. * @type {string}
  45519. */
  45520. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  45521. /**
  45522. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  45523. * @type {string}
  45524. */
  45525. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  45526. /**
  45527. * The output strength of the SSAO post-process. Default value is 1.0.
  45528. * @type {number}
  45529. */
  45530. this.totalStrength = 1.0;
  45531. /**
  45532. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  45533. * @type {number}
  45534. */
  45535. this.radius = 0.0001;
  45536. /**
  45537. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  45538. * Must not be equal to fallOff and superior to fallOff.
  45539. * Default value is 0.975
  45540. * @type {number}
  45541. */
  45542. this.area = 0.0075;
  45543. /**
  45544. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  45545. * Must not be equal to area and inferior to area.
  45546. * Default value is 0.0
  45547. * @type {number}
  45548. */
  45549. this.fallOff = 0.000001;
  45550. /**
  45551. * The base color of the SSAO post-process
  45552. * The final result is "base + ssao" between [0, 1]
  45553. * @type {number}
  45554. */
  45555. this.base = 0.5;
  45556. this._firstUpdate = true;
  45557. this._scene = scene;
  45558. // Set up assets
  45559. this._createRandomTexture();
  45560. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45561. var ssaoRatio = ratio.ssaoRatio || ratio;
  45562. var combineRatio = ratio.combineRatio || ratio;
  45563. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45564. this._createSSAOPostProcess(ssaoRatio);
  45565. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45566. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45567. this._createSSAOCombinePostProcess(combineRatio);
  45568. // Set up pipeline
  45569. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  45570. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  45571. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  45572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  45573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  45574. // Finish
  45575. scene.postProcessRenderPipelineManager.addPipeline(this);
  45576. if (cameras)
  45577. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45578. }
  45579. // Public Methods
  45580. /**
  45581. * Returns the horizontal blur PostProcess
  45582. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  45583. */
  45584. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  45585. return this._blurHPostProcess;
  45586. };
  45587. /**
  45588. * Returns the vertical blur PostProcess
  45589. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  45590. */
  45591. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  45592. return this._blurVPostProcess;
  45593. };
  45594. /**
  45595. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  45596. */
  45597. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45598. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45599. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45600. this._originalColorPostProcess = undefined;
  45601. this._ssaoPostProcess = undefined;
  45602. this._blurHPostProcess = undefined;
  45603. this._blurVPostProcess = undefined;
  45604. this._ssaoCombinePostProcess = undefined;
  45605. this._randomTexture.dispose();
  45606. if (disableDepthRender)
  45607. this._scene.disableDepthRenderer();
  45608. };
  45609. // Private Methods
  45610. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  45611. var _this = this;
  45612. var numSamples = 16;
  45613. var sampleSphere = [
  45614. 0.5381, 0.1856, -0.4319,
  45615. 0.1379, 0.2486, 0.4430,
  45616. 0.3371, 0.5679, -0.0057,
  45617. -0.6999, -0.0451, -0.0019,
  45618. 0.0689, -0.1598, -0.8547,
  45619. 0.0560, 0.0069, -0.1843,
  45620. -0.0146, 0.1402, 0.0762,
  45621. 0.0100, -0.1924, -0.0344,
  45622. -0.3577, -0.5301, -0.4358,
  45623. -0.3169, 0.1063, 0.0158,
  45624. 0.0103, -0.5869, 0.0046,
  45625. -0.0897, -0.4940, 0.3287,
  45626. 0.7119, -0.0154, -0.0918,
  45627. -0.0533, 0.0596, -0.5411,
  45628. 0.0352, -0.0631, 0.5460,
  45629. -0.4776, 0.2847, -0.0271
  45630. ];
  45631. var samplesFactor = 1.0 / numSamples;
  45632. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  45633. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  45634. "area", "fallOff", "base"
  45635. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  45636. this._ssaoPostProcess.onApply = function (effect) {
  45637. if (_this._firstUpdate) {
  45638. effect.setArray3("sampleSphere", sampleSphere);
  45639. effect.setFloat("samplesFactor", samplesFactor);
  45640. effect.setFloat("randTextureTiles", 4.0);
  45641. _this._firstUpdate = false;
  45642. }
  45643. effect.setFloat("totalStrength", _this.totalStrength);
  45644. effect.setFloat("radius", _this.radius);
  45645. effect.setFloat("area", _this.area);
  45646. effect.setFloat("fallOff", _this.fallOff);
  45647. effect.setFloat("base", _this.base);
  45648. effect.setTexture("textureSampler", _this._depthTexture);
  45649. effect.setTexture("randomSampler", _this._randomTexture);
  45650. };
  45651. };
  45652. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  45653. var _this = this;
  45654. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  45655. this._ssaoCombinePostProcess.onApply = function (effect) {
  45656. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  45657. };
  45658. };
  45659. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  45660. var size = 512;
  45661. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45662. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45663. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45664. var context = this._randomTexture.getContext();
  45665. var rand = function (min, max) {
  45666. return Math.random() * (max - min) + min;
  45667. };
  45668. var randVector = BABYLON.Vector3.Zero();
  45669. for (var x = 0; x < size; x++) {
  45670. for (var y = 0; y < size; y++) {
  45671. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  45672. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  45673. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  45674. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  45675. context.fillRect(x, y, 1, 1);
  45676. }
  45677. }
  45678. this._randomTexture.update(false);
  45679. };
  45680. return SSAORenderingPipeline;
  45681. })(BABYLON.PostProcessRenderPipeline);
  45682. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  45683. })(BABYLON || (BABYLON = {}));
  45684. var BABYLON;
  45685. (function (BABYLON) {
  45686. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  45687. var VolumetricLightScatteringPostProcess = (function (_super) {
  45688. __extends(VolumetricLightScatteringPostProcess, _super);
  45689. /**
  45690. * @constructor
  45691. * @param {string} name - The post-process name
  45692. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  45693. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  45694. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  45695. * @param {number} samples - The post-process quality, default 100
  45696. * @param {number} samplingMode - The post-process filtering mode
  45697. * @param {BABYLON.Engine} engine - The babylon engine
  45698. * @param {boolean} reusable - If the post-process is reusable
  45699. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  45700. */
  45701. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  45702. var _this = this;
  45703. if (samples === void 0) { samples = 100; }
  45704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45705. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  45706. this._screenCoordinates = BABYLON.Vector2.Zero();
  45707. /**
  45708. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  45709. * @type {Vector3}
  45710. */
  45711. this.customMeshPosition = BABYLON.Vector3.Zero();
  45712. /**
  45713. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  45714. * @type {boolean}
  45715. */
  45716. this.useCustomMeshPosition = false;
  45717. /**
  45718. * If the post-process should inverse the light scattering direction
  45719. * @type {boolean}
  45720. */
  45721. this.invert = true;
  45722. /**
  45723. * Array containing the excluded meshes not rendered in the internal pass
  45724. */
  45725. this.excludedMeshes = new Array();
  45726. /**
  45727. * Controls the overall intensity of the post-process
  45728. * @type {number}
  45729. */
  45730. this.exposure = 0.3;
  45731. /**
  45732. * Dissipates each sample's contribution in range [0, 1]
  45733. * @type {number}
  45734. */
  45735. this.decay = 0.96815;
  45736. /**
  45737. * Controls the overall intensity of each sample
  45738. * @type {number}
  45739. */
  45740. this.weight = 0.58767;
  45741. /**
  45742. * Controls the density of each sample
  45743. * @type {number}
  45744. */
  45745. this.density = 0.926;
  45746. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  45747. var engine = scene.getEngine();
  45748. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  45749. // Configure mesh
  45750. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  45751. // Configure
  45752. this._createPass(scene, ratio.passRatio || ratio);
  45753. this.onActivate = function (camera) {
  45754. if (!_this.isSupported) {
  45755. _this.dispose(camera);
  45756. }
  45757. _this.onActivate = null;
  45758. };
  45759. this.onApplyObservable.add(function (effect) {
  45760. _this._updateMeshScreenCoordinates(scene);
  45761. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  45762. effect.setFloat("exposure", _this.exposure);
  45763. effect.setFloat("decay", _this.decay);
  45764. effect.setFloat("weight", _this.weight);
  45765. effect.setFloat("density", _this.density);
  45766. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  45767. });
  45768. }
  45769. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  45770. get: function () {
  45771. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  45772. return false;
  45773. },
  45774. set: function (useDiffuseColor) {
  45775. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  45776. },
  45777. enumerable: true,
  45778. configurable: true
  45779. });
  45780. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  45781. var mesh = subMesh.getMesh();
  45782. // Render this.mesh as default
  45783. if (mesh === this.mesh) {
  45784. return mesh.material.isReady(mesh);
  45785. }
  45786. var defines = [];
  45787. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45788. var material = subMesh.getMaterial();
  45789. var needUV = false;
  45790. // Alpha test
  45791. if (material) {
  45792. if (material.needAlphaTesting()) {
  45793. defines.push("#define ALPHATEST");
  45794. }
  45795. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45796. attribs.push(BABYLON.VertexBuffer.UVKind);
  45797. defines.push("#define UV1");
  45798. }
  45799. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45800. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45801. defines.push("#define UV2");
  45802. }
  45803. }
  45804. // Bones
  45805. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45806. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45807. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45808. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45809. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45810. }
  45811. else {
  45812. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45813. }
  45814. // Instances
  45815. if (useInstances) {
  45816. defines.push("#define INSTANCES");
  45817. attribs.push("world0");
  45818. attribs.push("world1");
  45819. attribs.push("world2");
  45820. attribs.push("world3");
  45821. }
  45822. // Get correct effect
  45823. var join = defines.join("\n");
  45824. if (this._cachedDefines !== join) {
  45825. this._cachedDefines = join;
  45826. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  45827. }
  45828. return this._volumetricLightScatteringPass.isReady();
  45829. };
  45830. /**
  45831. * Sets the new light position for light scattering effect
  45832. * @param {BABYLON.Vector3} The new custom light position
  45833. */
  45834. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  45835. this.customMeshPosition = position;
  45836. };
  45837. /**
  45838. * Returns the light position for light scattering effect
  45839. * @return {BABYLON.Vector3} The custom light position
  45840. */
  45841. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  45842. return this.customMeshPosition;
  45843. };
  45844. /**
  45845. * Disposes the internal assets and detaches the post-process from the camera
  45846. */
  45847. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  45848. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  45849. if (rttIndex !== -1) {
  45850. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  45851. }
  45852. this._volumetricLightScatteringRTT.dispose();
  45853. _super.prototype.dispose.call(this, camera);
  45854. };
  45855. /**
  45856. * Returns the render target texture used by the post-process
  45857. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  45858. */
  45859. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  45860. return this._volumetricLightScatteringRTT;
  45861. };
  45862. // Private methods
  45863. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  45864. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  45865. return true;
  45866. }
  45867. return false;
  45868. };
  45869. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  45870. var _this = this;
  45871. var engine = scene.getEngine();
  45872. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  45873. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45874. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45875. this._volumetricLightScatteringRTT.renderList = null;
  45876. this._volumetricLightScatteringRTT.renderParticles = false;
  45877. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  45878. // Custom render function for submeshes
  45879. var renderSubMesh = function (subMesh) {
  45880. var mesh = subMesh.getRenderingMesh();
  45881. if (_this._meshExcluded(mesh)) {
  45882. return;
  45883. }
  45884. var scene = mesh.getScene();
  45885. var engine = scene.getEngine();
  45886. // Culling
  45887. engine.setState(subMesh.getMaterial().backFaceCulling);
  45888. // Managing instances
  45889. var batch = mesh._getInstancesRenderList(subMesh._id);
  45890. if (batch.mustReturn) {
  45891. return;
  45892. }
  45893. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45894. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45895. var effect = _this._volumetricLightScatteringPass;
  45896. if (mesh === _this.mesh) {
  45897. effect = subMesh.getMaterial().getEffect();
  45898. }
  45899. engine.enableEffect(effect);
  45900. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  45901. if (mesh === _this.mesh) {
  45902. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  45903. }
  45904. else {
  45905. var material = subMesh.getMaterial();
  45906. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  45907. // Alpha test
  45908. if (material && material.needAlphaTesting()) {
  45909. var alphaTexture = material.getAlphaTestTexture();
  45910. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  45911. if (alphaTexture) {
  45912. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45913. }
  45914. }
  45915. // Bones
  45916. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45917. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45918. }
  45919. }
  45920. // Draw
  45921. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  45922. }
  45923. };
  45924. // Render target texture callbacks
  45925. var savedSceneClearColor;
  45926. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  45927. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  45928. savedSceneClearColor = scene.clearColor;
  45929. scene.clearColor = sceneClearColor;
  45930. });
  45931. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  45932. scene.clearColor = savedSceneClearColor;
  45933. });
  45934. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  45935. var engine = scene.getEngine();
  45936. var index;
  45937. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45938. renderSubMesh(opaqueSubMeshes.data[index]);
  45939. }
  45940. engine.setAlphaTesting(true);
  45941. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45942. renderSubMesh(alphaTestSubMeshes.data[index]);
  45943. }
  45944. engine.setAlphaTesting(false);
  45945. if (transparentSubMeshes.length) {
  45946. // Sort sub meshes
  45947. for (index = 0; index < transparentSubMeshes.length; index++) {
  45948. var submesh = transparentSubMeshes.data[index];
  45949. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  45950. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  45951. }
  45952. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  45953. sortedArray.sort(function (a, b) {
  45954. // Alpha index first
  45955. if (a._alphaIndex > b._alphaIndex) {
  45956. return 1;
  45957. }
  45958. if (a._alphaIndex < b._alphaIndex) {
  45959. return -1;
  45960. }
  45961. // Then distance to camera
  45962. if (a._distanceToCamera < b._distanceToCamera) {
  45963. return 1;
  45964. }
  45965. if (a._distanceToCamera > b._distanceToCamera) {
  45966. return -1;
  45967. }
  45968. return 0;
  45969. });
  45970. // Render sub meshes
  45971. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45972. for (index = 0; index < sortedArray.length; index++) {
  45973. renderSubMesh(sortedArray[index]);
  45974. }
  45975. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45976. }
  45977. };
  45978. };
  45979. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  45980. var transform = scene.getTransformMatrix();
  45981. var meshPosition;
  45982. if (this.useCustomMeshPosition) {
  45983. meshPosition = this.customMeshPosition;
  45984. }
  45985. else if (this.attachedNode) {
  45986. meshPosition = this.attachedNode.position;
  45987. }
  45988. else {
  45989. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  45990. }
  45991. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  45992. this._screenCoordinates.x = pos.x / this._viewPort.width;
  45993. this._screenCoordinates.y = pos.y / this._viewPort.height;
  45994. if (this.invert)
  45995. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  45996. };
  45997. // Static methods
  45998. /**
  45999. * Creates a default mesh for the Volumeric Light Scattering post-process
  46000. * @param {string} The mesh name
  46001. * @param {BABYLON.Scene} The scene where to create the mesh
  46002. * @return {BABYLON.Mesh} the default mesh
  46003. */
  46004. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  46005. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  46006. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  46007. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  46008. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  46009. mesh.material = material;
  46010. return mesh;
  46011. };
  46012. __decorate([
  46013. BABYLON.serializeAsVector3()
  46014. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  46015. __decorate([
  46016. BABYLON.serialize()
  46017. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  46018. __decorate([
  46019. BABYLON.serialize()
  46020. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  46021. __decorate([
  46022. BABYLON.serializeAsMeshReference()
  46023. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  46024. __decorate([
  46025. BABYLON.serialize()
  46026. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  46027. __decorate([
  46028. BABYLON.serialize()
  46029. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  46030. __decorate([
  46031. BABYLON.serialize()
  46032. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  46033. __decorate([
  46034. BABYLON.serialize()
  46035. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  46036. __decorate([
  46037. BABYLON.serialize()
  46038. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  46039. return VolumetricLightScatteringPostProcess;
  46040. })(BABYLON.PostProcess);
  46041. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  46042. })(BABYLON || (BABYLON = {}));
  46043. // BABYLON.JS Chromatic Aberration GLSL Shader
  46044. // Author: Olivier Guyot
  46045. // Separates very slightly R, G and B colors on the edges of the screen
  46046. // Inspired by Francois Tarlier & Martins Upitis
  46047. var BABYLON;
  46048. (function (BABYLON) {
  46049. var LensRenderingPipeline = (function (_super) {
  46050. __extends(LensRenderingPipeline, _super);
  46051. /**
  46052. * @constructor
  46053. *
  46054. * Effect parameters are as follow:
  46055. * {
  46056. * chromatic_aberration: number; // from 0 to x (1 for realism)
  46057. * edge_blur: number; // from 0 to x (1 for realism)
  46058. * distortion: number; // from 0 to x (1 for realism)
  46059. * grain_amount: number; // from 0 to 1
  46060. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  46061. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  46062. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  46063. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  46064. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  46065. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  46066. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  46067. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  46068. * }
  46069. * Note: if an effect parameter is unset, effect is disabled
  46070. *
  46071. * @param {string} name - The rendering pipeline name
  46072. * @param {object} parameters - An object containing all parameters (see above)
  46073. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46074. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  46075. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46076. */
  46077. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  46078. var _this = this;
  46079. if (ratio === void 0) { ratio = 1.0; }
  46080. _super.call(this, scene.getEngine(), name);
  46081. // Lens effects can be of the following:
  46082. // - chromatic aberration (slight shift of RGB colors)
  46083. // - blur on the edge of the lens
  46084. // - lens distortion
  46085. // - depth-of-field blur & highlights enhancing
  46086. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  46087. // - grain effect (noise or custom texture)
  46088. // Two additional texture samplers are needed:
  46089. // - depth map (for depth-of-field)
  46090. // - grain texture
  46091. /**
  46092. * The chromatic aberration PostProcess id in the pipeline
  46093. * @type {string}
  46094. */
  46095. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  46096. /**
  46097. * The highlights enhancing PostProcess id in the pipeline
  46098. * @type {string}
  46099. */
  46100. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  46101. /**
  46102. * The depth-of-field PostProcess id in the pipeline
  46103. * @type {string}
  46104. */
  46105. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  46106. this._scene = scene;
  46107. // Fetch texture samplers
  46108. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46109. if (parameters.grain_texture) {
  46110. this._grainTexture = parameters.grain_texture;
  46111. }
  46112. else {
  46113. this._createGrainTexture();
  46114. }
  46115. // save parameters
  46116. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  46117. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  46118. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  46119. this._distortion = parameters.distortion ? parameters.distortion : 0;
  46120. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  46121. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  46122. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  46123. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  46124. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  46125. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  46126. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  46127. // Create effects
  46128. this._createChromaticAberrationPostProcess(ratio);
  46129. this._createHighlightsPostProcess(ratio);
  46130. this._createDepthOfFieldPostProcess(ratio / 4);
  46131. // Set up pipeline
  46132. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  46133. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  46134. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  46135. if (this._highlightsGain === -1) {
  46136. this._disableEffect(this.HighlightsEnhancingEffect, null);
  46137. }
  46138. // Finish
  46139. scene.postProcessRenderPipelineManager.addPipeline(this);
  46140. if (cameras) {
  46141. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46142. }
  46143. }
  46144. // public methods (self explanatory)
  46145. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  46146. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  46147. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  46148. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  46149. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  46150. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  46151. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  46152. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  46153. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  46154. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  46155. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  46156. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  46157. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  46158. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  46159. };
  46160. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  46161. this._highlightsPostProcess.updateEffect();
  46162. };
  46163. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  46164. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  46165. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  46166. this._highlightsGain = amount;
  46167. };
  46168. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  46169. if (this._highlightsGain === -1) {
  46170. this._highlightsGain = 1.0;
  46171. }
  46172. this._highlightsThreshold = amount;
  46173. };
  46174. LensRenderingPipeline.prototype.disableHighlights = function () {
  46175. this._highlightsGain = -1;
  46176. };
  46177. /**
  46178. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  46179. */
  46180. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46181. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46182. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46183. this._chromaticAberrationPostProcess = undefined;
  46184. this._highlightsPostProcess = undefined;
  46185. this._depthOfFieldPostProcess = undefined;
  46186. this._grainTexture.dispose();
  46187. if (disableDepthRender)
  46188. this._scene.disableDepthRenderer();
  46189. };
  46190. // colors shifting and distortion
  46191. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  46192. var _this = this;
  46193. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  46194. [], // samplers
  46195. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46196. this._chromaticAberrationPostProcess.onApply = function (effect) {
  46197. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  46198. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46199. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46200. };
  46201. };
  46202. // highlights enhancing
  46203. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  46204. var _this = this;
  46205. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  46206. [], // samplers
  46207. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  46208. this._highlightsPostProcess.onApply = function (effect) {
  46209. effect.setFloat('gain', _this._highlightsGain);
  46210. effect.setFloat('threshold', _this._highlightsThreshold);
  46211. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  46212. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46213. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46214. };
  46215. };
  46216. // colors shifting and distortion
  46217. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  46218. var _this = this;
  46219. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  46220. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  46221. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  46222. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46223. this._depthOfFieldPostProcess.onApply = function (effect) {
  46224. effect.setTexture("depthSampler", _this._depthTexture);
  46225. effect.setTexture("grainSampler", _this._grainTexture);
  46226. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  46227. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  46228. effect.setFloat('grain_amount', _this._grainAmount);
  46229. effect.setBool('blur_noise', _this._blurNoise);
  46230. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46231. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46232. effect.setFloat('distortion', _this._distortion);
  46233. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  46234. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  46235. effect.setFloat('aperture', _this._dofAperture);
  46236. effect.setFloat('darken', _this._dofDarken);
  46237. effect.setFloat('edge_blur', _this._edgeBlur);
  46238. effect.setBool('highlights', (_this._highlightsGain !== -1));
  46239. effect.setFloat('near', _this._scene.activeCamera.minZ);
  46240. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  46241. };
  46242. };
  46243. // creates a black and white random noise texture, 512x512
  46244. LensRenderingPipeline.prototype._createGrainTexture = function () {
  46245. var size = 512;
  46246. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46247. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46248. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46249. var context = this._grainTexture.getContext();
  46250. var rand = function (min, max) {
  46251. return Math.random() * (max - min) + min;
  46252. };
  46253. var value;
  46254. for (var x = 0; x < size; x++) {
  46255. for (var y = 0; y < size; y++) {
  46256. value = Math.floor(rand(0.42, 0.58) * 255);
  46257. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  46258. context.fillRect(x, y, 1, 1);
  46259. }
  46260. }
  46261. this._grainTexture.update(false);
  46262. };
  46263. return LensRenderingPipeline;
  46264. })(BABYLON.PostProcessRenderPipeline);
  46265. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  46266. })(BABYLON || (BABYLON = {}));
  46267. //
  46268. // This post-process allows the modification of rendered colors by using
  46269. // a 'look-up table' (LUT). This effect is also called Color Grading.
  46270. //
  46271. // The object needs to be provided an url to a texture containing the color
  46272. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  46273. // Use an image editing software to tweak the LUT to match your needs.
  46274. //
  46275. // For an example of a color LUT, see here:
  46276. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  46277. // For explanations on color grading, see here:
  46278. // http://udn.epicgames.com/Three/ColorGrading.html
  46279. //
  46280. var BABYLON;
  46281. (function (BABYLON) {
  46282. var ColorCorrectionPostProcess = (function (_super) {
  46283. __extends(ColorCorrectionPostProcess, _super);
  46284. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  46285. var _this = this;
  46286. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  46287. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46288. this._colorTableTexture.anisotropicFilteringLevel = 1;
  46289. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46290. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46291. this.onApply = function (effect) {
  46292. effect.setTexture("colorTable", _this._colorTableTexture);
  46293. };
  46294. }
  46295. return ColorCorrectionPostProcess;
  46296. })(BABYLON.PostProcess);
  46297. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  46298. })(BABYLON || (BABYLON = {}));
  46299. var BABYLON;
  46300. (function (BABYLON) {
  46301. var AnaglyphFreeCamera = (function (_super) {
  46302. __extends(AnaglyphFreeCamera, _super);
  46303. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  46304. _super.call(this, name, position, scene);
  46305. this.interaxialDistance = interaxialDistance;
  46306. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46307. }
  46308. AnaglyphFreeCamera.prototype.getTypeName = function () {
  46309. return "AnaglyphFreeCamera";
  46310. };
  46311. return AnaglyphFreeCamera;
  46312. })(BABYLON.FreeCamera);
  46313. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  46314. var AnaglyphArcRotateCamera = (function (_super) {
  46315. __extends(AnaglyphArcRotateCamera, _super);
  46316. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  46317. _super.call(this, name, alpha, beta, radius, target, scene);
  46318. this.interaxialDistance = interaxialDistance;
  46319. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46320. }
  46321. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  46322. return "AnaglyphArcRotateCamera";
  46323. };
  46324. return AnaglyphArcRotateCamera;
  46325. })(BABYLON.ArcRotateCamera);
  46326. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  46327. var AnaglyphGamepadCamera = (function (_super) {
  46328. __extends(AnaglyphGamepadCamera, _super);
  46329. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  46330. _super.call(this, name, position, scene);
  46331. this.interaxialDistance = interaxialDistance;
  46332. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46333. }
  46334. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  46335. return "AnaglyphGamepadCamera";
  46336. };
  46337. return AnaglyphGamepadCamera;
  46338. })(BABYLON.GamepadCamera);
  46339. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  46340. var AnaglyphUniversalCamera = (function (_super) {
  46341. __extends(AnaglyphUniversalCamera, _super);
  46342. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  46343. _super.call(this, name, position, scene);
  46344. this.interaxialDistance = interaxialDistance;
  46345. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46346. }
  46347. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  46348. return "AnaglyphUniversalCamera";
  46349. };
  46350. return AnaglyphUniversalCamera;
  46351. })(BABYLON.UniversalCamera);
  46352. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  46353. var StereoscopicFreeCamera = (function (_super) {
  46354. __extends(StereoscopicFreeCamera, _super);
  46355. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46356. _super.call(this, name, position, scene);
  46357. this.interaxialDistance = interaxialDistance;
  46358. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46359. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46360. }
  46361. StereoscopicFreeCamera.prototype.getTypeName = function () {
  46362. return "StereoscopicFreeCamera";
  46363. };
  46364. return StereoscopicFreeCamera;
  46365. })(BABYLON.FreeCamera);
  46366. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  46367. var StereoscopicArcRotateCamera = (function (_super) {
  46368. __extends(StereoscopicArcRotateCamera, _super);
  46369. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  46370. _super.call(this, name, alpha, beta, radius, target, scene);
  46371. this.interaxialDistance = interaxialDistance;
  46372. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46373. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46374. }
  46375. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  46376. return "StereoscopicArcRotateCamera";
  46377. };
  46378. return StereoscopicArcRotateCamera;
  46379. })(BABYLON.ArcRotateCamera);
  46380. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  46381. var StereoscopicGamepadCamera = (function (_super) {
  46382. __extends(StereoscopicGamepadCamera, _super);
  46383. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46384. _super.call(this, name, position, scene);
  46385. this.interaxialDistance = interaxialDistance;
  46386. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46387. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46388. }
  46389. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  46390. return "StereoscopicGamepadCamera";
  46391. };
  46392. return StereoscopicGamepadCamera;
  46393. })(BABYLON.GamepadCamera);
  46394. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  46395. var StereoscopicUniversalCamera = (function (_super) {
  46396. __extends(StereoscopicUniversalCamera, _super);
  46397. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46398. _super.call(this, name, position, scene);
  46399. this.interaxialDistance = interaxialDistance;
  46400. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46401. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46402. }
  46403. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  46404. return "StereoscopicUniversalCamera";
  46405. };
  46406. return StereoscopicUniversalCamera;
  46407. })(BABYLON.UniversalCamera);
  46408. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  46409. })(BABYLON || (BABYLON = {}));
  46410. var BABYLON;
  46411. (function (BABYLON) {
  46412. var HDRRenderingPipeline = (function (_super) {
  46413. __extends(HDRRenderingPipeline, _super);
  46414. /**
  46415. * @constructor
  46416. * @param {string} name - The rendering pipeline name
  46417. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46418. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  46419. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46420. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46421. */
  46422. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46423. var _this = this;
  46424. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46425. _super.call(this, scene.getEngine(), name);
  46426. /**
  46427. * Public members
  46428. */
  46429. // Gaussian Blur
  46430. /**
  46431. * Gaussian blur coefficient
  46432. * @type {number}
  46433. */
  46434. this.gaussCoeff = 0.3;
  46435. /**
  46436. * Gaussian blur mean
  46437. * @type {number}
  46438. */
  46439. this.gaussMean = 1.0;
  46440. /**
  46441. * Gaussian blur standard deviation
  46442. * @type {number}
  46443. */
  46444. this.gaussStandDev = 0.8;
  46445. /**
  46446. * Gaussian blur multiplier. Multiplies the blur effect
  46447. * @type {number}
  46448. */
  46449. this.gaussMultiplier = 4.0;
  46450. // HDR
  46451. /**
  46452. * Exposure, controls the overall intensity of the pipeline
  46453. * @type {number}
  46454. */
  46455. this.exposure = 1.0;
  46456. /**
  46457. * Minimum luminance that the post-process can output. Luminance is >= 0
  46458. * @type {number}
  46459. */
  46460. this.minimumLuminance = 1.0;
  46461. /**
  46462. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  46463. * @type {number}
  46464. */
  46465. this.maximumLuminance = 1e20;
  46466. /**
  46467. * Increase rate for luminance: eye adaptation speed to dark
  46468. * @type {number}
  46469. */
  46470. this.luminanceIncreaserate = 0.5;
  46471. /**
  46472. * Decrease rate for luminance: eye adaptation speed to bright
  46473. * @type {number}
  46474. */
  46475. this.luminanceDecreaseRate = 0.5;
  46476. // Bright pass
  46477. /**
  46478. * Minimum luminance needed to compute HDR
  46479. * @type {number}
  46480. */
  46481. this.brightThreshold = 0.8;
  46482. this._needUpdate = true;
  46483. this._scene = scene;
  46484. // Bright pass
  46485. this._createBrightPassPostProcess(scene, ratio);
  46486. // Down sample X4
  46487. this._createDownSampleX4PostProcess(scene, ratio);
  46488. // Create gaussian blur post-processes
  46489. this._createGaussianBlurPostProcess(scene, ratio);
  46490. // Texture adder
  46491. this._createTextureAdderPostProcess(scene, ratio);
  46492. // Luminance generator
  46493. this._createLuminanceGeneratorPostProcess(scene);
  46494. // HDR
  46495. this._createHDRPostProcess(scene, ratio);
  46496. // Pass postprocess
  46497. if (originalPostProcess === null) {
  46498. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46499. }
  46500. else {
  46501. this._originalPostProcess = originalPostProcess;
  46502. }
  46503. // Configure pipeline
  46504. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  46505. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  46506. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  46507. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  46508. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  46509. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  46510. var addDownSamplerPostProcess = function (id) {
  46511. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  46512. };
  46513. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46514. addDownSamplerPostProcess(i);
  46515. }
  46516. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  46517. // Finish
  46518. scene.postProcessRenderPipelineManager.addPipeline(this);
  46519. if (cameras !== null) {
  46520. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46521. }
  46522. this.update();
  46523. }
  46524. /**
  46525. * Tells the pipeline to update its post-processes
  46526. */
  46527. HDRRenderingPipeline.prototype.update = function () {
  46528. this._needUpdate = true;
  46529. };
  46530. /**
  46531. * Returns the current calculated luminance
  46532. */
  46533. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  46534. return this._hdrCurrentLuminance;
  46535. };
  46536. /**
  46537. * Returns the currently drawn luminance
  46538. */
  46539. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  46540. return this._hdrOutputLuminance;
  46541. };
  46542. /**
  46543. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  46544. */
  46545. HDRRenderingPipeline.prototype.dispose = function () {
  46546. this._originalPostProcess = undefined;
  46547. this._brightPassPostProcess = undefined;
  46548. this._downSampleX4PostProcess = undefined;
  46549. this._guassianBlurHPostProcess = undefined;
  46550. this._guassianBlurVPostProcess = undefined;
  46551. this._textureAdderPostProcess = undefined;
  46552. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46553. this._downSamplePostProcesses[i] = undefined;
  46554. }
  46555. this._hdrPostProcess = undefined;
  46556. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46557. };
  46558. /**
  46559. * Creates the HDR post-process and computes the luminance adaptation
  46560. */
  46561. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  46562. var _this = this;
  46563. var hdrLastLuminance = 0.0;
  46564. this._hdrOutputLuminance = -1.0;
  46565. this._hdrCurrentLuminance = 1.0;
  46566. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  46567. this._hdrPostProcess.onApply = function (effect) {
  46568. if (_this._hdrOutputLuminance < 0.0) {
  46569. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46570. }
  46571. else {
  46572. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  46573. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  46574. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  46575. }
  46576. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  46577. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  46578. }
  46579. else {
  46580. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46581. }
  46582. }
  46583. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  46584. hdrLastLuminance += scene.getEngine().getDeltaTime();
  46585. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46586. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46587. effect.setFloat("exposure", _this.exposure);
  46588. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  46589. _this._needUpdate = false;
  46590. };
  46591. };
  46592. /**
  46593. * Texture Adder post-process
  46594. */
  46595. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46596. var _this = this;
  46597. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  46598. this._textureAdderPostProcess.onApply = function (effect) {
  46599. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46600. };
  46601. };
  46602. /**
  46603. * Down sample X4 post-process
  46604. */
  46605. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46606. var _this = this;
  46607. var downSampleX4Offsets = new Array(32);
  46608. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  46609. this._downSampleX4PostProcess.onApply = function (effect) {
  46610. if (_this._needUpdate) {
  46611. var id = 0;
  46612. for (var i = -2; i < 2; i++) {
  46613. for (var j = -2; j < 2; j++) {
  46614. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  46615. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  46616. id += 2;
  46617. }
  46618. }
  46619. }
  46620. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46621. };
  46622. };
  46623. /**
  46624. * Bright pass post-process
  46625. */
  46626. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46627. var _this = this;
  46628. var brightOffsets = new Array(8);
  46629. var brightPassCallback = function (effect) {
  46630. if (_this._needUpdate) {
  46631. var sU = (1.0 / _this._brightPassPostProcess.width);
  46632. var sV = (1.0 / _this._brightPassPostProcess.height);
  46633. brightOffsets[0] = -0.5 * sU;
  46634. brightOffsets[1] = 0.5 * sV;
  46635. brightOffsets[2] = 0.5 * sU;
  46636. brightOffsets[3] = 0.5 * sV;
  46637. brightOffsets[4] = -0.5 * sU;
  46638. brightOffsets[5] = -0.5 * sV;
  46639. brightOffsets[6] = 0.5 * sU;
  46640. brightOffsets[7] = -0.5 * sV;
  46641. }
  46642. effect.setArray2("dsOffsets", brightOffsets);
  46643. effect.setFloat("brightThreshold", _this.brightThreshold);
  46644. };
  46645. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  46646. this._brightPassPostProcess.onApply = brightPassCallback;
  46647. };
  46648. /**
  46649. * Luminance generator. Creates the luminance post-process and down sample post-processes
  46650. */
  46651. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  46652. var _this = this;
  46653. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  46654. var luminanceOffsets = new Array(8);
  46655. var downSampleOffsets = new Array(18);
  46656. var halfDestPixelSize;
  46657. this._downSamplePostProcesses = new Array(lumSteps);
  46658. // Utils for luminance
  46659. var luminanceUpdateSourceOffsets = function (width, height) {
  46660. var sU = (1.0 / width);
  46661. var sV = (1.0 / height);
  46662. luminanceOffsets[0] = -0.5 * sU;
  46663. luminanceOffsets[1] = 0.5 * sV;
  46664. luminanceOffsets[2] = 0.5 * sU;
  46665. luminanceOffsets[3] = 0.5 * sV;
  46666. luminanceOffsets[4] = -0.5 * sU;
  46667. luminanceOffsets[5] = -0.5 * sV;
  46668. luminanceOffsets[6] = 0.5 * sU;
  46669. luminanceOffsets[7] = -0.5 * sV;
  46670. };
  46671. var luminanceUpdateDestOffsets = function (width, height) {
  46672. var id = 0;
  46673. for (var x = -1; x < 2; x++) {
  46674. for (var y = -1; y < 2; y++) {
  46675. downSampleOffsets[id] = (x) / width;
  46676. downSampleOffsets[id + 1] = (y) / height;
  46677. id += 2;
  46678. }
  46679. }
  46680. };
  46681. // Luminance callback
  46682. var luminanceCallback = function (effect) {
  46683. if (_this._needUpdate) {
  46684. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  46685. }
  46686. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46687. effect.setArray2("lumOffsets", luminanceOffsets);
  46688. };
  46689. // Down sample callbacks
  46690. var downSampleCallback = function (indice) {
  46691. var i = indice;
  46692. return function (effect) {
  46693. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46694. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46695. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  46696. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  46697. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  46698. effect.setArray2("dsOffsets", downSampleOffsets);
  46699. };
  46700. };
  46701. var downSampleAfterRenderCallback = function (effect) {
  46702. // Unpack result
  46703. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  46704. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  46705. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  46706. };
  46707. // Create luminance post-process
  46708. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  46709. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  46710. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  46711. // Create down sample post-processes
  46712. for (var i = lumSteps - 2; i >= 0; i--) {
  46713. var length = Math.pow(3, i);
  46714. ratio = { width: length, height: length };
  46715. var defines = "#define DOWN_SAMPLE\n";
  46716. if (i === 0) {
  46717. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  46718. }
  46719. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  46720. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  46721. if (i === 0) {
  46722. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  46723. }
  46724. }
  46725. };
  46726. /**
  46727. * Gaussian blur post-processes. Horizontal and Vertical
  46728. */
  46729. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  46730. var _this = this;
  46731. var blurOffsetsW = new Array(9);
  46732. var blurOffsetsH = new Array(9);
  46733. var blurWeights = new Array(9);
  46734. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  46735. // Utils for gaussian blur
  46736. var calculateBlurOffsets = function (height) {
  46737. var lastOutputDimensions = {
  46738. width: scene.getEngine().getRenderWidth(),
  46739. height: scene.getEngine().getRenderHeight()
  46740. };
  46741. for (var i = 0; i < 9; i++) {
  46742. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  46743. if (height) {
  46744. blurOffsetsH[i] = value;
  46745. }
  46746. else {
  46747. blurOffsetsW[i] = value;
  46748. }
  46749. }
  46750. };
  46751. var calculateWeights = function () {
  46752. var x = 0.0;
  46753. for (var i = 0; i < 9; i++) {
  46754. x = (i - 4.0) / 4.0;
  46755. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  46756. }
  46757. };
  46758. // Callback
  46759. var gaussianBlurCallback = function (height) {
  46760. return function (effect) {
  46761. if (_this._needUpdate) {
  46762. calculateWeights();
  46763. calculateBlurOffsets(height);
  46764. }
  46765. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  46766. effect.setArray("blurWeights", blurWeights);
  46767. effect.setFloat("multiplier", _this.gaussMultiplier);
  46768. };
  46769. };
  46770. // Create horizontal gaussian blur post-processes
  46771. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  46772. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  46773. // Create vertical gaussian blur post-process
  46774. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  46775. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  46776. };
  46777. // Luminance generator
  46778. HDRRenderingPipeline.LUM_STEPS = 6;
  46779. return HDRRenderingPipeline;
  46780. })(BABYLON.PostProcessRenderPipeline);
  46781. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  46782. })(BABYLON || (BABYLON = {}));
  46783. var BABYLON;
  46784. (function (BABYLON) {
  46785. var FaceAdjacencies = (function () {
  46786. function FaceAdjacencies() {
  46787. this.edges = new Array();
  46788. this.edgesConnectedCount = 0;
  46789. }
  46790. return FaceAdjacencies;
  46791. })();
  46792. var EdgesRenderer = (function () {
  46793. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  46794. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  46795. if (epsilon === void 0) { epsilon = 0.95; }
  46796. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  46797. this.edgesWidthScalerForOrthographic = 1000.0;
  46798. this.edgesWidthScalerForPerspective = 50.0;
  46799. this._linesPositions = new Array();
  46800. this._linesNormals = new Array();
  46801. this._linesIndices = new Array();
  46802. this._buffers = new Array();
  46803. this._checkVerticesInsteadOfIndices = false;
  46804. this._source = source;
  46805. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  46806. this._epsilon = epsilon;
  46807. this._prepareRessources();
  46808. this._generateEdgesLines();
  46809. }
  46810. EdgesRenderer.prototype._prepareRessources = function () {
  46811. if (this._lineShader) {
  46812. return;
  46813. }
  46814. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  46815. attributes: ["position", "normal"],
  46816. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  46817. });
  46818. this._lineShader.disableDepthWrite = true;
  46819. this._lineShader.backFaceCulling = false;
  46820. };
  46821. EdgesRenderer.prototype.dispose = function () {
  46822. this._vb0.dispose();
  46823. this._vb1.dispose();
  46824. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  46825. this._lineShader.dispose();
  46826. };
  46827. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  46828. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  46829. return 0;
  46830. }
  46831. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  46832. return 1;
  46833. }
  46834. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  46835. return 2;
  46836. }
  46837. return -1;
  46838. };
  46839. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  46840. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  46841. return 0;
  46842. }
  46843. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  46844. return 1;
  46845. }
  46846. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  46847. return 2;
  46848. }
  46849. return -1;
  46850. };
  46851. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  46852. var needToCreateLine;
  46853. if (edge === undefined) {
  46854. needToCreateLine = true;
  46855. }
  46856. else {
  46857. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  46858. needToCreateLine = dotProduct < this._epsilon;
  46859. }
  46860. if (needToCreateLine) {
  46861. var offset = this._linesPositions.length / 3;
  46862. var normal = p0.subtract(p1);
  46863. normal.normalize();
  46864. // Positions
  46865. this._linesPositions.push(p0.x);
  46866. this._linesPositions.push(p0.y);
  46867. this._linesPositions.push(p0.z);
  46868. this._linesPositions.push(p0.x);
  46869. this._linesPositions.push(p0.y);
  46870. this._linesPositions.push(p0.z);
  46871. this._linesPositions.push(p1.x);
  46872. this._linesPositions.push(p1.y);
  46873. this._linesPositions.push(p1.z);
  46874. this._linesPositions.push(p1.x);
  46875. this._linesPositions.push(p1.y);
  46876. this._linesPositions.push(p1.z);
  46877. // Normals
  46878. this._linesNormals.push(p1.x);
  46879. this._linesNormals.push(p1.y);
  46880. this._linesNormals.push(p1.z);
  46881. this._linesNormals.push(-1);
  46882. this._linesNormals.push(p1.x);
  46883. this._linesNormals.push(p1.y);
  46884. this._linesNormals.push(p1.z);
  46885. this._linesNormals.push(1);
  46886. this._linesNormals.push(p0.x);
  46887. this._linesNormals.push(p0.y);
  46888. this._linesNormals.push(p0.z);
  46889. this._linesNormals.push(-1);
  46890. this._linesNormals.push(p0.x);
  46891. this._linesNormals.push(p0.y);
  46892. this._linesNormals.push(p0.z);
  46893. this._linesNormals.push(1);
  46894. // Indices
  46895. this._linesIndices.push(offset);
  46896. this._linesIndices.push(offset + 1);
  46897. this._linesIndices.push(offset + 2);
  46898. this._linesIndices.push(offset);
  46899. this._linesIndices.push(offset + 2);
  46900. this._linesIndices.push(offset + 3);
  46901. }
  46902. };
  46903. EdgesRenderer.prototype._generateEdgesLines = function () {
  46904. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46905. var indices = this._source.getIndices();
  46906. // First let's find adjacencies
  46907. var adjacencies = new Array();
  46908. var faceNormals = new Array();
  46909. var index;
  46910. var faceAdjacencies;
  46911. // Prepare faces
  46912. for (index = 0; index < indices.length; index += 3) {
  46913. faceAdjacencies = new FaceAdjacencies();
  46914. var p0Index = indices[index];
  46915. var p1Index = indices[index + 1];
  46916. var p2Index = indices[index + 2];
  46917. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  46918. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  46919. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  46920. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  46921. faceNormal.normalize();
  46922. faceNormals.push(faceNormal);
  46923. adjacencies.push(faceAdjacencies);
  46924. }
  46925. // Scan
  46926. for (index = 0; index < adjacencies.length; index++) {
  46927. faceAdjacencies = adjacencies[index];
  46928. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  46929. var otherFaceAdjacencies = adjacencies[otherIndex];
  46930. if (faceAdjacencies.edgesConnectedCount === 3) {
  46931. break;
  46932. }
  46933. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  46934. continue;
  46935. }
  46936. var otherP0 = indices[otherIndex * 3];
  46937. var otherP1 = indices[otherIndex * 3 + 1];
  46938. var otherP2 = indices[otherIndex * 3 + 2];
  46939. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  46940. var otherEdgeIndex;
  46941. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  46942. continue;
  46943. }
  46944. switch (edgeIndex) {
  46945. case 0:
  46946. if (this._checkVerticesInsteadOfIndices) {
  46947. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  46948. }
  46949. else {
  46950. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  46951. }
  46952. break;
  46953. case 1:
  46954. if (this._checkVerticesInsteadOfIndices) {
  46955. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  46956. }
  46957. else {
  46958. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  46959. }
  46960. break;
  46961. case 2:
  46962. if (this._checkVerticesInsteadOfIndices) {
  46963. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  46964. }
  46965. else {
  46966. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  46967. }
  46968. break;
  46969. }
  46970. if (otherEdgeIndex === -1) {
  46971. continue;
  46972. }
  46973. faceAdjacencies.edges[edgeIndex] = otherIndex;
  46974. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  46975. faceAdjacencies.edgesConnectedCount++;
  46976. otherFaceAdjacencies.edgesConnectedCount++;
  46977. if (faceAdjacencies.edgesConnectedCount === 3) {
  46978. break;
  46979. }
  46980. }
  46981. }
  46982. }
  46983. // Create lines
  46984. for (index = 0; index < adjacencies.length; index++) {
  46985. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  46986. var current = adjacencies[index];
  46987. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  46988. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  46989. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  46990. }
  46991. // Merge into a single mesh
  46992. var engine = this._source.getScene().getEngine();
  46993. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  46994. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  46995. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  46996. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  46997. this._ib = engine.createIndexBuffer(this._linesIndices);
  46998. this._indicesCount = this._linesIndices.length;
  46999. };
  47000. EdgesRenderer.prototype.render = function () {
  47001. if (!this._lineShader.isReady()) {
  47002. return;
  47003. }
  47004. var scene = this._source.getScene();
  47005. var engine = scene.getEngine();
  47006. this._lineShader._preBind();
  47007. // VBOs
  47008. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  47009. scene.resetCachedMaterial();
  47010. this._lineShader.setColor4("color", this._source.edgesColor);
  47011. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  47012. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  47013. }
  47014. else {
  47015. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  47016. }
  47017. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  47018. this._lineShader.bind(this._source.getWorldMatrix());
  47019. // Draw order
  47020. engine.draw(true, 0, this._indicesCount);
  47021. this._lineShader.unbind();
  47022. engine.setDepthWrite(true);
  47023. };
  47024. return EdgesRenderer;
  47025. })();
  47026. BABYLON.EdgesRenderer = EdgesRenderer;
  47027. })(BABYLON || (BABYLON = {}));
  47028. var BABYLON;
  47029. (function (BABYLON) {
  47030. (function (TonemappingOperator) {
  47031. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  47032. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  47033. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  47034. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  47035. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  47036. var TonemappingOperator = BABYLON.TonemappingOperator;
  47037. ;
  47038. var TonemapPostProcess = (function (_super) {
  47039. __extends(TonemapPostProcess, _super);
  47040. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  47041. var _this = this;
  47042. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47043. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47044. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  47045. this._operator = _operator;
  47046. this.exposureAdjustment = exposureAdjustment;
  47047. var defines = "#define ";
  47048. if (this._operator === TonemappingOperator.Hable)
  47049. defines += "HABLE_TONEMAPPING";
  47050. else if (this._operator === TonemappingOperator.Reinhard)
  47051. defines += "REINHARD_TONEMAPPING";
  47052. else if (this._operator === TonemappingOperator.HejiDawson)
  47053. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  47054. else if (this._operator === TonemappingOperator.Photographic)
  47055. defines += "PHOTOGRAPHIC_TONEMAPPING";
  47056. //sadly a second call to create the effect.
  47057. this.updateEffect(defines);
  47058. this.onApply = function (effect) {
  47059. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  47060. };
  47061. }
  47062. return TonemapPostProcess;
  47063. })(BABYLON.PostProcess);
  47064. BABYLON.TonemapPostProcess = TonemapPostProcess;
  47065. })(BABYLON || (BABYLON = {}));
  47066. var BABYLON;
  47067. (function (BABYLON) {
  47068. var ReflectionProbe = (function () {
  47069. function ReflectionProbe(name, size, scene, generateMipMaps) {
  47070. var _this = this;
  47071. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47072. this.name = name;
  47073. this._viewMatrix = BABYLON.Matrix.Identity();
  47074. this._target = BABYLON.Vector3.Zero();
  47075. this._add = BABYLON.Vector3.Zero();
  47076. this.invertYAxis = false;
  47077. this.position = BABYLON.Vector3.Zero();
  47078. this._scene = scene;
  47079. this._scene.reflectionProbes.push(this);
  47080. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  47081. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  47082. switch (faceIndex) {
  47083. case 0:
  47084. _this._add.copyFromFloats(1, 0, 0);
  47085. break;
  47086. case 1:
  47087. _this._add.copyFromFloats(-1, 0, 0);
  47088. break;
  47089. case 2:
  47090. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  47091. break;
  47092. case 3:
  47093. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  47094. break;
  47095. case 4:
  47096. _this._add.copyFromFloats(0, 0, 1);
  47097. break;
  47098. case 5:
  47099. _this._add.copyFromFloats(0, 0, -1);
  47100. break;
  47101. }
  47102. if (_this._attachedMesh) {
  47103. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  47104. }
  47105. _this.position.addToRef(_this._add, _this._target);
  47106. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  47107. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  47108. });
  47109. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  47110. scene.updateTransformMatrix(true);
  47111. });
  47112. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  47113. }
  47114. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  47115. get: function () {
  47116. return this._renderTargetTexture.refreshRate;
  47117. },
  47118. set: function (value) {
  47119. this._renderTargetTexture.refreshRate = value;
  47120. },
  47121. enumerable: true,
  47122. configurable: true
  47123. });
  47124. ReflectionProbe.prototype.getScene = function () {
  47125. return this._scene;
  47126. };
  47127. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  47128. get: function () {
  47129. return this._renderTargetTexture;
  47130. },
  47131. enumerable: true,
  47132. configurable: true
  47133. });
  47134. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  47135. get: function () {
  47136. return this._renderTargetTexture.renderList;
  47137. },
  47138. enumerable: true,
  47139. configurable: true
  47140. });
  47141. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  47142. this._attachedMesh = mesh;
  47143. };
  47144. ReflectionProbe.prototype.dispose = function () {
  47145. var index = this._scene.reflectionProbes.indexOf(this);
  47146. if (index !== -1) {
  47147. // Remove from the scene if found
  47148. this._scene.reflectionProbes.splice(index, 1);
  47149. }
  47150. if (this._renderTargetTexture) {
  47151. this._renderTargetTexture.dispose();
  47152. this._renderTargetTexture = null;
  47153. }
  47154. };
  47155. return ReflectionProbe;
  47156. })();
  47157. BABYLON.ReflectionProbe = ReflectionProbe;
  47158. })(BABYLON || (BABYLON = {}));
  47159. var BABYLON;
  47160. (function (BABYLON) {
  47161. var SolidParticle = (function () {
  47162. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  47163. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  47164. this.position = BABYLON.Vector3.Zero(); // position
  47165. this.rotation = BABYLON.Vector3.Zero(); // rotation
  47166. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  47167. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  47168. this.velocity = BABYLON.Vector3.Zero(); // velocity
  47169. this.alive = true; // alive
  47170. this.idx = particleIndex;
  47171. this._pos = positionIndex;
  47172. this._model = model;
  47173. this.shapeId = shapeId;
  47174. this.idxInShape = idxInShape;
  47175. }
  47176. Object.defineProperty(SolidParticle.prototype, "scale", {
  47177. //legacy support, changed scale to scaling
  47178. get: function () {
  47179. return this.scaling;
  47180. },
  47181. set: function (scale) {
  47182. this.scaling = scale;
  47183. },
  47184. enumerable: true,
  47185. configurable: true
  47186. });
  47187. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  47188. //legacy support, changed quaternion to rotationQuaternion
  47189. get: function () {
  47190. return this.rotationQuaternion;
  47191. },
  47192. set: function (q) {
  47193. this.rotationQuaternion = q;
  47194. },
  47195. enumerable: true,
  47196. configurable: true
  47197. });
  47198. return SolidParticle;
  47199. })();
  47200. BABYLON.SolidParticle = SolidParticle;
  47201. var ModelShape = (function () {
  47202. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  47203. this.shapeID = id;
  47204. this._shape = shape;
  47205. this._shapeUV = shapeUV;
  47206. this._positionFunction = posFunction;
  47207. this._vertexFunction = vtxFunction;
  47208. }
  47209. return ModelShape;
  47210. })();
  47211. BABYLON.ModelShape = ModelShape;
  47212. })(BABYLON || (BABYLON = {}));
  47213. var BABYLON;
  47214. (function (BABYLON) {
  47215. /**
  47216. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47217. */
  47218. var SolidParticleSystem = (function () {
  47219. /**
  47220. * Creates a SPS (Solid Particle System) object.
  47221. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47222. * `scene` (Scene) is the scene in which the SPS is added.
  47223. * `updatableè (default true) : if the SPS must be updatable or immutable.
  47224. * `isPickable` (default false) : if the solid particles must be pickable.
  47225. */
  47226. function SolidParticleSystem(name, scene, options) {
  47227. // public members
  47228. /**
  47229. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47230. * Example : var p = SPS.particles[i];
  47231. */
  47232. this.particles = new Array();
  47233. /**
  47234. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47235. */
  47236. this.nbParticles = 0;
  47237. /**
  47238. * If the particles must ever face the camera (default false). Useful for planar particles.
  47239. */
  47240. this.billboard = false;
  47241. /**
  47242. * This a counter ofr your own usage. It's not set by any SPS functions.
  47243. */
  47244. this.counter = 0;
  47245. /**
  47246. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47247. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47248. */
  47249. this.vars = {};
  47250. this._positions = new Array();
  47251. this._indices = new Array();
  47252. this._normals = new Array();
  47253. this._colors = new Array();
  47254. this._uvs = new Array();
  47255. this._index = 0; // indices index
  47256. this._updatable = true;
  47257. this._pickable = false;
  47258. this._isVisibilityBoxLocked = false;
  47259. this._alwaysVisible = false;
  47260. this._shapeCounter = 0;
  47261. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  47262. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47263. this._computeParticleColor = true;
  47264. this._computeParticleTexture = true;
  47265. this._computeParticleRotation = true;
  47266. this._computeParticleVertex = false;
  47267. this._computeBoundingBox = false;
  47268. this._cam_axisZ = BABYLON.Vector3.Zero();
  47269. this._cam_axisY = BABYLON.Vector3.Zero();
  47270. this._cam_axisX = BABYLON.Vector3.Zero();
  47271. this._axisX = BABYLON.Axis.X;
  47272. this._axisY = BABYLON.Axis.Y;
  47273. this._axisZ = BABYLON.Axis.Z;
  47274. this._fakeCamPos = BABYLON.Vector3.Zero();
  47275. this._rotMatrix = new BABYLON.Matrix();
  47276. this._invertMatrix = new BABYLON.Matrix();
  47277. this._rotated = BABYLON.Vector3.Zero();
  47278. this._quaternion = new BABYLON.Quaternion();
  47279. this._vertex = BABYLON.Vector3.Zero();
  47280. this._normal = BABYLON.Vector3.Zero();
  47281. this._yaw = 0.0;
  47282. this._pitch = 0.0;
  47283. this._roll = 0.0;
  47284. this._halfroll = 0.0;
  47285. this._halfpitch = 0.0;
  47286. this._halfyaw = 0.0;
  47287. this._sinRoll = 0.0;
  47288. this._cosRoll = 0.0;
  47289. this._sinPitch = 0.0;
  47290. this._cosPitch = 0.0;
  47291. this._sinYaw = 0.0;
  47292. this._cosYaw = 0.0;
  47293. this._w = 0.0;
  47294. this._minimum = BABYLON.Tmp.Vector3[0];
  47295. this._maximum = BABYLON.Tmp.Vector3[1];
  47296. this.name = name;
  47297. this._scene = scene;
  47298. this._camera = scene.activeCamera;
  47299. this._pickable = options ? options.isPickable : false;
  47300. if (options && options.updatable) {
  47301. this._updatable = options.updatable;
  47302. }
  47303. else {
  47304. this._updatable = true;
  47305. }
  47306. if (this._pickable) {
  47307. this.pickedParticles = [];
  47308. }
  47309. }
  47310. /**
  47311. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47312. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47313. */
  47314. SolidParticleSystem.prototype.buildMesh = function () {
  47315. if (this.nbParticles === 0) {
  47316. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47317. this.addShape(triangle, 1);
  47318. triangle.dispose();
  47319. }
  47320. this._positions32 = new Float32Array(this._positions);
  47321. this._uvs32 = new Float32Array(this._uvs);
  47322. this._colors32 = new Float32Array(this._colors);
  47323. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  47324. this._normals32 = new Float32Array(this._normals);
  47325. this._fixedNormal32 = new Float32Array(this._normals);
  47326. var vertexData = new BABYLON.VertexData();
  47327. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47328. vertexData.indices = this._indices;
  47329. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47330. if (this._uvs32) {
  47331. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47332. ;
  47333. }
  47334. if (this._colors32) {
  47335. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47336. }
  47337. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47338. vertexData.applyToMesh(mesh, this._updatable);
  47339. this.mesh = mesh;
  47340. this.mesh.isPickable = this._pickable;
  47341. // free memory
  47342. this._positions = null;
  47343. this._normals = null;
  47344. this._uvs = null;
  47345. this._colors = null;
  47346. if (!this._updatable) {
  47347. this.particles.length = 0;
  47348. }
  47349. return mesh;
  47350. };
  47351. /**
  47352. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47353. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47354. * Thus the particles generated from `digest()` have their property `position` set yet.
  47355. * `mesh` (`Mesh`) is the mesh to be digested
  47356. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47357. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47358. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47359. */
  47360. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47361. var size = (options && options.facetNb) || 1;
  47362. var number = (options && options.number);
  47363. var delta = (options && options.delta) || 0;
  47364. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47365. var meshInd = mesh.getIndices();
  47366. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47367. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47368. var f = 0; // facet counter
  47369. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47370. // compute size from number
  47371. if (number) {
  47372. number = (number > totalFacets) ? totalFacets : number;
  47373. size = Math.round(totalFacets / number);
  47374. delta = 0;
  47375. }
  47376. else {
  47377. size = (size > totalFacets) ? totalFacets : size;
  47378. }
  47379. var facetPos = []; // submesh positions
  47380. var facetInd = []; // submesh indices
  47381. var facetUV = []; // submesh UV
  47382. var facetCol = []; // submesh colors
  47383. var barycenter = BABYLON.Tmp.Vector3[0];
  47384. var rand;
  47385. var sizeO = size;
  47386. while (f < totalFacets) {
  47387. size = sizeO + Math.floor((1 + delta) * Math.random());
  47388. if (f > totalFacets - size) {
  47389. size = totalFacets - f;
  47390. }
  47391. // reset temp arrays
  47392. facetPos.length = 0;
  47393. facetInd.length = 0;
  47394. facetUV.length = 0;
  47395. facetCol.length = 0;
  47396. // iterate over "size" facets
  47397. var fi = 0;
  47398. for (var j = f * 3; j < (f + size) * 3; j++) {
  47399. facetInd.push(fi);
  47400. var i = meshInd[j];
  47401. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47402. if (meshUV) {
  47403. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47404. }
  47405. if (meshCol) {
  47406. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47407. }
  47408. fi++;
  47409. }
  47410. // create a model shape for each single particle
  47411. var idx = this.nbParticles;
  47412. var shape = this._posToShape(facetPos);
  47413. var shapeUV = this._uvsToShapeUV(facetUV);
  47414. // compute the barycenter of the shape
  47415. var v;
  47416. for (v = 0; v < shape.length; v++) {
  47417. barycenter.addInPlace(shape[v]);
  47418. }
  47419. barycenter.scaleInPlace(1 / shape.length);
  47420. // shift the shape from its barycenter to the origin
  47421. for (v = 0; v < shape.length; v++) {
  47422. shape[v].subtractInPlace(barycenter);
  47423. }
  47424. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  47425. // add the particle in the SPS
  47426. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  47427. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  47428. // initialize the particle position
  47429. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47430. this._index += shape.length;
  47431. idx++;
  47432. this.nbParticles++;
  47433. this._shapeCounter++;
  47434. f += size;
  47435. }
  47436. return this;
  47437. };
  47438. //reset copy
  47439. SolidParticleSystem.prototype._resetCopy = function () {
  47440. this._copy.position.x = 0;
  47441. this._copy.position.y = 0;
  47442. this._copy.position.z = 0;
  47443. this._copy.rotation.x = 0;
  47444. this._copy.rotation.y = 0;
  47445. this._copy.rotation.z = 0;
  47446. this._copy.rotationQuaternion = null;
  47447. this._copy.scaling.x = 1;
  47448. this._copy.scaling.y = 1;
  47449. this._copy.scaling.z = 1;
  47450. this._copy.uvs.x = 0;
  47451. this._copy.uvs.y = 0;
  47452. this._copy.uvs.z = 1;
  47453. this._copy.uvs.w = 1;
  47454. this._copy.color = null;
  47455. };
  47456. // _meshBuilder : inserts the shape model in the global SPS mesh
  47457. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  47458. var i;
  47459. var u = 0;
  47460. var c = 0;
  47461. this._resetCopy();
  47462. if (options && options.positionFunction) {
  47463. options.positionFunction(this._copy, idx, idxInShape);
  47464. }
  47465. if (this._copy.rotationQuaternion) {
  47466. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47467. }
  47468. else {
  47469. this._yaw = this._copy.rotation.y;
  47470. this._pitch = this._copy.rotation.x;
  47471. this._roll = this._copy.rotation.z;
  47472. this._quaternionRotationYPR();
  47473. }
  47474. this._quaternionToRotationMatrix();
  47475. for (i = 0; i < shape.length; i++) {
  47476. this._vertex.x = shape[i].x;
  47477. this._vertex.y = shape[i].y;
  47478. this._vertex.z = shape[i].z;
  47479. if (options && options.vertexFunction) {
  47480. options.vertexFunction(this._copy, this._vertex, i);
  47481. }
  47482. this._vertex.x *= this._copy.scaling.x;
  47483. this._vertex.y *= this._copy.scaling.y;
  47484. this._vertex.z *= this._copy.scaling.z;
  47485. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47486. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47487. if (meshUV) {
  47488. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  47489. u += 2;
  47490. }
  47491. if (this._copy.color) {
  47492. this._color = this._copy.color;
  47493. }
  47494. else if (meshCol && meshCol[c]) {
  47495. this._color.r = meshCol[c];
  47496. this._color.g = meshCol[c + 1];
  47497. this._color.b = meshCol[c + 2];
  47498. this._color.a = meshCol[c + 3];
  47499. }
  47500. else {
  47501. this._color.r = 1;
  47502. this._color.g = 1;
  47503. this._color.b = 1;
  47504. this._color.a = 1;
  47505. }
  47506. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47507. c += 4;
  47508. }
  47509. for (i = 0; i < meshInd.length; i++) {
  47510. indices.push(p + meshInd[i]);
  47511. }
  47512. if (this._pickable) {
  47513. var nbfaces = meshInd.length / 3;
  47514. for (i = 0; i < nbfaces; i++) {
  47515. this.pickedParticles.push({ idx: idx, faceId: i });
  47516. }
  47517. }
  47518. };
  47519. // returns a shape array from positions array
  47520. SolidParticleSystem.prototype._posToShape = function (positions) {
  47521. var shape = [];
  47522. for (var i = 0; i < positions.length; i += 3) {
  47523. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47524. }
  47525. return shape;
  47526. };
  47527. // returns a shapeUV array from a Vector4 uvs
  47528. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47529. var shapeUV = [];
  47530. if (uvs) {
  47531. for (var i = 0; i < uvs.length; i++)
  47532. shapeUV.push(uvs[i]);
  47533. }
  47534. return shapeUV;
  47535. };
  47536. // adds a new particle object in the particles array
  47537. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  47538. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  47539. };
  47540. /**
  47541. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47542. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47543. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  47544. * `nb` (positive integer) the number of particles to be created from this model
  47545. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47546. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47547. */
  47548. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47549. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47550. var meshInd = mesh.getIndices();
  47551. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47552. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47553. var shape = this._posToShape(meshPos);
  47554. var shapeUV = this._uvsToShapeUV(meshUV);
  47555. var posfunc = options ? options.positionFunction : null;
  47556. var vtxfunc = options ? options.vertexFunction : null;
  47557. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  47558. // particles
  47559. var idx = this.nbParticles;
  47560. for (var i = 0; i < nb; i++) {
  47561. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  47562. if (this._updatable) {
  47563. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  47564. }
  47565. this._index += shape.length;
  47566. idx++;
  47567. }
  47568. this.nbParticles += nb;
  47569. this._shapeCounter++;
  47570. return this._shapeCounter - 1;
  47571. };
  47572. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47573. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47574. this._resetCopy();
  47575. if (particle._model._positionFunction) {
  47576. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47577. }
  47578. if (this._copy.rotationQuaternion) {
  47579. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47580. }
  47581. else {
  47582. this._yaw = this._copy.rotation.y;
  47583. this._pitch = this._copy.rotation.x;
  47584. this._roll = this._copy.rotation.z;
  47585. this._quaternionRotationYPR();
  47586. }
  47587. this._quaternionToRotationMatrix();
  47588. this._shape = particle._model._shape;
  47589. for (var pt = 0; pt < this._shape.length; pt++) {
  47590. this._vertex.x = this._shape[pt].x;
  47591. this._vertex.y = this._shape[pt].y;
  47592. this._vertex.z = this._shape[pt].z;
  47593. if (particle._model._vertexFunction) {
  47594. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47595. }
  47596. this._vertex.x *= this._copy.scaling.x;
  47597. this._vertex.y *= this._copy.scaling.y;
  47598. this._vertex.z *= this._copy.scaling.z;
  47599. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47600. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47601. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47602. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47603. }
  47604. particle.position.x = 0;
  47605. particle.position.y = 0;
  47606. particle.position.z = 0;
  47607. particle.rotation.x = 0;
  47608. particle.rotation.y = 0;
  47609. particle.rotation.z = 0;
  47610. particle.rotationQuaternion = null;
  47611. particle.scaling.x = 1;
  47612. particle.scaling.y = 1;
  47613. particle.scaling.z = 1;
  47614. };
  47615. /**
  47616. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47617. */
  47618. SolidParticleSystem.prototype.rebuildMesh = function () {
  47619. for (var p = 0; p < this.particles.length; p++) {
  47620. this._rebuildParticle(this.particles[p]);
  47621. }
  47622. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47623. };
  47624. /**
  47625. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47626. * This method calls `updateParticle()` for each particle of the SPS.
  47627. * For an animated SPS, it is usually called within the render loop.
  47628. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  47629. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  47630. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  47631. */
  47632. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47633. if (start === void 0) { start = 0; }
  47634. if (end === void 0) { end = this.nbParticles - 1; }
  47635. if (update === void 0) { update = true; }
  47636. if (!this._updatable) {
  47637. return;
  47638. }
  47639. // custom beforeUpdate
  47640. this.beforeUpdateParticles(start, end, update);
  47641. this._cam_axisX.x = 1;
  47642. this._cam_axisX.y = 0;
  47643. this._cam_axisX.z = 0;
  47644. this._cam_axisY.x = 0;
  47645. this._cam_axisY.y = 1;
  47646. this._cam_axisY.z = 0;
  47647. this._cam_axisZ.x = 0;
  47648. this._cam_axisZ.y = 0;
  47649. this._cam_axisZ.z = 1;
  47650. // if the particles will always face the camera
  47651. if (this.billboard) {
  47652. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  47653. this._yaw = this.mesh.rotation.y;
  47654. this._pitch = this.mesh.rotation.x;
  47655. this._roll = this.mesh.rotation.z;
  47656. this._quaternionRotationYPR();
  47657. this._quaternionToRotationMatrix();
  47658. this._rotMatrix.invertToRef(this._invertMatrix);
  47659. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  47660. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  47661. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  47662. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  47663. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  47664. this._cam_axisY.normalize();
  47665. this._cam_axisX.normalize();
  47666. this._cam_axisZ.normalize();
  47667. }
  47668. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47669. var idx = 0;
  47670. var index = 0;
  47671. var colidx = 0;
  47672. var colorIndex = 0;
  47673. var uvidx = 0;
  47674. var uvIndex = 0;
  47675. if (this._computeBoundingBox) {
  47676. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47677. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47678. }
  47679. // particle loop
  47680. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  47681. for (var p = start; p <= end; p++) {
  47682. this._particle = this.particles[p];
  47683. this._shape = this._particle._model._shape;
  47684. this._shapeUV = this._particle._model._shapeUV;
  47685. // call to custom user function to update the particle properties
  47686. this.updateParticle(this._particle);
  47687. // particle rotation matrix
  47688. if (this.billboard) {
  47689. this._particle.rotation.x = 0.0;
  47690. this._particle.rotation.y = 0.0;
  47691. }
  47692. if (this._computeParticleRotation) {
  47693. if (this._particle.rotationQuaternion) {
  47694. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47695. }
  47696. else {
  47697. this._yaw = this._particle.rotation.y;
  47698. this._pitch = this._particle.rotation.x;
  47699. this._roll = this._particle.rotation.z;
  47700. this._quaternionRotationYPR();
  47701. }
  47702. this._quaternionToRotationMatrix();
  47703. }
  47704. for (var pt = 0; pt < this._shape.length; pt++) {
  47705. idx = index + pt * 3;
  47706. colidx = colorIndex + pt * 4;
  47707. uvidx = uvIndex + pt * 2;
  47708. this._vertex.x = this._shape[pt].x;
  47709. this._vertex.y = this._shape[pt].y;
  47710. this._vertex.z = this._shape[pt].z;
  47711. if (this._computeParticleVertex) {
  47712. this.updateParticleVertex(this._particle, this._vertex, pt);
  47713. }
  47714. // positions
  47715. this._vertex.x *= this._particle.scaling.x;
  47716. this._vertex.y *= this._particle.scaling.y;
  47717. this._vertex.z *= this._particle.scaling.z;
  47718. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  47719. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  47720. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  47721. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  47722. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47723. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  47724. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  47725. if (this._computeBoundingBox) {
  47726. if (this._positions32[idx] < this._minimum.x) {
  47727. this._minimum.x = this._positions32[idx];
  47728. }
  47729. if (this._positions32[idx] > this._maximum.x) {
  47730. this._maximum.x = this._positions32[idx];
  47731. }
  47732. if (this._positions32[idx + 1] < this._minimum.y) {
  47733. this._minimum.y = this._positions32[idx + 1];
  47734. }
  47735. if (this._positions32[idx + 1] > this._maximum.y) {
  47736. this._maximum.y = this._positions32[idx + 1];
  47737. }
  47738. if (this._positions32[idx + 2] < this._minimum.z) {
  47739. this._minimum.z = this._positions32[idx + 2];
  47740. }
  47741. if (this._positions32[idx + 2] > this._maximum.z) {
  47742. this._maximum.z = this._positions32[idx + 2];
  47743. }
  47744. }
  47745. // normals : if the particles can't be morphed then just rotate the normals
  47746. if (!this._computeParticleVertex && !this.billboard) {
  47747. this._normal.x = this._fixedNormal32[idx];
  47748. this._normal.y = this._fixedNormal32[idx + 1];
  47749. this._normal.z = this._fixedNormal32[idx + 2];
  47750. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  47751. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  47752. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  47753. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  47754. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47755. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  47756. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  47757. }
  47758. if (this._computeParticleColor) {
  47759. this._colors32[colidx] = this._particle.color.r;
  47760. this._colors32[colidx + 1] = this._particle.color.g;
  47761. this._colors32[colidx + 2] = this._particle.color.b;
  47762. this._colors32[colidx + 3] = this._particle.color.a;
  47763. }
  47764. if (this._computeParticleTexture) {
  47765. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47766. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47767. }
  47768. }
  47769. index = idx + 3;
  47770. colorIndex = colidx + 4;
  47771. uvIndex = uvidx + 2;
  47772. }
  47773. if (update) {
  47774. if (this._computeParticleColor) {
  47775. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47776. }
  47777. if (this._computeParticleTexture) {
  47778. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47779. }
  47780. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47781. if (!this.mesh.areNormalsFrozen) {
  47782. if (this._computeParticleVertex || this.billboard) {
  47783. // recompute the normals only if the particles can be morphed, update then the normal reference array
  47784. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  47785. for (var i = 0; i < this._normals32.length; i++) {
  47786. this._fixedNormal32[i] = this._normals32[i];
  47787. }
  47788. }
  47789. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47790. }
  47791. }
  47792. if (this._computeBoundingBox) {
  47793. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47794. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47795. }
  47796. this.afterUpdateParticles(start, end, update);
  47797. };
  47798. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47799. this._halfroll = this._roll * 0.5;
  47800. this._halfpitch = this._pitch * 0.5;
  47801. this._halfyaw = this._yaw * 0.5;
  47802. this._sinRoll = Math.sin(this._halfroll);
  47803. this._cosRoll = Math.cos(this._halfroll);
  47804. this._sinPitch = Math.sin(this._halfpitch);
  47805. this._cosPitch = Math.cos(this._halfpitch);
  47806. this._sinYaw = Math.sin(this._halfyaw);
  47807. this._cosYaw = Math.cos(this._halfyaw);
  47808. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  47809. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  47810. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  47811. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  47812. };
  47813. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47814. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47815. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47816. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47817. this._rotMatrix.m[3] = 0;
  47818. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47819. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47820. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47821. this._rotMatrix.m[7] = 0;
  47822. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47823. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47824. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47825. this._rotMatrix.m[11] = 0;
  47826. this._rotMatrix.m[12] = 0;
  47827. this._rotMatrix.m[13] = 0;
  47828. this._rotMatrix.m[14] = 0;
  47829. this._rotMatrix.m[15] = 1.0;
  47830. };
  47831. /**
  47832. * Disposes the SPS
  47833. */
  47834. SolidParticleSystem.prototype.dispose = function () {
  47835. this.mesh.dispose();
  47836. this.vars = null;
  47837. // drop references to internal big arrays for the GC
  47838. this._positions = null;
  47839. this._indices = null;
  47840. this._normals = null;
  47841. this._uvs = null;
  47842. this._colors = null;
  47843. this._positions32 = null;
  47844. this._normals32 = null;
  47845. this._fixedNormal32 = null;
  47846. this._uvs32 = null;
  47847. this._colors32 = null;
  47848. this.pickedParticles = null;
  47849. };
  47850. /**
  47851. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47852. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47853. */
  47854. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47855. if (!this._isVisibilityBoxLocked) {
  47856. this.mesh.refreshBoundingInfo();
  47857. }
  47858. };
  47859. /**
  47860. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47861. * @param size the size (float) of the visibility box
  47862. * note : this doesn't lock the SPS mesh bounding box.
  47863. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47864. */
  47865. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47866. var vis = size / 2;
  47867. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47868. };
  47869. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47870. // getter and setter
  47871. get: function () {
  47872. return this._alwaysVisible;
  47873. },
  47874. /**
  47875. * Sets the SPS as always visible or not
  47876. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47877. */
  47878. set: function (val) {
  47879. this._alwaysVisible = val;
  47880. this.mesh.alwaysSelectAsActiveMesh = val;
  47881. },
  47882. enumerable: true,
  47883. configurable: true
  47884. });
  47885. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47886. get: function () {
  47887. return this._isVisibilityBoxLocked;
  47888. },
  47889. /**
  47890. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47891. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47892. */
  47893. set: function (val) {
  47894. this._isVisibilityBoxLocked = val;
  47895. this.mesh.getBoundingInfo().isLocked = val;
  47896. },
  47897. enumerable: true,
  47898. configurable: true
  47899. });
  47900. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47901. // getters
  47902. get: function () {
  47903. return this._computeParticleRotation;
  47904. },
  47905. // Optimizer setters
  47906. /**
  47907. * Tells to `setParticles()` to compute the particle rotations or not.
  47908. * Default value : true. The SPS is faster when it's set to false.
  47909. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47910. */
  47911. set: function (val) {
  47912. this._computeParticleRotation = val;
  47913. },
  47914. enumerable: true,
  47915. configurable: true
  47916. });
  47917. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47918. get: function () {
  47919. return this._computeParticleColor;
  47920. },
  47921. /**
  47922. * Tells to `setParticles()` to compute the particle colors or not.
  47923. * Default value : true. The SPS is faster when it's set to false.
  47924. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47925. */
  47926. set: function (val) {
  47927. this._computeParticleColor = val;
  47928. },
  47929. enumerable: true,
  47930. configurable: true
  47931. });
  47932. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47933. get: function () {
  47934. return this._computeParticleTexture;
  47935. },
  47936. /**
  47937. * Tells to `setParticles()` to compute the particle textures or not.
  47938. * Default value : true. The SPS is faster when it's set to false.
  47939. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47940. */
  47941. set: function (val) {
  47942. this._computeParticleTexture = val;
  47943. },
  47944. enumerable: true,
  47945. configurable: true
  47946. });
  47947. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47948. get: function () {
  47949. return this._computeParticleVertex;
  47950. },
  47951. /**
  47952. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47953. * Default value : false. The SPS is faster when it's set to false.
  47954. * Note : the particle custom vertex positions aren't stored values.
  47955. */
  47956. set: function (val) {
  47957. this._computeParticleVertex = val;
  47958. },
  47959. enumerable: true,
  47960. configurable: true
  47961. });
  47962. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  47963. get: function () {
  47964. return this._computeBoundingBox;
  47965. },
  47966. /**
  47967. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  47968. */
  47969. set: function (val) {
  47970. this._computeBoundingBox = val;
  47971. },
  47972. enumerable: true,
  47973. configurable: true
  47974. });
  47975. // =======================================================================
  47976. // Particle behavior logic
  47977. // these following methods may be overwritten by the user to fit his needs
  47978. /**
  47979. * This function does nothing. It may be overwritten to set all the particle first values.
  47980. * The SPS doesn't call this function, you may have to call it by your own.
  47981. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47982. */
  47983. SolidParticleSystem.prototype.initParticles = function () {
  47984. };
  47985. /**
  47986. * This function does nothing. It may be overwritten to recycle a particle.
  47987. * The SPS doesn't call this function, you may have to call it by your own.
  47988. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47989. */
  47990. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  47991. return particle;
  47992. };
  47993. /**
  47994. * Updates a particle : this function should be overwritten by the user.
  47995. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  47996. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47997. * ex : just set a particle position or velocity and recycle conditions
  47998. */
  47999. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48000. return particle;
  48001. };
  48002. /**
  48003. * Updates a vertex of a particle : it can be overwritten by the user.
  48004. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48005. * @param particle the current particle
  48006. * @param vertex the current index of the current particle
  48007. * @param pt the index of the current vertex in the particle shape
  48008. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48009. * ex : just set a vertex particle position
  48010. */
  48011. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48012. return vertex;
  48013. };
  48014. /**
  48015. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48016. * This does nothing and may be overwritten by the user.
  48017. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48018. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48019. * @param update the boolean update value actually passed to setParticles()
  48020. */
  48021. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48022. };
  48023. /**
  48024. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48025. * This will be passed three parameters.
  48026. * This does nothing and may be overwritten by the user.
  48027. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48028. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48029. * @param update the boolean update value actually passed to setParticles()
  48030. */
  48031. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48032. };
  48033. return SolidParticleSystem;
  48034. })();
  48035. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48036. })(BABYLON || (BABYLON = {}));
  48037. var BABYLON;
  48038. (function (BABYLON) {
  48039. var Internals;
  48040. (function (Internals) {
  48041. var FileFaceOrientation = (function () {
  48042. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48043. this.name = name;
  48044. this.worldAxisForNormal = worldAxisForNormal;
  48045. this.worldAxisForFileX = worldAxisForFileX;
  48046. this.worldAxisForFileY = worldAxisForFileY;
  48047. }
  48048. return FileFaceOrientation;
  48049. })();
  48050. ;
  48051. /**
  48052. * Helper class dealing with the extraction of spherical polynomial dataArray
  48053. * from a cube map.
  48054. */
  48055. var CubeMapToSphericalPolynomialTools = (function () {
  48056. function CubeMapToSphericalPolynomialTools() {
  48057. }
  48058. /**
  48059. * Converts a cubemap to the according Spherical Polynomial data.
  48060. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48061. *
  48062. * @param cubeInfo The Cube map to extract the information from.
  48063. * @return The Spherical Polynomial data.
  48064. */
  48065. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48066. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48067. var totalSolidAngle = 0.0;
  48068. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48069. var du = 2.0 / cubeInfo.size;
  48070. var dv = du;
  48071. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48072. var minUV = du * 0.5 - 1.0;
  48073. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48074. var fileFace = this.FileFaces[faceIndex];
  48075. var dataArray = cubeInfo[fileFace.name];
  48076. var v = minUV;
  48077. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48078. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48079. // Because SP is still linear, so summation is fine in that basis.
  48080. for (var y = 0; y < cubeInfo.size; y++) {
  48081. var u = minUV;
  48082. for (var x = 0; x < cubeInfo.size; x++) {
  48083. // World direction (not normalised)
  48084. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48085. worldDirection.normalize();
  48086. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48087. if (1) {
  48088. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  48089. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  48090. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  48091. var color = new BABYLON.Color3(r, g, b);
  48092. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48093. }
  48094. else {
  48095. if (faceIndex == 0) {
  48096. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48097. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48098. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48099. }
  48100. else if (faceIndex == 1) {
  48101. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48102. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48103. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48104. }
  48105. else if (faceIndex == 2) {
  48106. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48107. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48108. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48109. }
  48110. else if (faceIndex == 3) {
  48111. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48112. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48113. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48114. }
  48115. else if (faceIndex == 4) {
  48116. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48117. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48118. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48119. }
  48120. else if (faceIndex == 5) {
  48121. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48122. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48123. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48124. }
  48125. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  48126. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48127. }
  48128. totalSolidAngle += deltaSolidAngle;
  48129. u += du;
  48130. }
  48131. v += dv;
  48132. }
  48133. }
  48134. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  48135. var correction = correctSolidAngle / totalSolidAngle;
  48136. sphericalHarmonics.scale(correction);
  48137. // Additionally scale by pi -- audit needed
  48138. sphericalHarmonics.scale(1.0 / Math.PI);
  48139. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48140. };
  48141. CubeMapToSphericalPolynomialTools.FileFaces = [
  48142. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48143. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48144. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48145. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48146. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48147. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48148. ];
  48149. return CubeMapToSphericalPolynomialTools;
  48150. })();
  48151. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48152. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48153. })(BABYLON || (BABYLON = {}));
  48154. var BABYLON;
  48155. (function (BABYLON) {
  48156. var Internals;
  48157. (function (Internals) {
  48158. /**
  48159. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48160. */
  48161. var PanoramaToCubeMapTools = (function () {
  48162. function PanoramaToCubeMapTools() {
  48163. }
  48164. /**
  48165. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48166. *
  48167. * @param float32Array The source data.
  48168. * @param inputWidth The width of the input panorama.
  48169. * @param inputhHeight The height of the input panorama.
  48170. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48171. * @return The cubemap data
  48172. */
  48173. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48174. if (!float32Array) {
  48175. throw "ConvertPanoramaToCubemap: input cannot be null";
  48176. }
  48177. if (float32Array.length != inputWidth * inputHeight * 3) {
  48178. throw "ConvertPanoramaToCubemap: input size is wrong";
  48179. }
  48180. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48181. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48182. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48183. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48184. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48185. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48186. return {
  48187. front: textureFront,
  48188. back: textureBack,
  48189. left: textureLeft,
  48190. right: textureRight,
  48191. up: textureUp,
  48192. down: textureDown,
  48193. size: size
  48194. };
  48195. };
  48196. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48197. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48198. var textureArray = new Float32Array(buffer);
  48199. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48200. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48201. var dy = 1 / texSize;
  48202. var fy = 0;
  48203. for (var y = 0; y < texSize; y++) {
  48204. var xv1 = faceData[0];
  48205. var xv2 = faceData[2];
  48206. for (var x = 0; x < texSize; x++) {
  48207. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48208. v.normalize();
  48209. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48210. // 3 channels per pixels
  48211. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48212. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48213. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48214. xv1 = xv1.add(rotDX1);
  48215. xv2 = xv2.add(rotDX2);
  48216. }
  48217. fy += dy;
  48218. }
  48219. return textureArray;
  48220. };
  48221. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48222. var theta = Math.atan2(vDir.z, vDir.x);
  48223. var phi = Math.acos(vDir.y);
  48224. while (theta < -Math.PI)
  48225. theta += 2 * Math.PI;
  48226. while (theta > Math.PI)
  48227. theta -= 2 * Math.PI;
  48228. var dx = theta / Math.PI;
  48229. var dy = phi / Math.PI;
  48230. // recenter.
  48231. dx = dx * 0.5 + 0.5;
  48232. var px = Math.round(dx * inputWidth);
  48233. if (px < 0)
  48234. px = 0;
  48235. else if (px >= inputWidth)
  48236. px = inputWidth - 1;
  48237. var py = Math.round(dy * inputHeight);
  48238. if (py < 0)
  48239. py = 0;
  48240. else if (py >= inputHeight)
  48241. py = inputHeight - 1;
  48242. var inputY = (inputHeight - py - 1);
  48243. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48244. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48245. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48246. return {
  48247. r: r,
  48248. g: g,
  48249. b: b
  48250. };
  48251. };
  48252. PanoramaToCubeMapTools.FACE_FRONT = [
  48253. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48254. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48255. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48256. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48257. ];
  48258. PanoramaToCubeMapTools.FACE_BACK = [
  48259. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48260. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48261. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48262. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48263. ];
  48264. PanoramaToCubeMapTools.FACE_RIGHT = [
  48265. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48266. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48267. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48268. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48269. ];
  48270. PanoramaToCubeMapTools.FACE_LEFT = [
  48271. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48272. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48273. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48274. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48275. ];
  48276. PanoramaToCubeMapTools.FACE_DOWN = [
  48277. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48278. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48279. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48280. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48281. ];
  48282. PanoramaToCubeMapTools.FACE_UP = [
  48283. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48284. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48285. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48286. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48287. ];
  48288. return PanoramaToCubeMapTools;
  48289. })();
  48290. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48291. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48292. })(BABYLON || (BABYLON = {}));
  48293. var BABYLON;
  48294. (function (BABYLON) {
  48295. var Internals;
  48296. (function (Internals) {
  48297. ;
  48298. /**
  48299. * This groups tools to convert HDR texture to native colors array.
  48300. */
  48301. var HDRTools = (function () {
  48302. function HDRTools() {
  48303. }
  48304. HDRTools.Ldexp = function (mantissa, exponent) {
  48305. if (exponent > 1023) {
  48306. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48307. }
  48308. if (exponent < -1074) {
  48309. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48310. }
  48311. return mantissa * Math.pow(2, exponent);
  48312. };
  48313. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48314. if (exponent > 0) {
  48315. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48316. float32array[index + 0] = red * exponent;
  48317. float32array[index + 1] = green * exponent;
  48318. float32array[index + 2] = blue * exponent;
  48319. }
  48320. else {
  48321. float32array[index + 0] = 0;
  48322. float32array[index + 1] = 0;
  48323. float32array[index + 2] = 0;
  48324. }
  48325. };
  48326. HDRTools.readStringLine = function (uint8array, startIndex) {
  48327. var line = "";
  48328. var character = "";
  48329. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48330. character = String.fromCharCode(uint8array[i]);
  48331. if (character == "\n") {
  48332. break;
  48333. }
  48334. line += character;
  48335. }
  48336. return line;
  48337. };
  48338. /**
  48339. * Reads header information from an RGBE texture stored in a native array.
  48340. * More information on this format are available here:
  48341. * https://en.wikipedia.org/wiki/RGBE_image_format
  48342. *
  48343. * @param uint8array The binary file stored in native array.
  48344. * @return The header information.
  48345. */
  48346. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48347. var height = 0;
  48348. var width = 0;
  48349. var line = this.readStringLine(uint8array, 0);
  48350. if (line[0] != '#' || line[1] != '?') {
  48351. throw "Bad HDR Format.";
  48352. }
  48353. var endOfHeader = false;
  48354. var findFormat = false;
  48355. var lineIndex = 0;
  48356. do {
  48357. lineIndex += (line.length + 1);
  48358. line = this.readStringLine(uint8array, lineIndex);
  48359. if (line == "FORMAT=32-bit_rle_rgbe") {
  48360. findFormat = true;
  48361. }
  48362. else if (line.length == 0) {
  48363. endOfHeader = true;
  48364. }
  48365. } while (!endOfHeader);
  48366. if (!findFormat) {
  48367. throw "HDR Bad header format, unsupported FORMAT";
  48368. }
  48369. lineIndex += (line.length + 1);
  48370. line = this.readStringLine(uint8array, lineIndex);
  48371. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48372. var match = sizeRegexp.exec(line);
  48373. // TODO. Support +Y and -X if needed.
  48374. if (match.length < 3) {
  48375. throw "HDR Bad header format, no size";
  48376. }
  48377. width = parseInt(match[2]);
  48378. height = parseInt(match[1]);
  48379. if (width < 8 || width > 0x7fff) {
  48380. throw "HDR Bad header format, unsupported size";
  48381. }
  48382. lineIndex += (line.length + 1);
  48383. return {
  48384. height: height,
  48385. width: width,
  48386. dataPosition: lineIndex
  48387. };
  48388. };
  48389. /**
  48390. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48391. * This RGBE texture needs to store the information as a panorama.
  48392. *
  48393. * More information on this format are available here:
  48394. * https://en.wikipedia.org/wiki/RGBE_image_format
  48395. *
  48396. * @param buffer The binary file stored in an array buffer.
  48397. * @param size The expected size of the extracted cubemap.
  48398. * @return The Cube Map information.
  48399. */
  48400. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48401. var uint8array = new Uint8Array(buffer);
  48402. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48403. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48404. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48405. return cubeMapData;
  48406. };
  48407. /**
  48408. * Returns the pixels data extracted from an RGBE texture.
  48409. * This pixels will be stored left to right up to down in the R G B order in one array.
  48410. *
  48411. * More information on this format are available here:
  48412. * https://en.wikipedia.org/wiki/RGBE_image_format
  48413. *
  48414. * @param uint8array The binary file stored in an array buffer.
  48415. * @param hdrInfo The header information of the file.
  48416. * @return The pixels data in RGB right to left up to down order.
  48417. */
  48418. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48419. // Keep for multi format supports.
  48420. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48421. };
  48422. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48423. var num_scanlines = hdrInfo.height;
  48424. var scanline_width = hdrInfo.width;
  48425. var a, b, c, d, count;
  48426. var dataIndex = hdrInfo.dataPosition;
  48427. var index = 0, endIndex = 0, i = 0;
  48428. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48429. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48430. // 3 channels of 4 bytes per pixel in float.
  48431. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48432. var resultArray = new Float32Array(resultBuffer);
  48433. // read in each successive scanline
  48434. while (num_scanlines > 0) {
  48435. a = uint8array[dataIndex++];
  48436. b = uint8array[dataIndex++];
  48437. c = uint8array[dataIndex++];
  48438. d = uint8array[dataIndex++];
  48439. if (a != 2 || b != 2 || (c & 0x80)) {
  48440. // this file is not run length encoded
  48441. throw "HDR Bad header format, not RLE";
  48442. }
  48443. if (((c << 8) | d) != scanline_width) {
  48444. throw "HDR Bad header format, wrong scan line width";
  48445. }
  48446. index = 0;
  48447. // read each of the four channels for the scanline into the buffer
  48448. for (i = 0; i < 4; i++) {
  48449. endIndex = (i + 1) * scanline_width;
  48450. while (index < endIndex) {
  48451. a = uint8array[dataIndex++];
  48452. b = uint8array[dataIndex++];
  48453. if (a > 128) {
  48454. // a run of the same value
  48455. count = a - 128;
  48456. if ((count == 0) || (count > endIndex - index)) {
  48457. throw "HDR Bad Format, bad scanline data (run)";
  48458. }
  48459. while (count-- > 0) {
  48460. scanLineArray[index++] = b;
  48461. }
  48462. }
  48463. else {
  48464. // a non-run
  48465. count = a;
  48466. if ((count == 0) || (count > endIndex - index)) {
  48467. throw "HDR Bad Format, bad scanline data (non-run)";
  48468. }
  48469. scanLineArray[index++] = b;
  48470. if (--count > 0) {
  48471. for (var j = 0; j < count; j++) {
  48472. scanLineArray[index++] = uint8array[dataIndex++];
  48473. }
  48474. }
  48475. }
  48476. }
  48477. }
  48478. // now convert data from buffer into floats
  48479. for (i = 0; i < scanline_width; i++) {
  48480. a = scanLineArray[i];
  48481. b = scanLineArray[i + scanline_width];
  48482. c = scanLineArray[i + 2 * scanline_width];
  48483. d = scanLineArray[i + 3 * scanline_width];
  48484. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48485. }
  48486. num_scanlines--;
  48487. }
  48488. return resultArray;
  48489. };
  48490. return HDRTools;
  48491. })();
  48492. Internals.HDRTools = HDRTools;
  48493. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48494. })(BABYLON || (BABYLON = {}));
  48495. //_______________________________________________________________
  48496. // Extracted from CubeMapGen:
  48497. // https://code.google.com/archive/p/cubemapgen/
  48498. //
  48499. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  48500. //_______________________________________________________________
  48501. var BABYLON;
  48502. (function (BABYLON) {
  48503. var Internals;
  48504. (function (Internals) {
  48505. /**
  48506. * The bounding box information used during the conversion process.
  48507. */
  48508. var CMGBoundinBox = (function () {
  48509. function CMGBoundinBox() {
  48510. this.min = new BABYLON.Vector3(0, 0, 0);
  48511. this.max = new BABYLON.Vector3(0, 0, 0);
  48512. this.clear();
  48513. }
  48514. CMGBoundinBox.prototype.clear = function () {
  48515. this.min.x = CMGBoundinBox.MAX;
  48516. this.min.y = CMGBoundinBox.MAX;
  48517. this.min.z = CMGBoundinBox.MAX;
  48518. this.max.x = CMGBoundinBox.MIN;
  48519. this.max.y = CMGBoundinBox.MIN;
  48520. this.max.z = CMGBoundinBox.MIN;
  48521. };
  48522. CMGBoundinBox.prototype.augment = function (x, y, z) {
  48523. this.min.x = Math.min(this.min.x, x);
  48524. this.min.y = Math.min(this.min.y, y);
  48525. this.min.z = Math.min(this.min.z, z);
  48526. this.max.x = Math.max(this.max.x, x);
  48527. this.max.y = Math.max(this.max.y, y);
  48528. this.max.z = Math.max(this.max.z, z);
  48529. };
  48530. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  48531. this.min.x = Math.max(this.min.x, x);
  48532. this.min.y = Math.max(this.min.y, y);
  48533. this.min.z = Math.max(this.min.z, z);
  48534. };
  48535. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  48536. this.max.x = Math.min(this.max.x, x);
  48537. this.max.y = Math.min(this.max.y, y);
  48538. this.max.z = Math.min(this.max.z, z);
  48539. };
  48540. CMGBoundinBox.prototype.empty = function () {
  48541. if ((this.min.x > this.max.y) ||
  48542. (this.min.y > this.max.y) ||
  48543. (this.min.z > this.max.y)) {
  48544. return true;
  48545. }
  48546. else {
  48547. return false;
  48548. }
  48549. };
  48550. CMGBoundinBox.MAX = Number.MAX_VALUE;
  48551. CMGBoundinBox.MIN = Number.MIN_VALUE;
  48552. return CMGBoundinBox;
  48553. })();
  48554. /**
  48555. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  48556. * required by the glossinees of a material.
  48557. *
  48558. * This only supports the cosine drop power as well as Warp fixup generation method.
  48559. *
  48560. * This is using the process from CubeMapGen described here:
  48561. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  48562. */
  48563. var PMREMGenerator = (function () {
  48564. /**
  48565. * Constructor of the generator.
  48566. *
  48567. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  48568. * @param inputSize The size of the cubemap faces
  48569. * @param outputSize The size of the output cubemap faces
  48570. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  48571. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  48572. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  48573. * @param specularPower The max specular level of the desired cubemap
  48574. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  48575. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  48576. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  48577. */
  48578. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  48579. this.input = input;
  48580. this.inputSize = inputSize;
  48581. this.outputSize = outputSize;
  48582. this.maxNumMipLevels = maxNumMipLevels;
  48583. this.numChannels = numChannels;
  48584. this.isFloat = isFloat;
  48585. this.specularPower = specularPower;
  48586. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  48587. this.excludeBase = excludeBase;
  48588. this.fixup = fixup;
  48589. this._outputSurface = [];
  48590. this._numMipLevels = 0;
  48591. }
  48592. /**
  48593. * Launches the filter process and return the result.
  48594. *
  48595. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  48596. */
  48597. PMREMGenerator.prototype.filterCubeMap = function () {
  48598. // Init cubemap processor
  48599. this.init();
  48600. // Filters the cubemap
  48601. this.filterCubeMapMipChain();
  48602. // Returns the filtered mips.
  48603. return this._outputSurface;
  48604. };
  48605. PMREMGenerator.prototype.init = function () {
  48606. var i;
  48607. var j;
  48608. var mipLevelSize;
  48609. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  48610. if (this.maxNumMipLevels == 0) {
  48611. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  48612. }
  48613. //first miplevel size
  48614. mipLevelSize = this.outputSize;
  48615. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  48616. for (j = 0; j < this.maxNumMipLevels; j++) {
  48617. this._outputSurface.length++;
  48618. this._outputSurface[j] = [];
  48619. //Iterate over faces for output images
  48620. for (i = 0; i < 6; i++) {
  48621. this._outputSurface[j].length++;
  48622. // Initializes a new array for the output.
  48623. if (this.isFloat) {
  48624. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  48625. }
  48626. else {
  48627. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  48628. }
  48629. }
  48630. //next mip level is half size
  48631. mipLevelSize >>= 1;
  48632. this._numMipLevels++;
  48633. //terminate if mip chain becomes too small
  48634. if (mipLevelSize == 0) {
  48635. this.maxNumMipLevels = j;
  48636. return;
  48637. }
  48638. }
  48639. };
  48640. //--------------------------------------------------------------------------------------
  48641. //Cube map filtering and mip chain generation.
  48642. // the cube map filtereing is specified using a number of parameters:
  48643. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  48644. // indicates the region of the hemisphere to filter over for each tap.
  48645. //
  48646. // Note that the top mip level is also a filtered version of the original input images
  48647. // as well in order to create mip chains for diffuse environment illumination.
  48648. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  48649. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  48650. //
  48651. // Then the mip angle used to genreate the next level of the mip chain from the first level
  48652. // is a_InitialMipAngle
  48653. //
  48654. // The angle for the subsequent levels of the mip chain are specified by their parents
  48655. // filtering angle and a per-level scale and bias
  48656. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  48657. //
  48658. //--------------------------------------------------------------------------------------
  48659. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  48660. // First, take count of the lighting model to modify SpecularPower
  48661. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  48662. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  48663. //Cone angle start (for generating subsequent mip levels)
  48664. var currentSpecularPower = this.specularPower;
  48665. //Build filter lookup tables based on the source miplevel size
  48666. this.precomputeFilterLookupTables(this.inputSize);
  48667. // Note that we need to filter the first level before generating mipmap
  48668. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  48669. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  48670. // TODO : Write a function to copy and scale the base mipmap in output
  48671. // I am just lazy here and just put a high specular power value, and do some if.
  48672. if (this.excludeBase && (levelIndex == 0)) {
  48673. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  48674. currentSpecularPower = 100000.0;
  48675. }
  48676. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  48677. var srcCubeImage = this.input;
  48678. var dstCubeImage = this._outputSurface[levelIndex];
  48679. var dstSize = this.outputSize >> levelIndex;
  48680. // Compute required angle.
  48681. var angle = this.getBaseFilterAngle(currentSpecularPower);
  48682. // filter cube surfaces
  48683. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  48684. // fix seams
  48685. if (this.fixup) {
  48686. this.fixupCubeEdges(dstCubeImage, dstSize);
  48687. }
  48688. // Decrease the specular power to generate the mipmap chain
  48689. // TODO : Use another method for Exclude (see first comment at start of the function
  48690. if (this.excludeBase && (levelIndex == 0)) {
  48691. currentSpecularPower = this.specularPower;
  48692. }
  48693. currentSpecularPower *= this.cosinePowerDropPerMip;
  48694. }
  48695. };
  48696. //--------------------------------------------------------------------------------------
  48697. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  48698. // It allow to optimize the texel to access base on the specular power.
  48699. //--------------------------------------------------------------------------------------
  48700. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  48701. // We want to find the alpha such that:
  48702. // cos(alpha)^cosinePower = epsilon
  48703. // That's: acos(epsilon^(1/cosinePower))
  48704. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  48705. var angle = 180.0;
  48706. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  48707. angle *= 180.0 / Math.PI; // Convert to degree
  48708. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  48709. return angle;
  48710. };
  48711. //--------------------------------------------------------------------------------------
  48712. //Builds the following lookup tables prior to filtering:
  48713. // -normalizer cube map
  48714. // -tap weight lookup table
  48715. //
  48716. //--------------------------------------------------------------------------------------
  48717. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  48718. var srcTexelAngle;
  48719. var iCubeFace;
  48720. //clear pre-existing normalizer cube map
  48721. this._normCubeMap = [];
  48722. //Normalized vectors per cubeface and per-texel solid angle
  48723. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  48724. };
  48725. //--------------------------------------------------------------------------------------
  48726. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  48727. //
  48728. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  48729. //
  48730. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  48731. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  48732. // below
  48733. //--------------------------------------------------------------------------------------
  48734. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  48735. var iCubeFace;
  48736. var u;
  48737. var v;
  48738. //iterate over cube faces
  48739. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  48740. //First three channels for norm cube, and last channel for solid angle
  48741. this._normCubeMap.push(new Float32Array(size * size * 4));
  48742. //fast texture walk, build normalizer cube map
  48743. var facesData = this.input[iCubeFace];
  48744. for (v = 0; v < size; v++) {
  48745. for (u = 0; u < size; u++) {
  48746. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  48747. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  48748. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  48749. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  48750. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  48751. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  48752. }
  48753. }
  48754. }
  48755. };
  48756. //--------------------------------------------------------------------------------------
  48757. // Convert cubemap face texel coordinates and face idx to 3D vector
  48758. // note the U and V coords are integer coords and range from 0 to size-1
  48759. // this routine can be used to generate a normalizer cube map
  48760. //--------------------------------------------------------------------------------------
  48761. // SL BEGIN
  48762. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  48763. var nvcU;
  48764. var nvcV;
  48765. var tempVec;
  48766. // Change from original AMD code
  48767. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  48768. // + 0.5f is for texel center addressing
  48769. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  48770. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  48771. // warp fixup
  48772. if (fixup && size > 1) {
  48773. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  48774. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  48775. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  48776. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  48777. }
  48778. // Get current vector
  48779. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  48780. // U contribution
  48781. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  48782. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  48783. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  48784. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  48785. // V contribution and Sum
  48786. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  48787. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  48788. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  48789. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  48790. //add face axis
  48791. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  48792. PMREMGenerator._vectorTemp.x += faceAxis[0];
  48793. PMREMGenerator._vectorTemp.y += faceAxis[1];
  48794. PMREMGenerator._vectorTemp.z += faceAxis[2];
  48795. //normalize vector
  48796. PMREMGenerator._vectorTemp.normalize();
  48797. return PMREMGenerator._vectorTemp;
  48798. };
  48799. //--------------------------------------------------------------------------------------
  48800. // Convert 3D vector to cubemap face texel coordinates and face idx
  48801. // note the U and V coords are integer coords and range from 0 to size-1
  48802. // this routine can be used to generate a normalizer cube map
  48803. //
  48804. // returns face IDX and texel coords
  48805. //--------------------------------------------------------------------------------------
  48806. // SL BEGIN
  48807. /*
  48808. Mapping Texture Coordinates to Cube Map Faces
  48809. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  48810. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  48811. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  48812. map arrangement in Pixar's RenderMan package.
  48813. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  48814. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  48815. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  48816. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  48817. the major axis direction). The target column in the table below explains how the major axis direction
  48818. maps to the 2D image of a particular cube map target.
  48819. major axis
  48820. direction target sc tc ma
  48821. ---------- --------------------------------- --- --- ---
  48822. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  48823. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  48824. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  48825. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  48826. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  48827. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  48828. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  48829. an updated (s,t) is calculated as follows
  48830. s = ( sc/|ma| + 1 ) / 2
  48831. t = ( tc/|ma| + 1 ) / 2
  48832. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  48833. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  48834. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  48835. */
  48836. // Note this method return U and V in range from 0 to size-1
  48837. // SL END
  48838. // Store the information in vector3 for convenience (faceindex, u, v)
  48839. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  48840. var maxCoord;
  48841. var faceIdx;
  48842. //absolute value 3
  48843. var absX = Math.abs(x);
  48844. var absY = Math.abs(y);
  48845. var absZ = Math.abs(z);
  48846. if (absX >= absY && absX >= absZ) {
  48847. maxCoord = absX;
  48848. if (x >= 0) {
  48849. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  48850. }
  48851. else {
  48852. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  48853. }
  48854. }
  48855. else if (absY >= absX && absY >= absZ) {
  48856. maxCoord = absY;
  48857. if (y >= 0) {
  48858. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  48859. }
  48860. else {
  48861. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  48862. }
  48863. }
  48864. else {
  48865. maxCoord = absZ;
  48866. if (z >= 0) {
  48867. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  48868. }
  48869. else {
  48870. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  48871. }
  48872. }
  48873. //divide through by max coord so face vector lies on cube face
  48874. var scale = 1 / maxCoord;
  48875. x *= scale;
  48876. y *= scale;
  48877. z *= scale;
  48878. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  48879. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  48880. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  48881. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  48882. // Modify original AMD code to return value from 0 to Size - 1
  48883. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  48884. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  48885. PMREMGenerator._vectorTemp.x = faceIdx;
  48886. PMREMGenerator._vectorTemp.y = u;
  48887. PMREMGenerator._vectorTemp.z = v;
  48888. return PMREMGenerator._vectorTemp;
  48889. };
  48890. //--------------------------------------------------------------------------------------
  48891. //Original code from Ignacio CastaÒo
  48892. // This formula is from Manne ÷hrstrˆm's thesis.
  48893. // Take two coordiantes in the range [-1, 1] that define a portion of a
  48894. // cube face and return the area of the projection of that portion on the
  48895. // surface of the sphere.
  48896. //--------------------------------------------------------------------------------------
  48897. PMREMGenerator.prototype.areaElement = function (x, y) {
  48898. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  48899. };
  48900. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  48901. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  48902. // (+ 0.5f is for texel center addressing)
  48903. u = (2.0 * (u + 0.5) / size) - 1.0;
  48904. v = (2.0 * (v + 0.5) / size) - 1.0;
  48905. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  48906. var invResolution = 1.0 / size;
  48907. // U and V are the -1..1 texture coordinate on the current face.
  48908. // Get projected area for this texel
  48909. var x0 = u - invResolution;
  48910. var y0 = v - invResolution;
  48911. var x1 = u + invResolution;
  48912. var y1 = v + invResolution;
  48913. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  48914. return solidAngle;
  48915. };
  48916. //--------------------------------------------------------------------------------------
  48917. //The key to the speed of these filtering routines is to quickly define a per-face
  48918. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  48919. // Later these pixels are selectively processed based on their dot products to see if
  48920. // they reside within the filtering cone.
  48921. //
  48922. //This is done by computing the smallest per-texel angle to get a conservative estimate
  48923. // of the number of texels needed to be covered in width and height order to filter the
  48924. // region. the bounding box for the center taps face is defined first, and if the
  48925. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  48926. // defined next
  48927. //--------------------------------------------------------------------------------------
  48928. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  48929. // note that pixels within these regions may be rejected
  48930. // based on the anlge
  48931. var iCubeFace;
  48932. var u;
  48933. var v;
  48934. // bounding box per face to specify region to process
  48935. var filterExtents = [];
  48936. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  48937. filterExtents.push(new CMGBoundinBox());
  48938. }
  48939. // min angle a src texel can cover (in degrees)
  48940. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  48941. // angle about center tap to define filter cone
  48942. // filter angle is 1/2 the cone angle
  48943. var filterAngle = filterConeAngle / 2.0;
  48944. //ensure filter angle is larger than a texel
  48945. if (filterAngle < srcTexelAngle) {
  48946. filterAngle = srcTexelAngle;
  48947. }
  48948. //ensure filter cone is always smaller than the hemisphere
  48949. if (filterAngle > 90.0) {
  48950. filterAngle = 90.0;
  48951. }
  48952. // the maximum number of texels in 1D the filter cone angle will cover
  48953. // used to determine bounding box size for filter extents
  48954. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  48955. // ensure conservative region always covers at least one texel
  48956. if (filterSize < 1) {
  48957. filterSize = 1;
  48958. }
  48959. // dotProdThresh threshold based on cone angle to determine whether or not taps
  48960. // reside within the cone angle
  48961. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  48962. // process required faces
  48963. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  48964. //iterate over dst cube map face texel
  48965. for (v = 0; v < dstSize; v++) {
  48966. for (u = 0; u < dstSize; u++) {
  48967. //get center tap direction
  48968. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  48969. //clear old per-face filter extents
  48970. this.clearFilterExtents(filterExtents);
  48971. //define per-face filter extents
  48972. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  48973. //perform filtering of src faces using filter extents
  48974. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  48975. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  48976. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  48977. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  48978. }
  48979. }
  48980. }
  48981. };
  48982. //--------------------------------------------------------------------------------------
  48983. //Clear filter extents for the 6 cube map faces
  48984. //--------------------------------------------------------------------------------------
  48985. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  48986. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  48987. filterExtents[iCubeFaces].clear();
  48988. }
  48989. };
  48990. //--------------------------------------------------------------------------------------
  48991. //Define per-face bounding box filter extents
  48992. //
  48993. // These define conservative texel regions in each of the faces the filter can possibly
  48994. // process. When the pixels in the regions are actually processed, the dot product
  48995. // between the tap vector and the center tap vector is used to determine the weight of
  48996. // the tap and whether or not the tap is within the cone.
  48997. //
  48998. //--------------------------------------------------------------------------------------
  48999. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  49000. //neighboring face and bleed over amount, and width of BBOX for
  49001. // left, right, top, and bottom edges of this face
  49002. var bleedOverAmount = [0, 0, 0, 0];
  49003. var bleedOverBBoxMin = [0, 0, 0, 0];
  49004. var bleedOverBBoxMax = [0, 0, 0, 0];
  49005. var neighborFace;
  49006. var neighborEdge;
  49007. var oppositeFaceIdx;
  49008. //get face idx, and u, v info from center tap dir
  49009. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  49010. var faceIdx = result.x;
  49011. var u = result.y;
  49012. var v = result.z;
  49013. //define bbox size within face
  49014. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  49015. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  49016. filterExtents[faceIdx].clampMin(0, 0, 0);
  49017. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  49018. //u and v extent in face corresponding to center tap
  49019. var minU = filterExtents[faceIdx].min.x;
  49020. var minV = filterExtents[faceIdx].min.y;
  49021. var maxU = filterExtents[faceIdx].max.x;
  49022. var maxV = filterExtents[faceIdx].max.y;
  49023. //bleed over amounts for face across u=0 edge (left)
  49024. bleedOverAmount[0] = (bboxSize - u);
  49025. bleedOverBBoxMin[0] = minV;
  49026. bleedOverBBoxMax[0] = maxV;
  49027. //bleed over amounts for face across u=1 edge (right)
  49028. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  49029. bleedOverBBoxMin[1] = minV;
  49030. bleedOverBBoxMax[1] = maxV;
  49031. //bleed over to face across v=0 edge (up)
  49032. bleedOverAmount[2] = (bboxSize - v);
  49033. bleedOverBBoxMin[2] = minU;
  49034. bleedOverBBoxMax[2] = maxU;
  49035. //bleed over to face across v=1 edge (down)
  49036. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  49037. bleedOverBBoxMin[3] = minU;
  49038. bleedOverBBoxMax[3] = maxU;
  49039. //compute bleed over regions in neighboring faces
  49040. for (var i = 0; i < 4; i++) {
  49041. if (bleedOverAmount[i] > 0) {
  49042. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  49043. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  49044. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  49045. // be flipped: the cases are
  49046. // if a left edge mates with a left or bottom edge on the neighbor
  49047. // if a top edge mates with a top or right edge on the neighbor
  49048. // if a right edge mates with a right or top edge on the neighbor
  49049. // if a bottom edge mates with a bottom or left edge on the neighbor
  49050. //Seeing as the edges are enumerated as follows
  49051. // left =0
  49052. // right =1
  49053. // top =2
  49054. // bottom =3
  49055. //
  49056. // so if the edge enums are the same, or the sum of the enums == 3,
  49057. // the bbox needs to be flipped
  49058. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  49059. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  49060. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  49061. }
  49062. //The way the bounding box is extended onto the neighboring face
  49063. // depends on which edge of neighboring face abuts with this one
  49064. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  49065. case PMREMGenerator.CP_EDGE_LEFT:
  49066. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  49067. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49068. break;
  49069. case PMREMGenerator.CP_EDGE_RIGHT:
  49070. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  49071. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49072. break;
  49073. case PMREMGenerator.CP_EDGE_TOP:
  49074. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  49075. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  49076. break;
  49077. case PMREMGenerator.CP_EDGE_BOTTOM:
  49078. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  49079. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  49080. break;
  49081. }
  49082. //clamp filter extents in non-center tap faces to remain within surface
  49083. filterExtents[neighborFace].clampMin(0, 0, 0);
  49084. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  49085. }
  49086. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  49087. // from the center tap face, then process the opposite face entirely for now.
  49088. //Note that the cases in which this happens, what usually happens is that
  49089. // more than one edge bleeds onto the opposite face, and the bounding box
  49090. // encompasses the entire cube map face.
  49091. if (bleedOverAmount[i] > srcSize) {
  49092. //determine opposite face
  49093. switch (faceIdx) {
  49094. case PMREMGenerator.CP_FACE_X_POS:
  49095. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49096. break;
  49097. case PMREMGenerator.CP_FACE_X_NEG:
  49098. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  49099. break;
  49100. case PMREMGenerator.CP_FACE_Y_POS:
  49101. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49102. break;
  49103. case PMREMGenerator.CP_FACE_Y_NEG:
  49104. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49105. break;
  49106. case PMREMGenerator.CP_FACE_Z_POS:
  49107. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49108. break;
  49109. case PMREMGenerator.CP_FACE_Z_NEG:
  49110. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49111. break;
  49112. default:
  49113. break;
  49114. }
  49115. //just encompass entire face for now
  49116. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  49117. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  49118. }
  49119. }
  49120. };
  49121. //--------------------------------------------------------------------------------------
  49122. //ProcessFilterExtents
  49123. // Process bounding box in each cube face
  49124. //
  49125. //--------------------------------------------------------------------------------------
  49126. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  49127. //accumulators are 64-bit floats in order to have the precision needed
  49128. // over a summation of a large number of pixels
  49129. var dstAccum = [0, 0, 0, 0];
  49130. var weightAccum = 0;
  49131. var k = 0;
  49132. var nSrcChannels = this.numChannels;
  49133. // norm cube map and srcCubeMap have same face width
  49134. var faceWidth = srcSize;
  49135. //amount to add to pointer to move to next scanline in images
  49136. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  49137. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  49138. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  49139. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  49140. // iterate over cubefaces
  49141. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  49142. //if bbox is non empty
  49143. if (!filterExtents[iFaceIdx].empty()) {
  49144. var uStart = filterExtents[iFaceIdx].min.x;
  49145. var vStart = filterExtents[iFaceIdx].min.y;
  49146. var uEnd = filterExtents[iFaceIdx].max.x;
  49147. var vEnd = filterExtents[iFaceIdx].max.y;
  49148. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  49149. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  49150. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  49151. for (var v = vStart; v <= vEnd; v++) {
  49152. var normCubeRowWalk = 0;
  49153. var srcCubeRowWalk = 0;
  49154. for (var u = uStart; u <= uEnd; u++) {
  49155. //pointer to direction in cube map associated with texel
  49156. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  49157. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  49158. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  49159. //check dot product to see if texel is within cone
  49160. var tapDotProd = texelVectX * centerTapDir.x +
  49161. texelVectY * centerTapDir.y +
  49162. texelVectZ * centerTapDir.z;
  49163. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  49164. //solid angle stored in 4th channel of normalizer/solid angle cube map
  49165. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  49166. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  49167. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  49168. // so just adding one to specularpower do the trick.
  49169. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  49170. //iterate over channels
  49171. for (k = 0; k < nSrcChannels; k++) {
  49172. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  49173. srcCubeRowWalk++;
  49174. }
  49175. weightAccum += weight; //accumulate weight
  49176. }
  49177. else {
  49178. //step across source pixel
  49179. srcCubeRowWalk += nSrcChannels;
  49180. }
  49181. normCubeRowWalk += 4; // 4 channels per norm cube map.
  49182. }
  49183. startIndexNormCubeMap += normCubePitch;
  49184. startIndexSrcCubeMap += srcCubePitch;
  49185. }
  49186. }
  49187. }
  49188. //divide through by weights if weight is non zero
  49189. if (weightAccum != 0.0) {
  49190. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  49191. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  49192. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  49193. if (this.numChannels > 3) {
  49194. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  49195. }
  49196. }
  49197. else {
  49198. // otherwise sample nearest
  49199. // get face idx and u, v texel coordinate in face
  49200. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  49201. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  49202. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  49203. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  49204. if (this.numChannels > 3) {
  49205. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  49206. }
  49207. }
  49208. return PMREMGenerator._vectorTemp;
  49209. };
  49210. //--------------------------------------------------------------------------------------
  49211. // Fixup cube edges
  49212. //
  49213. // average texels on cube map faces across the edges
  49214. // WARP/BENT Method Only.
  49215. //--------------------------------------------------------------------------------------
  49216. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  49217. var k;
  49218. var j;
  49219. var i;
  49220. var iFace;
  49221. var iCorner = 0;
  49222. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  49223. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  49224. // note that if functionality to filter across the three texels for each corner, then
  49225. //indexed by corner and face idx. the array contains the face the start points belongs to.
  49226. var cornerPtr = [
  49227. [[], [], []],
  49228. [[], [], []],
  49229. [[], [], []],
  49230. [[], [], []],
  49231. [[], [], []],
  49232. [[], [], []],
  49233. [[], [], []],
  49234. [[], [], []]
  49235. ];
  49236. //if there is no fixup, or fixup width = 0, do nothing
  49237. if (cubeMapSize < 1) {
  49238. return;
  49239. }
  49240. //special case 1x1 cubemap, average face colors
  49241. if (cubeMapSize == 1) {
  49242. //iterate over channels
  49243. for (k = 0; k < this.numChannels; k++) {
  49244. var accum = 0.0;
  49245. //iterate over faces to accumulate face colors
  49246. for (iFace = 0; iFace < 6; iFace++) {
  49247. accum += cubeMap[iFace][k];
  49248. }
  49249. //compute average over 6 face colors
  49250. accum /= 6.0;
  49251. //iterate over faces to distribute face colors
  49252. for (iFace = 0; iFace < 6; iFace++) {
  49253. cubeMap[iFace][k] = accum;
  49254. }
  49255. }
  49256. return;
  49257. }
  49258. //iterate over faces to collect list of corner texel pointers
  49259. for (iFace = 0; iFace < 6; iFace++) {
  49260. //the 4 corner pointers for this face
  49261. faceCornerStartIndicies[0] = [iFace, 0];
  49262. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  49263. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  49264. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  49265. //iterate over face corners to collect cube corner pointers
  49266. for (iCorner = 0; iCorner < 4; iCorner++) {
  49267. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  49268. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  49269. cornerNumPtrs[corner]++;
  49270. }
  49271. }
  49272. //iterate over corners to average across corner tap values
  49273. for (iCorner = 0; iCorner < 8; iCorner++) {
  49274. for (k = 0; k < this.numChannels; k++) {
  49275. var cornerTapAccum = 0.0;
  49276. //iterate over corner texels and average results
  49277. for (i = 0; i < 3; i++) {
  49278. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  49279. }
  49280. //divide by 3 to compute average of corner tap values
  49281. cornerTapAccum *= (1.0 / 3.0);
  49282. //iterate over corner texels and average results
  49283. for (i = 0; i < 3; i++) {
  49284. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  49285. }
  49286. }
  49287. }
  49288. //iterate over the twelve edges of the cube to average across edges
  49289. for (i = 0; i < 12; i++) {
  49290. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  49291. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  49292. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  49293. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  49294. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  49295. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  49296. var edgeWalk = 0;
  49297. var neighborEdgeWalk = 0;
  49298. //Determine walking pointers based on edge type
  49299. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  49300. switch (edge) {
  49301. case PMREMGenerator.CP_EDGE_LEFT:
  49302. // no change to faceEdgeStartPtr
  49303. edgeWalk = this.numChannels * cubeMapSize;
  49304. break;
  49305. case PMREMGenerator.CP_EDGE_RIGHT:
  49306. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49307. edgeWalk = this.numChannels * cubeMapSize;
  49308. break;
  49309. case PMREMGenerator.CP_EDGE_TOP:
  49310. // no change to faceEdgeStartPtr
  49311. edgeWalk = this.numChannels;
  49312. break;
  49313. case PMREMGenerator.CP_EDGE_BOTTOM:
  49314. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49315. edgeWalk = this.numChannels;
  49316. break;
  49317. }
  49318. //For certain types of edge abutments, the neighbor edge walk needs to
  49319. // be flipped: the cases are
  49320. // if a left edge mates with a left or bottom edge on the neighbor
  49321. // if a top edge mates with a top or right edge on the neighbor
  49322. // if a right edge mates with a right or top edge on the neighbor
  49323. // if a bottom edge mates with a bottom or left edge on the neighbor
  49324. //Seeing as the edges are enumerated as follows
  49325. // left =0
  49326. // right =1
  49327. // top =2
  49328. // bottom =3
  49329. //
  49330. //If the edge enums are the same, or the sum of the enums == 3,
  49331. // the neighbor edge walk needs to be flipped
  49332. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  49333. switch (neighborEdge) {
  49334. case PMREMGenerator.CP_EDGE_LEFT:
  49335. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  49336. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49337. break;
  49338. case PMREMGenerator.CP_EDGE_RIGHT:
  49339. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49340. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49341. break;
  49342. case PMREMGenerator.CP_EDGE_TOP:
  49343. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49344. neighborEdgeWalk = -this.numChannels;
  49345. break;
  49346. case PMREMGenerator.CP_EDGE_BOTTOM:
  49347. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49348. neighborEdgeWalk = -this.numChannels;
  49349. break;
  49350. }
  49351. }
  49352. else {
  49353. //swapped direction neighbor edge walk
  49354. switch (neighborEdge) {
  49355. case PMREMGenerator.CP_EDGE_LEFT:
  49356. //no change to neighborEdgeStartPtr for this case since it points
  49357. // to the upper left corner already
  49358. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49359. break;
  49360. case PMREMGenerator.CP_EDGE_RIGHT:
  49361. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49362. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49363. break;
  49364. case PMREMGenerator.CP_EDGE_TOP:
  49365. //no change to neighborEdgeStartPtr for this case since it points
  49366. // to the upper left corner already
  49367. neighborEdgeWalk = this.numChannels;
  49368. break;
  49369. case PMREMGenerator.CP_EDGE_BOTTOM:
  49370. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49371. neighborEdgeWalk = this.numChannels;
  49372. break;
  49373. }
  49374. }
  49375. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  49376. //nearby neighborhood
  49377. //step ahead one texel on edge
  49378. edgeStartIndex += edgeWalk;
  49379. neighborEdgeStartIndex += neighborEdgeWalk;
  49380. // note that this loop does not process the corner texels, since they have already been
  49381. // averaged across faces across earlier
  49382. for (j = 1; j < (cubeMapSize - 1); j++) {
  49383. //for each set of taps along edge, average them
  49384. // and rewrite the results into the edges
  49385. for (k = 0; k < this.numChannels; k++) {
  49386. var edgeTap = cubeMap[face][edgeStartIndex + k];
  49387. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  49388. //compute average of tap intensity values
  49389. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  49390. //propagate average of taps to edge taps
  49391. cubeMap[face][edgeStartIndex + k] = avgTap;
  49392. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  49393. }
  49394. edgeStartIndex += edgeWalk;
  49395. neighborEdgeStartIndex += neighborEdgeWalk;
  49396. }
  49397. }
  49398. };
  49399. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  49400. PMREMGenerator.CP_UDIR = 0;
  49401. PMREMGenerator.CP_VDIR = 1;
  49402. PMREMGenerator.CP_FACEAXIS = 2;
  49403. //used to index cube faces
  49404. PMREMGenerator.CP_FACE_X_POS = 0;
  49405. PMREMGenerator.CP_FACE_X_NEG = 1;
  49406. PMREMGenerator.CP_FACE_Y_POS = 2;
  49407. PMREMGenerator.CP_FACE_Y_NEG = 3;
  49408. PMREMGenerator.CP_FACE_Z_POS = 4;
  49409. PMREMGenerator.CP_FACE_Z_NEG = 5;
  49410. //used to index image edges
  49411. // NOTE.. the actual number corresponding to the edge is important
  49412. // do not change these, or the code will break
  49413. //
  49414. // CP_EDGE_LEFT is u = 0
  49415. // CP_EDGE_RIGHT is u = width-1
  49416. // CP_EDGE_TOP is v = 0
  49417. // CP_EDGE_BOTTOM is v = height-1
  49418. PMREMGenerator.CP_EDGE_LEFT = 0;
  49419. PMREMGenerator.CP_EDGE_RIGHT = 1;
  49420. PMREMGenerator.CP_EDGE_TOP = 2;
  49421. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  49422. //corners of CUBE map (P or N specifys if it corresponds to the
  49423. // positive or negative direction each of X, Y, and Z
  49424. PMREMGenerator.CP_CORNER_NNN = 0;
  49425. PMREMGenerator.CP_CORNER_NNP = 1;
  49426. PMREMGenerator.CP_CORNER_NPN = 2;
  49427. PMREMGenerator.CP_CORNER_NPP = 3;
  49428. PMREMGenerator.CP_CORNER_PNN = 4;
  49429. PMREMGenerator.CP_CORNER_PNP = 5;
  49430. PMREMGenerator.CP_CORNER_PPN = 6;
  49431. PMREMGenerator.CP_CORNER_PPP = 7;
  49432. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  49433. //3x2 matrices that map cube map indexing vectors in 3d
  49434. // (after face selection and divide through by the
  49435. // _ABSOLUTE VALUE_ of the max coord)
  49436. // into NVC space
  49437. //Note this currently assumes the D3D cube face ordering and orientation
  49438. PMREMGenerator._sgFace2DMapping = [
  49439. //XPOS face
  49440. [[0, 0, -1],
  49441. [0, -1, 0],
  49442. [1, 0, 0]],
  49443. //XNEG face
  49444. [[0, 0, 1],
  49445. [0, -1, 0],
  49446. [-1, 0, 0]],
  49447. //YPOS face
  49448. [[1, 0, 0],
  49449. [0, 0, 1],
  49450. [0, 1, 0]],
  49451. //YNEG face
  49452. [[1, 0, 0],
  49453. [0, 0, -1],
  49454. [0, -1, 0]],
  49455. //ZPOS face
  49456. [[1, 0, 0],
  49457. [0, -1, 0],
  49458. [0, 0, 1]],
  49459. //ZNEG face
  49460. [[-1, 0, 0],
  49461. [0, -1, 0],
  49462. [0, 0, -1]],
  49463. ];
  49464. //------------------------------------------------------------------------------
  49465. // D3D cube map face specification
  49466. // mapping from 3D x,y,z cube map lookup coordinates
  49467. // to 2D within face u,v coordinates
  49468. //
  49469. // --------------------> U direction
  49470. // | (within-face texture space)
  49471. // | _____
  49472. // | | |
  49473. // | | +Y |
  49474. // | _____|_____|_____ _____
  49475. // | | | | | |
  49476. // | | -X | +Z | +X | -Z |
  49477. // | |_____|_____|_____|_____|
  49478. // | | |
  49479. // | | -Y |
  49480. // | |_____|
  49481. // |
  49482. // v V direction
  49483. // (within-face texture space)
  49484. //------------------------------------------------------------------------------
  49485. //Information about neighbors and how texture coorrdinates change across faces
  49486. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  49487. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  49488. //Note this currently assumes the D3D cube face ordering and orientation
  49489. PMREMGenerator._sgCubeNgh = [
  49490. //XPOS face
  49491. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49492. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49493. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49494. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  49495. //XNEG face
  49496. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49497. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  49498. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  49499. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  49500. //YPOS face
  49501. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  49502. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  49503. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  49504. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  49505. //YNEG face
  49506. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  49507. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49508. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49509. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  49510. //ZPOS face
  49511. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49512. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49513. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49514. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  49515. //ZNEG face
  49516. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49517. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49518. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  49519. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  49520. ];
  49521. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  49522. // this table is used to average over the edges.
  49523. PMREMGenerator._sgCubeEdgeList = [
  49524. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49525. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49526. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  49527. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49528. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49529. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49530. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  49531. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  49532. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  49533. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49534. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  49535. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  49536. ];
  49537. //Information about which of the 8 cube corners are correspond to the
  49538. // the 4 corners in each cube face
  49539. // the order is upper left, upper right, lower left, lower right
  49540. PMREMGenerator._sgCubeCornerList = [
  49541. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  49542. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  49543. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  49544. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  49545. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  49546. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  49547. ];
  49548. return PMREMGenerator;
  49549. })();
  49550. Internals.PMREMGenerator = PMREMGenerator;
  49551. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49552. })(BABYLON || (BABYLON = {}));
  49553. var BABYLON;
  49554. (function (BABYLON) {
  49555. /**
  49556. * This represents a texture coming from an HDR input.
  49557. *
  49558. * The only supported format is currently panorama picture stored in RGBE format.
  49559. * Example of such files can be found on HDRLib: http://hdrlib.com/
  49560. */
  49561. var HDRCubeTexture = (function (_super) {
  49562. __extends(HDRCubeTexture, _super);
  49563. /**
  49564. * Instantiates an HDRTexture from the following parameters.
  49565. *
  49566. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  49567. * @param scene The scene the texture will be used in
  49568. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  49569. * @param noMipmap Forces to not generate the mipmap if true
  49570. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  49571. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  49572. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  49573. */
  49574. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  49575. if (noMipmap === void 0) { noMipmap = false; }
  49576. if (generateHarmonics === void 0) { generateHarmonics = true; }
  49577. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  49578. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  49579. _super.call(this, scene);
  49580. this._useInGammaSpace = false;
  49581. this._generateHarmonics = true;
  49582. this._isBABYLONPreprocessed = false;
  49583. /**
  49584. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  49585. */
  49586. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49587. /**
  49588. * The spherical polynomial data extracted from the texture.
  49589. */
  49590. this.sphericalPolynomial = null;
  49591. /**
  49592. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  49593. * This is usefull at run time to apply the good shader.
  49594. */
  49595. this.isPMREM = false;
  49596. if (!url) {
  49597. return;
  49598. }
  49599. this.name = url;
  49600. this.url = url;
  49601. this.hasAlpha = false;
  49602. this.isCube = true;
  49603. this._textureMatrix = BABYLON.Matrix.Identity();
  49604. if (size) {
  49605. this._isBABYLONPreprocessed = false;
  49606. this._noMipmap = noMipmap;
  49607. this._size = size;
  49608. this._useInGammaSpace = useInGammaSpace;
  49609. this._usePMREMGenerator = usePMREMGenerator &&
  49610. scene.getEngine().getCaps().textureLOD &&
  49611. this.getScene().getEngine().getCaps().textureFloat &&
  49612. !this._useInGammaSpace;
  49613. }
  49614. else {
  49615. this._isBABYLONPreprocessed = true;
  49616. this._noMipmap = false;
  49617. this._useInGammaSpace = false;
  49618. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  49619. this.getScene().getEngine().getCaps().textureFloat &&
  49620. !this._useInGammaSpace;
  49621. }
  49622. this.isPMREM = this._usePMREMGenerator;
  49623. this._texture = this._getFromCache(url, this._noMipmap);
  49624. if (!this._texture) {
  49625. if (!scene.useDelayedTextureLoading) {
  49626. this.loadTexture();
  49627. }
  49628. else {
  49629. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49630. }
  49631. }
  49632. }
  49633. /**
  49634. * Occurs when the file is a preprocessed .babylon.hdr file.
  49635. */
  49636. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  49637. var _this = this;
  49638. var mipLevels = 0;
  49639. var floatArrayView = null;
  49640. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  49641. var mips = [];
  49642. var startIndex = 30;
  49643. for (var level = 0; level < mipLevels; level++) {
  49644. mips.push([]);
  49645. // Fill each pixel of the mip level.
  49646. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  49647. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49648. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  49649. mips[level].push(faceData);
  49650. startIndex += faceSize;
  49651. }
  49652. }
  49653. return mips;
  49654. } : null;
  49655. var callback = function (buffer) {
  49656. // Create Native Array Views
  49657. var intArrayView = new Int32Array(buffer);
  49658. floatArrayView = new Float32Array(buffer);
  49659. // Fill header.
  49660. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  49661. _this._size = intArrayView[1]; // CubeMap max mip face size.
  49662. // Update Texture Information.
  49663. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  49664. // Fill polynomial information.
  49665. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  49666. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  49667. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  49668. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  49669. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  49670. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  49671. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  49672. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  49673. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  49674. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  49675. // Fill pixel data.
  49676. mipLevels = intArrayView[29]; // Number of mip levels.
  49677. var startIndex = 30;
  49678. var data = [];
  49679. var faceSize = Math.pow(_this._size, 2) * 3;
  49680. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49681. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  49682. startIndex += faceSize;
  49683. }
  49684. var results = [];
  49685. var byteArray = null;
  49686. // Push each faces.
  49687. for (var k = 0; k < 6; k++) {
  49688. var dataFace = null;
  49689. // If special cases.
  49690. if (!mipmapGenerator) {
  49691. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  49692. dataFace = data[j];
  49693. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  49694. // 3 channels of 1 bytes per pixel in bytes.
  49695. var byteBuffer = new ArrayBuffer(faceSize);
  49696. byteArray = new Uint8Array(byteBuffer);
  49697. }
  49698. for (var i = 0; i < _this._size * _this._size; i++) {
  49699. // Put in gamma space if requested.
  49700. if (_this._useInGammaSpace) {
  49701. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  49702. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  49703. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  49704. }
  49705. // Convert to int texture for fallback.
  49706. if (byteArray) {
  49707. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  49708. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  49709. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  49710. // May use luminance instead if the result is not accurate.
  49711. var max = Math.max(Math.max(r, g), b);
  49712. if (max > 255) {
  49713. var scale = 255 / max;
  49714. r *= scale;
  49715. g *= scale;
  49716. b *= scale;
  49717. }
  49718. byteArray[(i * 3) + 0] = r;
  49719. byteArray[(i * 3) + 1] = g;
  49720. byteArray[(i * 3) + 2] = b;
  49721. }
  49722. }
  49723. }
  49724. else {
  49725. dataFace = data[k];
  49726. }
  49727. // Fill the array accordingly.
  49728. if (byteArray) {
  49729. results.push(byteArray);
  49730. }
  49731. else {
  49732. results.push(dataFace);
  49733. }
  49734. }
  49735. return results;
  49736. };
  49737. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  49738. };
  49739. /**
  49740. * Occurs when the file is raw .hdr file.
  49741. */
  49742. HDRCubeTexture.prototype.loadHDRTexture = function () {
  49743. var _this = this;
  49744. var callback = function (buffer) {
  49745. // Extract the raw linear data.
  49746. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  49747. // Generate harmonics if needed.
  49748. if (_this._generateHarmonics) {
  49749. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  49750. }
  49751. var results = [];
  49752. var byteArray = null;
  49753. // Push each faces.
  49754. for (var j = 0; j < 6; j++) {
  49755. // Create uintarray fallback.
  49756. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  49757. // 3 channels of 1 bytes per pixel in bytes.
  49758. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  49759. byteArray = new Uint8Array(byteBuffer);
  49760. }
  49761. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  49762. // If special cases.
  49763. if (_this._useInGammaSpace || byteArray) {
  49764. for (var i = 0; i < _this._size * _this._size; i++) {
  49765. // Put in gamma space if requested.
  49766. if (_this._useInGammaSpace) {
  49767. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  49768. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  49769. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  49770. }
  49771. // Convert to int texture for fallback.
  49772. if (byteArray) {
  49773. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  49774. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  49775. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  49776. // May use luminance instead if the result is not accurate.
  49777. var max = Math.max(Math.max(r, g), b);
  49778. if (max > 255) {
  49779. var scale = 255 / max;
  49780. r *= scale;
  49781. g *= scale;
  49782. b *= scale;
  49783. }
  49784. byteArray[(i * 3) + 0] = r;
  49785. byteArray[(i * 3) + 1] = g;
  49786. byteArray[(i * 3) + 2] = b;
  49787. }
  49788. }
  49789. }
  49790. if (byteArray) {
  49791. results.push(byteArray);
  49792. }
  49793. else {
  49794. results.push(dataFace);
  49795. }
  49796. }
  49797. return results;
  49798. };
  49799. var mipmapGenerator = null;
  49800. if (!this._noMipmap &&
  49801. this._usePMREMGenerator) {
  49802. mipmapGenerator = function (data) {
  49803. // Custom setup of the generator matching with the PBR shader values.
  49804. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  49805. return generator.filterCubeMap();
  49806. };
  49807. }
  49808. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  49809. };
  49810. /**
  49811. * Starts the loading process of the texture.
  49812. */
  49813. HDRCubeTexture.prototype.loadTexture = function () {
  49814. if (this._isBABYLONPreprocessed) {
  49815. this.loadBabylonTexture();
  49816. }
  49817. else {
  49818. this.loadHDRTexture();
  49819. }
  49820. };
  49821. HDRCubeTexture.prototype.clone = function () {
  49822. var size = this._isBABYLONPreprocessed ? null : this._size;
  49823. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  49824. // Base texture
  49825. newTexture.level = this.level;
  49826. newTexture.wrapU = this.wrapU;
  49827. newTexture.wrapV = this.wrapV;
  49828. newTexture.coordinatesIndex = this.coordinatesIndex;
  49829. newTexture.coordinatesMode = this.coordinatesMode;
  49830. return newTexture;
  49831. };
  49832. // Methods
  49833. HDRCubeTexture.prototype.delayLoad = function () {
  49834. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49835. return;
  49836. }
  49837. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49838. this._texture = this._getFromCache(this.url, this._noMipmap);
  49839. if (!this._texture) {
  49840. this.loadTexture();
  49841. }
  49842. };
  49843. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  49844. return this._textureMatrix;
  49845. };
  49846. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49847. var texture = null;
  49848. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  49849. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  49850. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  49851. texture.name = parsedTexture.name;
  49852. texture.hasAlpha = parsedTexture.hasAlpha;
  49853. texture.level = parsedTexture.level;
  49854. texture.coordinatesMode = parsedTexture.coordinatesMode;
  49855. }
  49856. return texture;
  49857. };
  49858. HDRCubeTexture.prototype.serialize = function () {
  49859. if (!this.name) {
  49860. return null;
  49861. }
  49862. var serializationObject = {};
  49863. serializationObject.name = this.name;
  49864. serializationObject.hasAlpha = this.hasAlpha;
  49865. serializationObject.isCube = true;
  49866. serializationObject.level = this.level;
  49867. serializationObject.size = this._size;
  49868. serializationObject.coordinatesMode = this.coordinatesMode;
  49869. serializationObject.useInGammaSpace = this._useInGammaSpace;
  49870. serializationObject.generateHarmonics = this._generateHarmonics;
  49871. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  49872. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  49873. return serializationObject;
  49874. };
  49875. /**
  49876. * Saves as a file the data contained in the texture in a binary format.
  49877. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49878. * as the spherical used in the lighting.
  49879. * @param url The HDR file url.
  49880. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49881. * @param onError Method called if any error happens during download.
  49882. * @return The packed binary data.
  49883. */
  49884. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  49885. if (onError === void 0) { onError = null; }
  49886. var callback = function (buffer) {
  49887. var data = new Blob([buffer], { type: 'application/octet-stream' });
  49888. // Returns a URL you can use as a href.
  49889. var objUrl = window.URL.createObjectURL(data);
  49890. // Simulates a link to it and click to dowload.
  49891. var a = document.createElement("a");
  49892. document.body.appendChild(a);
  49893. a.style.display = "none";
  49894. a.href = objUrl;
  49895. a.download = "envmap.babylon.hdr";
  49896. a.click();
  49897. };
  49898. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  49899. };
  49900. /**
  49901. * Serializes the data contained in the texture in a binary format.
  49902. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49903. * as the spherical used in the lighting.
  49904. * @param url The HDR file url.
  49905. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49906. * @param onError Method called if any error happens during download.
  49907. * @return The packed binary data.
  49908. */
  49909. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  49910. if (onError === void 0) { onError = null; }
  49911. // Needs the url tho create the texture.
  49912. if (!url) {
  49913. return null;
  49914. }
  49915. // Check Power of two size.
  49916. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  49917. return null;
  49918. }
  49919. var getDataCallback = function (dataBuffer) {
  49920. // Extract the raw linear data.
  49921. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  49922. // Generate harmonics if needed.
  49923. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  49924. // Generate seamless faces
  49925. var mipGeneratorArray = [];
  49926. // Data are known to be in +X +Y +Z -X -Y -Z
  49927. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  49928. mipGeneratorArray.push(cubeData.right); // +X
  49929. mipGeneratorArray.push(cubeData.left); // -X
  49930. mipGeneratorArray.push(cubeData.up); // +Y
  49931. mipGeneratorArray.push(cubeData.down); // -Y
  49932. mipGeneratorArray.push(cubeData.front); // +Z
  49933. mipGeneratorArray.push(cubeData.back); // -Z
  49934. // Custom setup of the generator matching with the PBR shader values.
  49935. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  49936. var mippedData = generator.filterCubeMap();
  49937. // Compute required byte length.
  49938. var byteLength = 1 * 4; // Raw Data Version int32.
  49939. byteLength += 4; // CubeMap max mip face size int32.
  49940. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  49941. // Add data size.
  49942. byteLength += 4; // Number of mip levels int32.
  49943. for (var level = 0; level < mippedData.length; level++) {
  49944. var mipSize = size >> level;
  49945. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  49946. }
  49947. // Prepare binary structure.
  49948. var buffer = new ArrayBuffer(byteLength);
  49949. var intArrayView = new Int32Array(buffer);
  49950. var floatArrayView = new Float32Array(buffer);
  49951. // Fill header.
  49952. intArrayView[0] = 1; // Version 1.
  49953. intArrayView[1] = size; // CubeMap max mip face size.
  49954. // Fill polynomial information.
  49955. sphericalPolynomial.x.toArray(floatArrayView, 2);
  49956. sphericalPolynomial.y.toArray(floatArrayView, 5);
  49957. sphericalPolynomial.z.toArray(floatArrayView, 8);
  49958. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  49959. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  49960. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  49961. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  49962. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  49963. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  49964. // Fill pixel data.
  49965. intArrayView[29] = mippedData.length; // Number of mip levels.
  49966. var startIndex = 30;
  49967. for (var level = 0; level < mippedData.length; level++) {
  49968. // Fill each pixel of the mip level.
  49969. var faceSize = Math.pow(size >> level, 2) * 3;
  49970. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49971. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  49972. startIndex += faceSize;
  49973. }
  49974. }
  49975. // Callback.
  49976. callback(buffer);
  49977. };
  49978. // Download and process.
  49979. BABYLON.Tools.LoadFile(url, function (data) {
  49980. getDataCallback(data);
  49981. }, null, null, true, onError);
  49982. };
  49983. HDRCubeTexture._facesMapping = [
  49984. "right",
  49985. "up",
  49986. "front",
  49987. "left",
  49988. "down",
  49989. "back"
  49990. ];
  49991. return HDRCubeTexture;
  49992. })(BABYLON.BaseTexture);
  49993. BABYLON.HDRCubeTexture = HDRCubeTexture;
  49994. })(BABYLON || (BABYLON = {}));
  49995. var BABYLON;
  49996. (function (BABYLON) {
  49997. var Debug;
  49998. (function (Debug) {
  49999. /**
  50000. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  50001. */
  50002. var SkeletonViewer = (function () {
  50003. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  50004. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  50005. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  50006. this.skeleton = skeleton;
  50007. this.mesh = mesh;
  50008. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  50009. this.renderingGroupId = renderingGroupId;
  50010. this.color = BABYLON.Color3.White();
  50011. this._debugLines = [];
  50012. this._isEnabled = false;
  50013. this._scene = scene;
  50014. this.update();
  50015. this._renderFunction = this.update.bind(this);
  50016. }
  50017. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  50018. get: function () {
  50019. return this._isEnabled;
  50020. },
  50021. set: function (value) {
  50022. if (this._isEnabled === value) {
  50023. return;
  50024. }
  50025. this._isEnabled = value;
  50026. if (value) {
  50027. this._scene.registerBeforeRender(this._renderFunction);
  50028. }
  50029. else {
  50030. this._scene.unregisterBeforeRender(this._renderFunction);
  50031. }
  50032. },
  50033. enumerable: true,
  50034. configurable: true
  50035. });
  50036. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  50037. if (x === void 0) { x = 0; }
  50038. if (y === void 0) { y = 0; }
  50039. if (z === void 0) { z = 0; }
  50040. var tmat = BABYLON.Tmp.Matrix[0];
  50041. var parentBone = bone.getParent();
  50042. tmat.copyFrom(bone.getLocalMatrix());
  50043. if (x !== 0 || y !== 0 || z !== 0) {
  50044. var tmat2 = BABYLON.Tmp.Matrix[1];
  50045. BABYLON.Matrix.IdentityToRef(tmat2);
  50046. tmat2.m[12] = x;
  50047. tmat2.m[13] = y;
  50048. tmat2.m[14] = z;
  50049. tmat2.multiplyToRef(tmat, tmat);
  50050. }
  50051. if (parentBone) {
  50052. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  50053. }
  50054. tmat.multiplyToRef(meshMat, tmat);
  50055. position.x = tmat.m[12];
  50056. position.y = tmat.m[13];
  50057. position.z = tmat.m[14];
  50058. };
  50059. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  50060. var len = bones.length;
  50061. for (var i = 0; i < len; i++) {
  50062. var bone = bones[i];
  50063. var points = this._debugLines[i];
  50064. if (!points) {
  50065. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50066. this._debugLines[i] = points;
  50067. }
  50068. this._getBonePosition(points[0], bone, meshMat);
  50069. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  50070. }
  50071. };
  50072. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  50073. var len = bones.length;
  50074. var boneNum = 0;
  50075. for (var i = len - 1; i >= 0; i--) {
  50076. var childBone = bones[i];
  50077. var parentBone = childBone.getParent();
  50078. if (!parentBone) {
  50079. continue;
  50080. }
  50081. var points = this._debugLines[boneNum];
  50082. if (!points) {
  50083. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50084. this._debugLines[boneNum] = points;
  50085. }
  50086. this._getBonePosition(points[0], childBone, meshMat);
  50087. this._getBonePosition(points[1], parentBone, meshMat);
  50088. boneNum++;
  50089. }
  50090. };
  50091. SkeletonViewer.prototype.update = function () {
  50092. if (this.autoUpdateBonesMatrices) {
  50093. this._updateBoneMatrix(this.skeleton.bones[0]);
  50094. }
  50095. if (this.skeleton.bones[0].length === undefined) {
  50096. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50097. }
  50098. else {
  50099. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50100. }
  50101. if (!this._debugMesh) {
  50102. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  50103. this._debugMesh.renderingGroupId = this.renderingGroupId;
  50104. }
  50105. else {
  50106. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  50107. }
  50108. this._debugMesh.color = this.color;
  50109. };
  50110. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  50111. if (bone.getParent()) {
  50112. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  50113. }
  50114. var children = bone.children;
  50115. var len = children.length;
  50116. for (var i = 0; i < len; i++) {
  50117. this._updateBoneMatrix(children[i]);
  50118. }
  50119. };
  50120. SkeletonViewer.prototype.dispose = function () {
  50121. if (this._debugMesh) {
  50122. this.isEnabled = false;
  50123. this._debugMesh.dispose();
  50124. this._debugMesh = null;
  50125. }
  50126. };
  50127. return SkeletonViewer;
  50128. })();
  50129. Debug.SkeletonViewer = SkeletonViewer;
  50130. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  50131. })(BABYLON || (BABYLON = {}));
  50132. var BABYLON;
  50133. (function (BABYLON) {
  50134. /**
  50135. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  50136. * It can help converting any input color in a desired output one. This can then be used to create effects
  50137. * from sepia, black and white to sixties or futuristic rendering...
  50138. *
  50139. * The only supported format is currently 3dl.
  50140. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  50141. */
  50142. var ColorGradingTexture = (function (_super) {
  50143. __extends(ColorGradingTexture, _super);
  50144. /**
  50145. * Instantiates a ColorGradingTexture from the following parameters.
  50146. *
  50147. * @param url The location of the color gradind data (currently only supporting 3dl)
  50148. * @param scene The scene the texture will be used in
  50149. */
  50150. function ColorGradingTexture(url, scene) {
  50151. _super.call(this, scene);
  50152. if (!url) {
  50153. return;
  50154. }
  50155. this._textureMatrix = BABYLON.Matrix.Identity();
  50156. this.name = url;
  50157. this.url = url;
  50158. this.hasAlpha = false;
  50159. this.isCube = false;
  50160. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50161. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50162. this.anisotropicFilteringLevel = 1;
  50163. this._texture = this._getFromCache(url, true);
  50164. if (!this._texture) {
  50165. if (!scene.useDelayedTextureLoading) {
  50166. this.loadTexture();
  50167. }
  50168. else {
  50169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50170. }
  50171. }
  50172. }
  50173. /**
  50174. * Returns the texture matrix used in most of the material.
  50175. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  50176. */
  50177. ColorGradingTexture.prototype.getTextureMatrix = function () {
  50178. return this._textureMatrix;
  50179. };
  50180. /**
  50181. * Occurs when the file being loaded is a .3dl LUT file.
  50182. */
  50183. ColorGradingTexture.prototype.load3dlTexture = function () {
  50184. var _this = this;
  50185. var mipLevels = 0;
  50186. var floatArrayView = null;
  50187. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50188. this._texture = texture;
  50189. var callback = function (text) {
  50190. var data;
  50191. var tempData;
  50192. var line;
  50193. var lines = text.split('\n');
  50194. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  50195. var maxColor = 0;
  50196. for (var i = 0; i < lines.length; i++) {
  50197. line = lines[i];
  50198. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  50199. continue;
  50200. if (line.indexOf('#') === 0)
  50201. continue;
  50202. var words = line.split(" ");
  50203. if (size === 0) {
  50204. // Number of space + one
  50205. size = words.length;
  50206. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  50207. tempData = new Float32Array(size * size * size * 4);
  50208. continue;
  50209. }
  50210. if (size != 0) {
  50211. var r = Math.max(parseInt(words[0]), 0);
  50212. var g = Math.max(parseInt(words[1]), 0);
  50213. var b = Math.max(parseInt(words[2]), 0);
  50214. maxColor = Math.max(r, maxColor);
  50215. maxColor = Math.max(g, maxColor);
  50216. maxColor = Math.max(b, maxColor);
  50217. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  50218. tempData[pixelStorageIndex + 0] = r;
  50219. tempData[pixelStorageIndex + 1] = g;
  50220. tempData[pixelStorageIndex + 2] = b;
  50221. tempData[pixelStorageIndex + 3] = 0;
  50222. pixelIndexSlice++;
  50223. if (pixelIndexSlice % size == 0) {
  50224. pixelIndexH++;
  50225. pixelIndexSlice = 0;
  50226. if (pixelIndexH % size == 0) {
  50227. pixelIndexW++;
  50228. pixelIndexH = 0;
  50229. }
  50230. }
  50231. }
  50232. }
  50233. for (var i = 0; i < tempData.length; i++) {
  50234. var value = tempData[i];
  50235. data[i] = (value / maxColor * 255);
  50236. }
  50237. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  50238. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  50239. };
  50240. BABYLON.Tools.LoadFile(this.url, callback);
  50241. return this._texture;
  50242. };
  50243. /**
  50244. * Starts the loading process of the texture.
  50245. */
  50246. ColorGradingTexture.prototype.loadTexture = function () {
  50247. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  50248. this.load3dlTexture();
  50249. }
  50250. };
  50251. /**
  50252. * Clones the color gradind texture.
  50253. */
  50254. ColorGradingTexture.prototype.clone = function () {
  50255. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  50256. // Base texture
  50257. newTexture.level = this.level;
  50258. return newTexture;
  50259. };
  50260. /**
  50261. * Called during delayed load for textures.
  50262. */
  50263. ColorGradingTexture.prototype.delayLoad = function () {
  50264. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50265. return;
  50266. }
  50267. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50268. this._texture = this._getFromCache(this.url, true);
  50269. if (!this._texture) {
  50270. this.loadTexture();
  50271. }
  50272. };
  50273. /**
  50274. * Parses a color grading texture serialized by Babylon.
  50275. * @param parsedTexture The texture information being parsedTexture
  50276. * @param scene The scene to load the texture in
  50277. * @param rootUrl The root url of the data assets to load
  50278. * @return A color gradind texture
  50279. */
  50280. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50281. var texture = null;
  50282. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50283. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  50284. texture.name = parsedTexture.name;
  50285. texture.level = parsedTexture.level;
  50286. }
  50287. return texture;
  50288. };
  50289. /**
  50290. * Serializes the LUT texture to json format.
  50291. */
  50292. ColorGradingTexture.prototype.serialize = function () {
  50293. if (!this.name) {
  50294. return null;
  50295. }
  50296. var serializationObject = {};
  50297. serializationObject.name = this.name;
  50298. serializationObject.level = this.level;
  50299. return serializationObject;
  50300. };
  50301. /**
  50302. * Empty line regex stored for GC.
  50303. */
  50304. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  50305. return ColorGradingTexture;
  50306. })(BABYLON.BaseTexture);
  50307. BABYLON.ColorGradingTexture = ColorGradingTexture;
  50308. })(BABYLON || (BABYLON = {}));
  50309. var BABYLON;
  50310. (function (BABYLON) {
  50311. var PBRMaterialDefines = (function (_super) {
  50312. __extends(PBRMaterialDefines, _super);
  50313. function PBRMaterialDefines() {
  50314. _super.call(this);
  50315. this.ALBEDO = false;
  50316. this.AMBIENT = false;
  50317. this.OPACITY = false;
  50318. this.OPACITYRGB = false;
  50319. this.REFLECTION = false;
  50320. this.EMISSIVE = false;
  50321. this.REFLECTIVITY = false;
  50322. this.BUMP = false;
  50323. this.PARALLAX = false;
  50324. this.PARALLAXOCCLUSION = false;
  50325. this.SPECULAROVERALPHA = false;
  50326. this.CLIPPLANE = false;
  50327. this.ALPHATEST = false;
  50328. this.ALPHAFROMALBEDO = false;
  50329. this.POINTSIZE = false;
  50330. this.FOG = false;
  50331. this.SPECULARTERM = false;
  50332. this.OPACITYFRESNEL = false;
  50333. this.EMISSIVEFRESNEL = false;
  50334. this.FRESNEL = false;
  50335. this.NORMAL = false;
  50336. this.UV1 = false;
  50337. this.UV2 = false;
  50338. this.VERTEXCOLOR = false;
  50339. this.VERTEXALPHA = false;
  50340. this.NUM_BONE_INFLUENCERS = 0;
  50341. this.BonesPerMesh = 0;
  50342. this.INSTANCES = false;
  50343. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  50344. this.MICROSURFACEAUTOMATIC = false;
  50345. this.EMISSIVEASILLUMINATION = false;
  50346. this.LINKEMISSIVEWITHALBEDO = false;
  50347. this.LIGHTMAP = false;
  50348. this.USELIGHTMAPASSHADOWMAP = false;
  50349. this.REFLECTIONMAP_3D = false;
  50350. this.REFLECTIONMAP_SPHERICAL = false;
  50351. this.REFLECTIONMAP_PLANAR = false;
  50352. this.REFLECTIONMAP_CUBIC = false;
  50353. this.REFLECTIONMAP_PROJECTION = false;
  50354. this.REFLECTIONMAP_SKYBOX = false;
  50355. this.REFLECTIONMAP_EXPLICIT = false;
  50356. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  50357. this.INVERTCUBICMAP = false;
  50358. this.LOGARITHMICDEPTH = false;
  50359. this.CAMERATONEMAP = false;
  50360. this.CAMERACONTRAST = false;
  50361. this.CAMERACOLORGRADING = false;
  50362. this.OVERLOADEDVALUES = false;
  50363. this.OVERLOADEDSHADOWVALUES = false;
  50364. this.USESPHERICALFROMREFLECTIONMAP = false;
  50365. this.REFRACTION = false;
  50366. this.REFRACTIONMAP_3D = false;
  50367. this.LINKREFRACTIONTOTRANSPARENCY = false;
  50368. this.REFRACTIONMAPINLINEARSPACE = false;
  50369. this.LODBASEDMICROSFURACE = false;
  50370. this.USEPHYSICALLIGHTFALLOFF = false;
  50371. this.RADIANCEOVERALPHA = false;
  50372. this.USEPMREMREFLECTION = false;
  50373. this.USEPMREMREFRACTION = false;
  50374. this.OPENGLNORMALMAP = false;
  50375. this.rebuild();
  50376. }
  50377. return PBRMaterialDefines;
  50378. })(BABYLON.MaterialDefines);
  50379. /**
  50380. * The Physically based material of BJS.
  50381. *
  50382. * This offers the main features of a standard PBR material.
  50383. * For more information, please refer to the documentation :
  50384. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  50385. */
  50386. var PBRMaterial = (function (_super) {
  50387. __extends(PBRMaterial, _super);
  50388. /**
  50389. * Instantiates a new PBRMaterial instance.
  50390. *
  50391. * @param name The material name
  50392. * @param scene The scene the material will be use in.
  50393. */
  50394. function PBRMaterial(name, scene) {
  50395. var _this = this;
  50396. _super.call(this, name, scene);
  50397. /**
  50398. * Intensity of the direct lights e.g. the four lights available in your scene.
  50399. * This impacts both the direct diffuse and specular highlights.
  50400. */
  50401. this.directIntensity = 1.0;
  50402. /**
  50403. * Intensity of the emissive part of the material.
  50404. * This helps controlling the emissive effect without modifying the emissive color.
  50405. */
  50406. this.emissiveIntensity = 1.0;
  50407. /**
  50408. * Intensity of the environment e.g. how much the environment will light the object
  50409. * either through harmonics for rough material or through the refelction for shiny ones.
  50410. */
  50411. this.environmentIntensity = 1.0;
  50412. /**
  50413. * This is a special control allowing the reduction of the specular highlights coming from the
  50414. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  50415. */
  50416. this.specularIntensity = 1.0;
  50417. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  50418. /**
  50419. * Debug Control allowing disabling the bump map on this material.
  50420. */
  50421. this.disableBumpMap = false;
  50422. /**
  50423. * Debug Control helping enforcing or dropping the darkness of shadows.
  50424. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  50425. */
  50426. this.overloadedShadowIntensity = 1.0;
  50427. /**
  50428. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  50429. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  50430. */
  50431. this.overloadedShadeIntensity = 1.0;
  50432. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  50433. /**
  50434. * The camera exposure used on this material.
  50435. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  50436. * This corresponds to a photographic exposure.
  50437. */
  50438. this.cameraExposure = 1.0;
  50439. /**
  50440. * The camera contrast used on this material.
  50441. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  50442. */
  50443. this.cameraContrast = 1.0;
  50444. /**
  50445. * Color Grading 2D Lookup Texture.
  50446. * This allows special effects like sepia, black and white to sixties rendering style.
  50447. */
  50448. this.cameraColorGradingTexture = null;
  50449. this._cameraColorGradingScaleOffset = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  50450. this._cameraColorGradingInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  50451. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  50452. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  50453. /**
  50454. * Debug Control allowing to overload the ambient color.
  50455. * This as to be use with the overloadedAmbientIntensity parameter.
  50456. */
  50457. this.overloadedAmbient = BABYLON.Color3.White();
  50458. /**
  50459. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  50460. */
  50461. this.overloadedAmbientIntensity = 0.0;
  50462. /**
  50463. * Debug Control allowing to overload the albedo color.
  50464. * This as to be use with the overloadedAlbedoIntensity parameter.
  50465. */
  50466. this.overloadedAlbedo = BABYLON.Color3.White();
  50467. /**
  50468. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  50469. */
  50470. this.overloadedAlbedoIntensity = 0.0;
  50471. /**
  50472. * Debug Control allowing to overload the reflectivity color.
  50473. * This as to be use with the overloadedReflectivityIntensity parameter.
  50474. */
  50475. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  50476. /**
  50477. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  50478. */
  50479. this.overloadedReflectivityIntensity = 0.0;
  50480. /**
  50481. * Debug Control allowing to overload the emissive color.
  50482. * This as to be use with the overloadedEmissiveIntensity parameter.
  50483. */
  50484. this.overloadedEmissive = BABYLON.Color3.White();
  50485. /**
  50486. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  50487. */
  50488. this.overloadedEmissiveIntensity = 0.0;
  50489. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  50490. /**
  50491. * Debug Control allowing to overload the reflection color.
  50492. * This as to be use with the overloadedReflectionIntensity parameter.
  50493. */
  50494. this.overloadedReflection = BABYLON.Color3.White();
  50495. /**
  50496. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  50497. */
  50498. this.overloadedReflectionIntensity = 0.0;
  50499. /**
  50500. * Debug Control allowing to overload the microsurface.
  50501. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  50502. */
  50503. this.overloadedMicroSurface = 0.0;
  50504. /**
  50505. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  50506. */
  50507. this.overloadedMicroSurfaceIntensity = 0.0;
  50508. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  50509. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  50510. /**
  50511. * AKA Diffuse Color in other nomenclature.
  50512. */
  50513. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  50514. /**
  50515. * AKA Specular Color in other nomenclature.
  50516. */
  50517. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  50518. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  50519. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  50520. /**
  50521. * AKA Glossiness in other nomenclature.
  50522. */
  50523. this.microSurface = 0.9;
  50524. /**
  50525. * source material index of refraction (IOR)' / 'destination material IOR.
  50526. */
  50527. this.indexOfRefraction = 0.66;
  50528. /**
  50529. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  50530. */
  50531. this.invertRefractionY = false;
  50532. /**
  50533. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  50534. * Materials half opaque for instance using refraction could benefit from this control.
  50535. */
  50536. this.linkRefractionWithTransparency = false;
  50537. /**
  50538. * The emissive and albedo are linked to never be more than one (Energy conservation).
  50539. */
  50540. this.linkEmissiveWithAlbedo = false;
  50541. this.useLightmapAsShadowmap = false;
  50542. /**
  50543. * In this mode, the emissive informtaion will always be added to the lighting once.
  50544. * A light for instance can be thought as emissive.
  50545. */
  50546. this.useEmissiveAsIllumination = false;
  50547. /**
  50548. * Secifies that the alpha is coming form the albedo channel alpha channel.
  50549. */
  50550. this.useAlphaFromAlbedoTexture = false;
  50551. /**
  50552. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  50553. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  50554. */
  50555. this.useSpecularOverAlpha = true;
  50556. /**
  50557. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  50558. */
  50559. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  50560. /**
  50561. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  50562. * The material will try to infer what glossiness each pixel should be.
  50563. */
  50564. this.useAutoMicroSurfaceFromReflectivityMap = false;
  50565. /**
  50566. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  50567. * the creation of the material.
  50568. */
  50569. this.useScalarInLinearSpace = false;
  50570. /**
  50571. * BJS is using an harcoded light falloff based on a manually sets up range.
  50572. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  50573. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  50574. */
  50575. this.usePhysicalLightFalloff = true;
  50576. /**
  50577. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  50578. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  50579. */
  50580. this.useRadianceOverAlpha = true;
  50581. /**
  50582. * Allows using the bump map in parallax mode.
  50583. */
  50584. this.useParallax = false;
  50585. /**
  50586. * Allows using the bump map in parallax occlusion mode.
  50587. */
  50588. this.useParallaxOcclusion = false;
  50589. /**
  50590. * Controls the scale bias of the parallax mode.
  50591. */
  50592. this.parallaxScaleBias = 0.05;
  50593. /**
  50594. * If sets to true, disables all the lights affecting the material.
  50595. */
  50596. this.disableLighting = false;
  50597. /**
  50598. * Number of Simultaneous lights allowed on the material.
  50599. */
  50600. this.maxSimultaneousLights = 4;
  50601. /**
  50602. * If sets to true, normal map will be considered following OpenGL convention.
  50603. */
  50604. this.useOpenGLNormalMap = false;
  50605. this._renderTargets = new BABYLON.SmartArray(16);
  50606. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  50607. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  50608. this._tempColor = new BABYLON.Color3();
  50609. this._defines = new PBRMaterialDefines();
  50610. this._cachedDefines = new PBRMaterialDefines();
  50611. this._myScene = null;
  50612. this._myShadowGenerator = null;
  50613. this._cachedDefines.BonesPerMesh = -1;
  50614. this.getRenderTargetTextures = function () {
  50615. _this._renderTargets.reset();
  50616. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  50617. _this._renderTargets.push(_this.reflectionTexture);
  50618. }
  50619. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  50620. _this._renderTargets.push(_this.refractionTexture);
  50621. }
  50622. return _this._renderTargets;
  50623. };
  50624. }
  50625. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  50626. get: function () {
  50627. return this._useLogarithmicDepth;
  50628. },
  50629. set: function (value) {
  50630. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  50631. },
  50632. enumerable: true,
  50633. configurable: true
  50634. });
  50635. PBRMaterial.prototype.needAlphaBlending = function () {
  50636. if (this.linkRefractionWithTransparency) {
  50637. return false;
  50638. }
  50639. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  50640. };
  50641. PBRMaterial.prototype.needAlphaTesting = function () {
  50642. if (this.linkRefractionWithTransparency) {
  50643. return false;
  50644. }
  50645. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  50646. };
  50647. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  50648. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  50649. };
  50650. PBRMaterial.prototype.getAlphaTestTexture = function () {
  50651. return this.albedoTexture;
  50652. };
  50653. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  50654. if (!mesh) {
  50655. return true;
  50656. }
  50657. if (this._defines.INSTANCES !== useInstances) {
  50658. return false;
  50659. }
  50660. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  50661. return true;
  50662. }
  50663. return false;
  50664. };
  50665. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  50666. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  50667. };
  50668. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  50669. if (!useScalarInLinear) {
  50670. color.toLinearSpaceToRef(ref);
  50671. }
  50672. else {
  50673. ref.r = color.r;
  50674. ref.g = color.g;
  50675. ref.b = color.b;
  50676. }
  50677. };
  50678. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  50679. var lightIndex = 0;
  50680. var depthValuesAlreadySet = false;
  50681. for (var index = 0; index < scene.lights.length; index++) {
  50682. var light = scene.lights[index];
  50683. if (!light.isEnabled()) {
  50684. continue;
  50685. }
  50686. if (!light.canAffectMesh(mesh)) {
  50687. continue;
  50688. }
  50689. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  50690. // GAMMA CORRECTION.
  50691. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  50692. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  50693. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  50694. if (defines["SPECULARTERM"]) {
  50695. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  50696. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  50697. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  50698. }
  50699. // Shadows
  50700. if (scene.shadowsEnabled) {
  50701. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  50702. }
  50703. lightIndex++;
  50704. if (lightIndex === maxSimultaneousLights)
  50705. break;
  50706. }
  50707. };
  50708. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  50709. if (this.checkReadyOnlyOnce) {
  50710. if (this._wasPreviouslyReady) {
  50711. return true;
  50712. }
  50713. }
  50714. var scene = this.getScene();
  50715. if (!this.checkReadyOnEveryCall) {
  50716. if (this._renderId === scene.getRenderId()) {
  50717. if (this._checkCache(scene, mesh, useInstances)) {
  50718. return true;
  50719. }
  50720. }
  50721. }
  50722. var engine = scene.getEngine();
  50723. var needNormals = false;
  50724. var needUVs = false;
  50725. this._defines.reset();
  50726. if (scene.texturesEnabled) {
  50727. // Textures
  50728. if (scene.texturesEnabled) {
  50729. if (scene.getEngine().getCaps().textureLOD) {
  50730. this._defines.LODBASEDMICROSFURACE = true;
  50731. }
  50732. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  50733. if (!this.albedoTexture.isReady()) {
  50734. return false;
  50735. }
  50736. else {
  50737. needUVs = true;
  50738. this._defines.ALBEDO = true;
  50739. }
  50740. }
  50741. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  50742. if (!this.ambientTexture.isReady()) {
  50743. return false;
  50744. }
  50745. else {
  50746. needUVs = true;
  50747. this._defines.AMBIENT = true;
  50748. }
  50749. }
  50750. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  50751. if (!this.opacityTexture.isReady()) {
  50752. return false;
  50753. }
  50754. else {
  50755. needUVs = true;
  50756. this._defines.OPACITY = true;
  50757. if (this.opacityTexture.getAlphaFromRGB) {
  50758. this._defines.OPACITYRGB = true;
  50759. }
  50760. }
  50761. }
  50762. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  50763. if (!this.reflectionTexture.isReady()) {
  50764. return false;
  50765. }
  50766. else {
  50767. needNormals = true;
  50768. this._defines.REFLECTION = true;
  50769. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  50770. this._defines.INVERTCUBICMAP = true;
  50771. }
  50772. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  50773. switch (this.reflectionTexture.coordinatesMode) {
  50774. case BABYLON.Texture.CUBIC_MODE:
  50775. case BABYLON.Texture.INVCUBIC_MODE:
  50776. this._defines.REFLECTIONMAP_CUBIC = true;
  50777. break;
  50778. case BABYLON.Texture.EXPLICIT_MODE:
  50779. this._defines.REFLECTIONMAP_EXPLICIT = true;
  50780. break;
  50781. case BABYLON.Texture.PLANAR_MODE:
  50782. this._defines.REFLECTIONMAP_PLANAR = true;
  50783. break;
  50784. case BABYLON.Texture.PROJECTION_MODE:
  50785. this._defines.REFLECTIONMAP_PROJECTION = true;
  50786. break;
  50787. case BABYLON.Texture.SKYBOX_MODE:
  50788. this._defines.REFLECTIONMAP_SKYBOX = true;
  50789. break;
  50790. case BABYLON.Texture.SPHERICAL_MODE:
  50791. this._defines.REFLECTIONMAP_SPHERICAL = true;
  50792. break;
  50793. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  50794. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  50795. break;
  50796. }
  50797. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  50798. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  50799. needNormals = true;
  50800. if (this.reflectionTexture.isPMREM) {
  50801. this._defines.USEPMREMREFLECTION = true;
  50802. }
  50803. }
  50804. }
  50805. }
  50806. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  50807. if (!this.lightmapTexture.isReady()) {
  50808. return false;
  50809. }
  50810. else {
  50811. needUVs = true;
  50812. this._defines.LIGHTMAP = true;
  50813. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  50814. }
  50815. }
  50816. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  50817. if (!this.emissiveTexture.isReady()) {
  50818. return false;
  50819. }
  50820. else {
  50821. needUVs = true;
  50822. this._defines.EMISSIVE = true;
  50823. }
  50824. }
  50825. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  50826. if (!this.reflectivityTexture.isReady()) {
  50827. return false;
  50828. }
  50829. else {
  50830. needUVs = true;
  50831. this._defines.REFLECTIVITY = true;
  50832. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  50833. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  50834. }
  50835. }
  50836. }
  50837. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  50838. if (!this.bumpTexture.isReady()) {
  50839. return false;
  50840. }
  50841. else {
  50842. needUVs = true;
  50843. this._defines.BUMP = true;
  50844. if (this.useParallax) {
  50845. this._defines.PARALLAX = true;
  50846. if (this.useParallaxOcclusion) {
  50847. this._defines.PARALLAXOCCLUSION = true;
  50848. }
  50849. }
  50850. if (this.useOpenGLNormalMap) {
  50851. this._defines.OPENGLNORMALMAP = true;
  50852. }
  50853. }
  50854. }
  50855. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  50856. if (!this.refractionTexture.isReady()) {
  50857. return false;
  50858. }
  50859. else {
  50860. needUVs = true;
  50861. this._defines.REFRACTION = true;
  50862. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  50863. if (this.linkRefractionWithTransparency) {
  50864. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  50865. }
  50866. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  50867. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  50868. if (this.refractionTexture.isPMREM) {
  50869. this._defines.USEPMREMREFRACTION = true;
  50870. }
  50871. }
  50872. }
  50873. }
  50874. if (this.cameraColorGradingTexture) {
  50875. if (!this.cameraColorGradingTexture.isReady()) {
  50876. return false;
  50877. }
  50878. else {
  50879. this._defines.CAMERACOLORGRADING = true;
  50880. }
  50881. }
  50882. }
  50883. // Effect
  50884. if (scene.clipPlane) {
  50885. this._defines.CLIPPLANE = true;
  50886. }
  50887. if (engine.getAlphaTesting()) {
  50888. this._defines.ALPHATEST = true;
  50889. }
  50890. if (this._shouldUseAlphaFromAlbedoTexture()) {
  50891. this._defines.ALPHAFROMALBEDO = true;
  50892. }
  50893. if (this.useEmissiveAsIllumination) {
  50894. this._defines.EMISSIVEASILLUMINATION = true;
  50895. }
  50896. if (this.linkEmissiveWithAlbedo) {
  50897. this._defines.LINKEMISSIVEWITHALBEDO = true;
  50898. }
  50899. if (this.useLogarithmicDepth) {
  50900. this._defines.LOGARITHMICDEPTH = true;
  50901. }
  50902. if (this.cameraContrast != 1) {
  50903. this._defines.CAMERACONTRAST = true;
  50904. }
  50905. if (this.cameraExposure != 1) {
  50906. this._defines.CAMERATONEMAP = true;
  50907. }
  50908. if (this.overloadedShadeIntensity != 1 ||
  50909. this.overloadedShadowIntensity != 1) {
  50910. this._defines.OVERLOADEDSHADOWVALUES = true;
  50911. }
  50912. if (this.overloadedMicroSurfaceIntensity > 0 ||
  50913. this.overloadedEmissiveIntensity > 0 ||
  50914. this.overloadedReflectivityIntensity > 0 ||
  50915. this.overloadedAlbedoIntensity > 0 ||
  50916. this.overloadedAmbientIntensity > 0 ||
  50917. this.overloadedReflectionIntensity > 0) {
  50918. this._defines.OVERLOADEDVALUES = true;
  50919. }
  50920. // Point size
  50921. if (this.pointsCloud || scene.forcePointsCloud) {
  50922. this._defines.POINTSIZE = true;
  50923. }
  50924. // Fog
  50925. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50926. this._defines.FOG = true;
  50927. }
  50928. if (scene.lightsEnabled && !this.disableLighting) {
  50929. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  50930. }
  50931. if (BABYLON.StandardMaterial.FresnelEnabled) {
  50932. // Fresnel
  50933. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  50934. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  50935. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  50936. this._defines.OPACITYFRESNEL = true;
  50937. }
  50938. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  50939. this._defines.EMISSIVEFRESNEL = true;
  50940. }
  50941. needNormals = true;
  50942. this._defines.FRESNEL = true;
  50943. }
  50944. }
  50945. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  50946. this._defines.SPECULAROVERALPHA = true;
  50947. }
  50948. if (this.usePhysicalLightFalloff) {
  50949. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  50950. }
  50951. if (this.useRadianceOverAlpha) {
  50952. this._defines.RADIANCEOVERALPHA = true;
  50953. }
  50954. // Attribs
  50955. if (mesh) {
  50956. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50957. this._defines.NORMAL = true;
  50958. }
  50959. if (needUVs) {
  50960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50961. this._defines.UV1 = true;
  50962. }
  50963. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50964. this._defines.UV2 = true;
  50965. }
  50966. }
  50967. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  50968. this._defines.VERTEXCOLOR = true;
  50969. if (mesh.hasVertexAlpha) {
  50970. this._defines.VERTEXALPHA = true;
  50971. }
  50972. }
  50973. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50974. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  50975. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  50976. }
  50977. // Instances
  50978. if (useInstances) {
  50979. this._defines.INSTANCES = true;
  50980. }
  50981. }
  50982. // Get correct effect
  50983. if (!this._defines.isEqual(this._cachedDefines)) {
  50984. this._defines.cloneTo(this._cachedDefines);
  50985. scene.resetCachedMaterial();
  50986. // Fallbacks
  50987. var fallbacks = new BABYLON.EffectFallbacks();
  50988. if (this._defines.REFLECTION) {
  50989. fallbacks.addFallback(0, "REFLECTION");
  50990. }
  50991. if (this._defines.REFRACTION) {
  50992. fallbacks.addFallback(0, "REFRACTION");
  50993. }
  50994. if (this._defines.REFLECTIVITY) {
  50995. fallbacks.addFallback(0, "REFLECTIVITY");
  50996. }
  50997. if (this._defines.BUMP) {
  50998. fallbacks.addFallback(0, "BUMP");
  50999. }
  51000. if (this._defines.PARALLAX) {
  51001. fallbacks.addFallback(1, "PARALLAX");
  51002. }
  51003. if (this._defines.PARALLAXOCCLUSION) {
  51004. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  51005. }
  51006. if (this._defines.SPECULAROVERALPHA) {
  51007. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  51008. }
  51009. if (this._defines.FOG) {
  51010. fallbacks.addFallback(1, "FOG");
  51011. }
  51012. if (this._defines.POINTSIZE) {
  51013. fallbacks.addFallback(0, "POINTSIZE");
  51014. }
  51015. if (this._defines.LOGARITHMICDEPTH) {
  51016. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  51017. }
  51018. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  51019. if (this._defines.SPECULARTERM) {
  51020. fallbacks.addFallback(0, "SPECULARTERM");
  51021. }
  51022. if (this._defines.OPACITYFRESNEL) {
  51023. fallbacks.addFallback(1, "OPACITYFRESNEL");
  51024. }
  51025. if (this._defines.EMISSIVEFRESNEL) {
  51026. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  51027. }
  51028. if (this._defines.FRESNEL) {
  51029. fallbacks.addFallback(3, "FRESNEL");
  51030. }
  51031. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  51032. fallbacks.addCPUSkinningFallback(0, mesh);
  51033. }
  51034. //Attributes
  51035. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51036. if (this._defines.NORMAL) {
  51037. attribs.push(BABYLON.VertexBuffer.NormalKind);
  51038. }
  51039. if (this._defines.UV1) {
  51040. attribs.push(BABYLON.VertexBuffer.UVKind);
  51041. }
  51042. if (this._defines.UV2) {
  51043. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51044. }
  51045. if (this._defines.VERTEXCOLOR) {
  51046. attribs.push(BABYLON.VertexBuffer.ColorKind);
  51047. }
  51048. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  51049. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  51050. // Legacy browser patch
  51051. var shaderName = "pbr";
  51052. if (!scene.getEngine().getCaps().standardDerivatives) {
  51053. shaderName = "legacypbr";
  51054. }
  51055. var join = this._defines.toString();
  51056. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  51057. "vFogInfos", "vFogColor", "pointSize",
  51058. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  51059. "mBones",
  51060. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  51061. "depthValues",
  51062. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  51063. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  51064. "logarithmicDepthConstant",
  51065. "vSphericalX", "vSphericalY", "vSphericalZ",
  51066. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  51067. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  51068. "vMicrosurfaceTextureLods",
  51069. "vCameraInfos", "vCameraColorGradingInfos", "vCameraColorGradingScaleOffset"
  51070. ];
  51071. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  51072. "cameraColorGrading2DSampler"];
  51073. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  51074. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  51075. }
  51076. if (!this._effect.isReady()) {
  51077. return false;
  51078. }
  51079. this._renderId = scene.getRenderId();
  51080. this._wasPreviouslyReady = true;
  51081. if (mesh) {
  51082. if (!mesh._materialDefines) {
  51083. mesh._materialDefines = new PBRMaterialDefines();
  51084. }
  51085. this._defines.cloneTo(mesh._materialDefines);
  51086. }
  51087. return true;
  51088. };
  51089. PBRMaterial.prototype.unbind = function () {
  51090. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  51091. this._effect.setTexture("reflection2DSampler", null);
  51092. }
  51093. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  51094. this._effect.setTexture("refraction2DSampler", null);
  51095. }
  51096. _super.prototype.unbind.call(this);
  51097. };
  51098. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  51099. this._effect.setMatrix("world", world);
  51100. };
  51101. PBRMaterial.prototype.bind = function (world, mesh) {
  51102. this._myScene = this.getScene();
  51103. // Matrices
  51104. this.bindOnlyWorldMatrix(world);
  51105. // Bones
  51106. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  51107. if (this._myScene.getCachedMaterial() !== this) {
  51108. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  51109. if (BABYLON.StandardMaterial.FresnelEnabled) {
  51110. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  51111. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  51112. }
  51113. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51114. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  51115. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  51116. }
  51117. }
  51118. // Textures
  51119. if (this._myScene.texturesEnabled) {
  51120. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51121. this._effect.setTexture("albedoSampler", this.albedoTexture);
  51122. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  51123. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  51124. }
  51125. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  51126. this._effect.setTexture("ambientSampler", this.ambientTexture);
  51127. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  51128. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  51129. }
  51130. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  51131. this._effect.setTexture("opacitySampler", this.opacityTexture);
  51132. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  51133. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  51134. }
  51135. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  51136. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  51137. if (this.reflectionTexture.isCube) {
  51138. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  51139. }
  51140. else {
  51141. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  51142. }
  51143. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  51144. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  51145. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  51146. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  51147. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  51148. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  51149. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  51150. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  51151. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  51152. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  51153. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  51154. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  51155. }
  51156. }
  51157. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  51158. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  51159. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  51160. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  51161. }
  51162. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  51163. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  51164. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  51165. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  51166. }
  51167. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  51168. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  51169. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  51170. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  51171. }
  51172. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  51173. this._effect.setTexture("bumpSampler", this.bumpTexture);
  51174. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  51175. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  51176. }
  51177. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  51178. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  51179. var depth = 1.0;
  51180. if (this.refractionTexture.isCube) {
  51181. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  51182. }
  51183. else {
  51184. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  51185. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  51186. if (this.refractionTexture.depth) {
  51187. depth = this.refractionTexture.depth;
  51188. }
  51189. }
  51190. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  51191. }
  51192. if ((this.reflectionTexture || this.refractionTexture)) {
  51193. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  51194. }
  51195. if (this.cameraColorGradingTexture) {
  51196. this._effect.setTexture("cameraColorGrading2DSampler", this.cameraColorGradingTexture);
  51197. this._cameraColorGradingInfos.x = this.cameraColorGradingTexture.level; // Texture Level
  51198. this._cameraColorGradingInfos.y = this.cameraColorGradingTexture.getSize().height; // Texture Size example with 8
  51199. this._cameraColorGradingInfos.z = this._cameraColorGradingInfos.y - 1.0; // SizeMinusOne 8 - 1
  51200. this._cameraColorGradingInfos.w = 1 / this._cameraColorGradingInfos.y; // Space of 1 slice 1 / 8
  51201. this._effect.setFloat4("vCameraColorGradingInfos", this._cameraColorGradingInfos.x, this._cameraColorGradingInfos.y, this._cameraColorGradingInfos.z, this._cameraColorGradingInfos.w);
  51202. var slicePixelSizeU = this._cameraColorGradingInfos.w / this._cameraColorGradingInfos.y; // Space of 1 pixel in U direction, e.g. 1/64
  51203. var slicePixelSizeV = 1.0 / this._cameraColorGradingInfos.y; // Space of 1 pixel in V direction, e.g. 1/8
  51204. this._cameraColorGradingScaleOffset.x = this._cameraColorGradingInfos.z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  51205. this._cameraColorGradingScaleOffset.y = this._cameraColorGradingInfos.z /
  51206. this._cameraColorGradingInfos.y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  51207. this._cameraColorGradingScaleOffset.z = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  51208. this._cameraColorGradingScaleOffset.w = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  51209. this._effect.setFloat4("vCameraColorGradingScaleOffset", this._cameraColorGradingScaleOffset.x, this._cameraColorGradingScaleOffset.y, this._cameraColorGradingScaleOffset.z, this._cameraColorGradingScaleOffset.w);
  51210. }
  51211. }
  51212. // Clip plane
  51213. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  51214. // Point size
  51215. if (this.pointsCloud) {
  51216. this._effect.setFloat("pointSize", this.pointSize);
  51217. }
  51218. // Colors
  51219. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  51220. // GAMMA CORRECTION.
  51221. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  51222. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  51223. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  51224. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  51225. // GAMMA CORRECTION.
  51226. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  51227. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  51228. // GAMMA CORRECTION.
  51229. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  51230. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  51231. }
  51232. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  51233. // GAMMA CORRECTION.
  51234. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  51235. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  51236. // Lights
  51237. if (this._myScene.lightsEnabled && !this.disableLighting) {
  51238. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  51239. }
  51240. // View
  51241. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  51242. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  51243. }
  51244. // Fog
  51245. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  51246. this._lightingInfos.x = this.directIntensity;
  51247. this._lightingInfos.y = this.emissiveIntensity;
  51248. this._lightingInfos.z = this.environmentIntensity;
  51249. this._lightingInfos.w = this.specularIntensity;
  51250. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  51251. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  51252. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  51253. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  51254. this._cameraInfos.x = this.cameraExposure;
  51255. this._cameraInfos.y = this.cameraContrast;
  51256. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  51257. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  51258. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  51259. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  51260. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  51261. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  51262. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  51263. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  51264. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  51265. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  51266. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  51267. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  51268. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  51269. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  51270. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  51271. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  51272. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  51273. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  51274. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  51275. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  51276. // Log. depth
  51277. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  51278. }
  51279. _super.prototype.bind.call(this, world, mesh);
  51280. this._myScene = null;
  51281. };
  51282. PBRMaterial.prototype.getAnimatables = function () {
  51283. var results = [];
  51284. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  51285. results.push(this.albedoTexture);
  51286. }
  51287. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  51288. results.push(this.ambientTexture);
  51289. }
  51290. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  51291. results.push(this.opacityTexture);
  51292. }
  51293. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  51294. results.push(this.reflectionTexture);
  51295. }
  51296. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  51297. results.push(this.emissiveTexture);
  51298. }
  51299. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  51300. results.push(this.reflectivityTexture);
  51301. }
  51302. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  51303. results.push(this.bumpTexture);
  51304. }
  51305. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  51306. results.push(this.lightmapTexture);
  51307. }
  51308. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  51309. results.push(this.refractionTexture);
  51310. }
  51311. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  51312. results.push(this.cameraColorGradingTexture);
  51313. }
  51314. return results;
  51315. };
  51316. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51317. if (forceDisposeTextures) {
  51318. if (this.albedoTexture) {
  51319. this.albedoTexture.dispose();
  51320. }
  51321. if (this.ambientTexture) {
  51322. this.ambientTexture.dispose();
  51323. }
  51324. if (this.opacityTexture) {
  51325. this.opacityTexture.dispose();
  51326. }
  51327. if (this.reflectionTexture) {
  51328. this.reflectionTexture.dispose();
  51329. }
  51330. if (this.emissiveTexture) {
  51331. this.emissiveTexture.dispose();
  51332. }
  51333. if (this.reflectivityTexture) {
  51334. this.reflectivityTexture.dispose();
  51335. }
  51336. if (this.bumpTexture) {
  51337. this.bumpTexture.dispose();
  51338. }
  51339. if (this.lightmapTexture) {
  51340. this.lightmapTexture.dispose();
  51341. }
  51342. if (this.refractionTexture) {
  51343. this.refractionTexture.dispose();
  51344. }
  51345. if (this.cameraColorGradingTexture) {
  51346. this.cameraColorGradingTexture.dispose();
  51347. }
  51348. }
  51349. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51350. };
  51351. PBRMaterial.prototype.clone = function (name) {
  51352. var _this = this;
  51353. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  51354. };
  51355. PBRMaterial.prototype.serialize = function () {
  51356. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51357. serializationObject.customType = "BABYLON.PBRMaterial";
  51358. return serializationObject;
  51359. };
  51360. // Statics
  51361. PBRMaterial.Parse = function (source, scene, rootUrl) {
  51362. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  51363. };
  51364. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  51365. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  51366. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  51367. PBRMaterial._scaledReflection = new BABYLON.Color3();
  51368. __decorate([
  51369. BABYLON.serialize()
  51370. ], PBRMaterial.prototype, "directIntensity", void 0);
  51371. __decorate([
  51372. BABYLON.serialize()
  51373. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  51374. __decorate([
  51375. BABYLON.serialize()
  51376. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  51377. __decorate([
  51378. BABYLON.serialize()
  51379. ], PBRMaterial.prototype, "specularIntensity", void 0);
  51380. __decorate([
  51381. BABYLON.serialize()
  51382. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  51383. __decorate([
  51384. BABYLON.serialize()
  51385. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  51386. __decorate([
  51387. BABYLON.serialize()
  51388. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  51389. __decorate([
  51390. BABYLON.serialize()
  51391. ], PBRMaterial.prototype, "cameraExposure", void 0);
  51392. __decorate([
  51393. BABYLON.serialize()
  51394. ], PBRMaterial.prototype, "cameraContrast", void 0);
  51395. __decorate([
  51396. BABYLON.serializeAsTexture()
  51397. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  51398. __decorate([
  51399. BABYLON.serializeAsColor3()
  51400. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  51401. __decorate([
  51402. BABYLON.serialize()
  51403. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  51404. __decorate([
  51405. BABYLON.serializeAsColor3()
  51406. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  51407. __decorate([
  51408. BABYLON.serialize()
  51409. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  51410. __decorate([
  51411. BABYLON.serializeAsColor3()
  51412. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  51413. __decorate([
  51414. BABYLON.serialize()
  51415. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  51416. __decorate([
  51417. BABYLON.serializeAsColor3()
  51418. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  51419. __decorate([
  51420. BABYLON.serialize()
  51421. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  51422. __decorate([
  51423. BABYLON.serializeAsColor3()
  51424. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  51425. __decorate([
  51426. BABYLON.serialize()
  51427. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  51428. __decorate([
  51429. BABYLON.serialize()
  51430. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  51431. __decorate([
  51432. BABYLON.serialize()
  51433. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  51434. __decorate([
  51435. BABYLON.serializeAsTexture()
  51436. ], PBRMaterial.prototype, "albedoTexture", void 0);
  51437. __decorate([
  51438. BABYLON.serializeAsTexture()
  51439. ], PBRMaterial.prototype, "ambientTexture", void 0);
  51440. __decorate([
  51441. BABYLON.serializeAsTexture()
  51442. ], PBRMaterial.prototype, "opacityTexture", void 0);
  51443. __decorate([
  51444. BABYLON.serializeAsTexture()
  51445. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  51446. __decorate([
  51447. BABYLON.serializeAsTexture()
  51448. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  51449. __decorate([
  51450. BABYLON.serializeAsTexture()
  51451. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  51452. __decorate([
  51453. BABYLON.serializeAsTexture()
  51454. ], PBRMaterial.prototype, "bumpTexture", void 0);
  51455. __decorate([
  51456. BABYLON.serializeAsTexture()
  51457. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  51458. __decorate([
  51459. BABYLON.serializeAsTexture()
  51460. ], PBRMaterial.prototype, "refractionTexture", void 0);
  51461. __decorate([
  51462. BABYLON.serializeAsColor3("ambient")
  51463. ], PBRMaterial.prototype, "ambientColor", void 0);
  51464. __decorate([
  51465. BABYLON.serializeAsColor3("albedo")
  51466. ], PBRMaterial.prototype, "albedoColor", void 0);
  51467. __decorate([
  51468. BABYLON.serializeAsColor3("reflectivity")
  51469. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  51470. __decorate([
  51471. BABYLON.serializeAsColor3("reflection")
  51472. ], PBRMaterial.prototype, "reflectionColor", void 0);
  51473. __decorate([
  51474. BABYLON.serializeAsColor3("emissive")
  51475. ], PBRMaterial.prototype, "emissiveColor", void 0);
  51476. __decorate([
  51477. BABYLON.serialize()
  51478. ], PBRMaterial.prototype, "microSurface", void 0);
  51479. __decorate([
  51480. BABYLON.serialize()
  51481. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  51482. __decorate([
  51483. BABYLON.serialize()
  51484. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  51485. __decorate([
  51486. BABYLON.serializeAsFresnelParameters()
  51487. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  51488. __decorate([
  51489. BABYLON.serializeAsFresnelParameters()
  51490. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  51491. __decorate([
  51492. BABYLON.serialize()
  51493. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  51494. __decorate([
  51495. BABYLON.serialize()
  51496. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  51497. __decorate([
  51498. BABYLON.serialize()
  51499. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  51500. __decorate([
  51501. BABYLON.serialize()
  51502. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  51503. __decorate([
  51504. BABYLON.serialize()
  51505. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  51506. __decorate([
  51507. BABYLON.serialize()
  51508. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  51509. __decorate([
  51510. BABYLON.serialize()
  51511. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  51512. __decorate([
  51513. BABYLON.serialize()
  51514. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  51515. __decorate([
  51516. BABYLON.serialize()
  51517. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  51518. __decorate([
  51519. BABYLON.serialize()
  51520. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  51521. __decorate([
  51522. BABYLON.serialize()
  51523. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  51524. __decorate([
  51525. BABYLON.serialize()
  51526. ], PBRMaterial.prototype, "useParallax", void 0);
  51527. __decorate([
  51528. BABYLON.serialize()
  51529. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  51530. __decorate([
  51531. BABYLON.serialize()
  51532. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  51533. __decorate([
  51534. BABYLON.serialize()
  51535. ], PBRMaterial.prototype, "disableLighting", void 0);
  51536. __decorate([
  51537. BABYLON.serialize()
  51538. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  51539. __decorate([
  51540. BABYLON.serialize()
  51541. ], PBRMaterial.prototype, "useOpenGLNormalMap", void 0);
  51542. __decorate([
  51543. BABYLON.serialize()
  51544. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  51545. return PBRMaterial;
  51546. })(BABYLON.Material);
  51547. BABYLON.PBRMaterial = PBRMaterial;
  51548. })(BABYLON || (BABYLON = {}));
  51549. var BABYLON;
  51550. (function (BABYLON) {
  51551. var DebugLayer = (function () {
  51552. function DebugLayer(scene) {
  51553. var _this = this;
  51554. this._transformationMatrix = BABYLON.Matrix.Identity();
  51555. this._enabled = false;
  51556. this._labelsEnabled = false;
  51557. this._displayStatistics = true;
  51558. this._displayTree = false;
  51559. this._displayLogs = false;
  51560. this._skeletonViewers = new Array();
  51561. this._identityMatrix = BABYLON.Matrix.Identity();
  51562. this.axisRatio = 0.02;
  51563. this.accentColor = "orange";
  51564. this._scene = scene;
  51565. this._syncPositions = function () {
  51566. var engine = _this._scene.getEngine();
  51567. var canvasRect = engine.getRenderingCanvasClientRect();
  51568. if (_this._showUI) {
  51569. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  51570. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  51571. _this._statsDiv.style.width = "400px";
  51572. _this._statsDiv.style.height = "auto";
  51573. _this._statsSubsetDiv.style.maxHeight = "240px";
  51574. _this._optionsDiv.style.left = "0px";
  51575. _this._optionsDiv.style.top = "10px";
  51576. _this._optionsDiv.style.width = "200px";
  51577. _this._optionsDiv.style.height = "auto";
  51578. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  51579. _this._logDiv.style.left = "0px";
  51580. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  51581. _this._logDiv.style.width = "600px";
  51582. _this._logDiv.style.height = "160px";
  51583. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  51584. _this._treeDiv.style.top = "10px";
  51585. _this._treeDiv.style.width = "300px";
  51586. _this._treeDiv.style.height = "auto";
  51587. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  51588. }
  51589. _this._globalDiv.style.left = canvasRect.left + "px";
  51590. _this._globalDiv.style.top = canvasRect.top + "px";
  51591. _this._drawingCanvas.style.left = "0px";
  51592. _this._drawingCanvas.style.top = "0px";
  51593. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  51594. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  51595. var devicePixelRatio = window.devicePixelRatio || 1;
  51596. var context = _this._drawingContext;
  51597. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  51598. context.mozBackingStorePixelRatio ||
  51599. context.msBackingStorePixelRatio ||
  51600. context.oBackingStorePixelRatio ||
  51601. context.backingStorePixelRatio || 1;
  51602. _this._ratio = devicePixelRatio / backingStoreRatio;
  51603. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  51604. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  51605. };
  51606. this._onCanvasClick = function (evt) {
  51607. _this._clickPosition = {
  51608. x: evt.clientX * _this._ratio,
  51609. y: evt.clientY * _this._ratio
  51610. };
  51611. };
  51612. this._syncUI = function () {
  51613. if (_this._showUI) {
  51614. if (_this._displayStatistics) {
  51615. _this._displayStats();
  51616. _this._statsDiv.style.display = "";
  51617. }
  51618. else {
  51619. _this._statsDiv.style.display = "none";
  51620. }
  51621. if (_this._displayLogs) {
  51622. _this._logDiv.style.display = "";
  51623. }
  51624. else {
  51625. _this._logDiv.style.display = "none";
  51626. }
  51627. if (_this._displayTree) {
  51628. _this._treeDiv.style.display = "";
  51629. if (_this._needToRefreshMeshesTree) {
  51630. _this._needToRefreshMeshesTree = false;
  51631. _this._refreshMeshesTreeContent();
  51632. }
  51633. }
  51634. else {
  51635. _this._treeDiv.style.display = "none";
  51636. }
  51637. }
  51638. };
  51639. this._syncData = function () {
  51640. if (_this._labelsEnabled || !_this._showUI) {
  51641. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  51642. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  51643. var engine = _this._scene.getEngine();
  51644. var viewport = _this._camera.viewport;
  51645. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  51646. // Meshes
  51647. var meshes = _this._camera.getActiveMeshes();
  51648. var index;
  51649. var projectedPosition;
  51650. for (index = 0; index < meshes.length; index++) {
  51651. var mesh = meshes.data[index];
  51652. var position = mesh.getBoundingInfo().boundingSphere.center;
  51653. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  51654. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  51655. _this._renderAxis(projectedPosition, mesh, globalViewport);
  51656. }
  51657. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  51658. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  51659. }
  51660. }
  51661. // Cameras
  51662. var cameras = _this._scene.cameras;
  51663. for (index = 0; index < cameras.length; index++) {
  51664. var camera = cameras[index];
  51665. if (camera === _this._camera) {
  51666. continue;
  51667. }
  51668. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  51669. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  51670. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  51671. _this._camera.detachControl(engine.getRenderingCanvas());
  51672. _this._camera = camera;
  51673. _this._camera.attachControl(engine.getRenderingCanvas());
  51674. }, function () { return "purple"; });
  51675. }
  51676. }
  51677. // Lights
  51678. var lights = _this._scene.lights;
  51679. for (index = 0; index < lights.length; index++) {
  51680. var light = lights[index];
  51681. if (light.position) {
  51682. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  51683. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  51684. _this._renderLabel(light.name, projectedPosition, -20, function () {
  51685. light.setEnabled(!light.isEnabled());
  51686. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  51687. }
  51688. }
  51689. }
  51690. }
  51691. _this._clickPosition = undefined;
  51692. };
  51693. }
  51694. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  51695. while (this._treeSubsetDiv.hasChildNodes()) {
  51696. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  51697. }
  51698. // Add meshes
  51699. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  51700. sortedArray.sort(function (a, b) {
  51701. if (a.name === b.name) {
  51702. return 0;
  51703. }
  51704. return (a.name > b.name) ? 1 : -1;
  51705. });
  51706. for (var index = 0; index < sortedArray.length; index++) {
  51707. var mesh = sortedArray[index];
  51708. if (!mesh.isEnabled()) {
  51709. continue;
  51710. }
  51711. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  51712. m.isVisible = element.checked;
  51713. }, mesh);
  51714. }
  51715. };
  51716. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  51717. this._drawingContext.beginPath();
  51718. this._drawingContext.moveTo(zero.x, zero.y);
  51719. this._drawingContext.lineTo(unit.x, unit.y);
  51720. this._drawingContext.strokeStyle = color;
  51721. this._drawingContext.lineWidth = 4;
  51722. this._drawingContext.stroke();
  51723. this._drawingContext.font = "normal 14px Segoe UI";
  51724. this._drawingContext.fillStyle = color;
  51725. this._drawingContext.fillText(label, unitText.x, unitText.y);
  51726. };
  51727. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  51728. var position = mesh.getBoundingInfo().boundingSphere.center;
  51729. var worldMatrix = mesh.getWorldMatrix();
  51730. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  51731. var unit = (unprojectedVector.subtract(position)).length();
  51732. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  51733. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  51734. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  51735. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  51736. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  51737. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  51738. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  51739. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  51740. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  51741. };
  51742. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  51743. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  51744. this._drawingContext.font = "normal 12px Segoe UI";
  51745. var textMetrics = this._drawingContext.measureText(text);
  51746. var centerX = projectedPosition.x - textMetrics.width / 2;
  51747. var centerY = projectedPosition.y;
  51748. var clientRect = this._drawingCanvas.getBoundingClientRect();
  51749. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  51750. onClick();
  51751. }
  51752. this._drawingContext.beginPath();
  51753. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  51754. this._drawingContext.fillStyle = getFillStyle();
  51755. this._drawingContext.globalAlpha = 0.5;
  51756. this._drawingContext.fill();
  51757. this._drawingContext.globalAlpha = 1.0;
  51758. this._drawingContext.strokeStyle = '#FFFFFF';
  51759. this._drawingContext.lineWidth = 1;
  51760. this._drawingContext.stroke();
  51761. this._drawingContext.fillStyle = "#FFFFFF";
  51762. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  51763. this._drawingContext.beginPath();
  51764. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  51765. this._drawingContext.fill();
  51766. }
  51767. };
  51768. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  51769. if (!this._clickPosition) {
  51770. return false;
  51771. }
  51772. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  51773. return false;
  51774. }
  51775. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  51776. return false;
  51777. }
  51778. return true;
  51779. };
  51780. DebugLayer.prototype.isVisible = function () {
  51781. return this._enabled;
  51782. };
  51783. DebugLayer.prototype.hide = function () {
  51784. if (!this._enabled) {
  51785. return;
  51786. }
  51787. this._enabled = false;
  51788. var engine = this._scene.getEngine();
  51789. this._scene.unregisterBeforeRender(this._syncData);
  51790. this._scene.unregisterAfterRender(this._syncUI);
  51791. this._rootElement.removeChild(this._globalDiv);
  51792. this._scene.forceShowBoundingBoxes = false;
  51793. this._scene.forceWireframe = false;
  51794. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  51795. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  51796. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  51797. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  51798. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  51799. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  51800. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  51801. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  51802. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  51803. this._scene.shadowsEnabled = true;
  51804. this._scene.particlesEnabled = true;
  51805. this._scene.postProcessesEnabled = true;
  51806. this._scene.collisionsEnabled = true;
  51807. this._scene.lightsEnabled = true;
  51808. this._scene.texturesEnabled = true;
  51809. this._scene.lensFlaresEnabled = true;
  51810. this._scene.proceduralTexturesEnabled = true;
  51811. this._scene.renderTargetsEnabled = true;
  51812. this._scene.probesEnabled = true;
  51813. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  51814. this._clearSkeletonViewers();
  51815. };
  51816. DebugLayer.prototype._clearSkeletonViewers = function () {
  51817. for (var index = 0; index < this._skeletonViewers.length; index++) {
  51818. this._skeletonViewers[index].dispose();
  51819. }
  51820. this._skeletonViewers = [];
  51821. };
  51822. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  51823. if (showUI === void 0) { showUI = true; }
  51824. if (camera === void 0) { camera = null; }
  51825. if (rootElement === void 0) { rootElement = null; }
  51826. if (this._enabled) {
  51827. return;
  51828. }
  51829. this._enabled = true;
  51830. if (camera) {
  51831. this._camera = camera;
  51832. }
  51833. else {
  51834. this._camera = this._scene.activeCamera;
  51835. }
  51836. this._showUI = showUI;
  51837. var engine = this._scene.getEngine();
  51838. this._globalDiv = document.createElement("div");
  51839. this._rootElement = rootElement || document.body;
  51840. this._rootElement.appendChild(this._globalDiv);
  51841. this._generateDOMelements();
  51842. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  51843. this._syncPositions();
  51844. this._scene.registerBeforeRender(this._syncData);
  51845. this._scene.registerAfterRender(this._syncUI);
  51846. };
  51847. DebugLayer.prototype._clearLabels = function () {
  51848. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  51849. for (var index = 0; index < this._scene.meshes.length; index++) {
  51850. var mesh = this._scene.meshes[index];
  51851. mesh.renderOverlay = false;
  51852. }
  51853. };
  51854. DebugLayer.prototype._generateheader = function (root, text) {
  51855. var header = document.createElement("div");
  51856. header.innerHTML = text + "&nbsp;";
  51857. header.style.textAlign = "right";
  51858. header.style.width = "100%";
  51859. header.style.color = "white";
  51860. header.style.backgroundColor = "Black";
  51861. header.style.padding = "5px 5px 4px 0px";
  51862. header.style.marginLeft = "-5px";
  51863. header.style.fontWeight = "bold";
  51864. root.appendChild(header);
  51865. };
  51866. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  51867. var label = document.createElement("label");
  51868. label.style.display = "inline";
  51869. label.innerHTML = title;
  51870. label.style.color = color;
  51871. root.appendChild(label);
  51872. root.appendChild(document.createElement("br"));
  51873. };
  51874. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  51875. if (tag === void 0) { tag = null; }
  51876. var label = document.createElement("label");
  51877. label.style.display = "inline";
  51878. var boundingBoxesCheckbox = document.createElement("input");
  51879. boundingBoxesCheckbox.type = "checkbox";
  51880. boundingBoxesCheckbox.checked = initialState;
  51881. boundingBoxesCheckbox.style.display = "inline";
  51882. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  51883. boundingBoxesCheckbox.style.verticalAlign = "sub";
  51884. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  51885. task(evt.target, tag);
  51886. });
  51887. label.appendChild(boundingBoxesCheckbox);
  51888. var container = document.createElement("span");
  51889. var leftPart = document.createElement("span");
  51890. var rightPart = document.createElement("span");
  51891. rightPart.style.cssFloat = "right";
  51892. leftPart.innerHTML = leftTitle;
  51893. rightPart.innerHTML = rightTitle;
  51894. rightPart.style.fontSize = "12px";
  51895. rightPart.style.maxWidth = "200px";
  51896. container.appendChild(leftPart);
  51897. container.appendChild(rightPart);
  51898. label.appendChild(container);
  51899. root.appendChild(label);
  51900. root.appendChild(document.createElement("br"));
  51901. };
  51902. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  51903. if (tag === void 0) { tag = null; }
  51904. var label = document.createElement("label");
  51905. label.style.display = "inline";
  51906. var checkBox = document.createElement("input");
  51907. checkBox.type = "checkbox";
  51908. checkBox.checked = initialState;
  51909. checkBox.style.display = "inline";
  51910. checkBox.style.margin = "0px 5px 0px 0px";
  51911. checkBox.style.verticalAlign = "sub";
  51912. checkBox.addEventListener("change", function (evt) {
  51913. task(evt.target, tag);
  51914. });
  51915. label.appendChild(checkBox);
  51916. label.appendChild(document.createTextNode(title));
  51917. root.appendChild(label);
  51918. root.appendChild(document.createElement("br"));
  51919. };
  51920. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  51921. if (tag === void 0) { tag = null; }
  51922. var button = document.createElement("button");
  51923. button.innerHTML = title;
  51924. button.style.height = "24px";
  51925. button.style.width = "150px";
  51926. button.style.marginBottom = "5px";
  51927. button.style.color = "#444444";
  51928. button.style.border = "1px solid white";
  51929. button.className = "debugLayerButton";
  51930. button.addEventListener("click", function (evt) {
  51931. task(evt.target, tag);
  51932. });
  51933. root.appendChild(button);
  51934. root.appendChild(document.createElement("br"));
  51935. };
  51936. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  51937. if (tag === void 0) { tag = null; }
  51938. var label = document.createElement("label");
  51939. label.style.display = "inline";
  51940. var boundingBoxesRadio = document.createElement("input");
  51941. boundingBoxesRadio.type = "radio";
  51942. boundingBoxesRadio.name = name;
  51943. boundingBoxesRadio.checked = initialState;
  51944. boundingBoxesRadio.style.display = "inline";
  51945. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  51946. boundingBoxesRadio.style.verticalAlign = "sub";
  51947. boundingBoxesRadio.addEventListener("change", function (evt) {
  51948. task(evt.target, tag);
  51949. });
  51950. label.appendChild(boundingBoxesRadio);
  51951. label.appendChild(document.createTextNode(title));
  51952. root.appendChild(label);
  51953. root.appendChild(document.createElement("br"));
  51954. };
  51955. DebugLayer.prototype._generateDOMelements = function () {
  51956. var _this = this;
  51957. this._globalDiv.id = "DebugLayer";
  51958. this._globalDiv.style.position = "absolute";
  51959. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  51960. this._globalDiv.style.fontSize = "14px";
  51961. this._globalDiv.style.color = "white";
  51962. // Drawing canvas
  51963. this._drawingCanvas = document.createElement("canvas");
  51964. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  51965. this._drawingCanvas.style.position = "absolute";
  51966. this._drawingCanvas.style.pointerEvents = "none";
  51967. this._drawingCanvas.style.backgroundColor = "transparent";
  51968. this._drawingContext = this._drawingCanvas.getContext("2d");
  51969. this._globalDiv.appendChild(this._drawingCanvas);
  51970. if (this._showUI) {
  51971. var background = "rgba(128, 128, 128, 0.4)";
  51972. var border = "rgb(180, 180, 180) solid 1px";
  51973. // Stats
  51974. this._statsDiv = document.createElement("div");
  51975. this._statsDiv.id = "DebugLayerStats";
  51976. this._statsDiv.style.border = border;
  51977. this._statsDiv.style.position = "absolute";
  51978. this._statsDiv.style.background = background;
  51979. this._statsDiv.style.padding = "0px 0px 0px 5px";
  51980. this._generateheader(this._statsDiv, "STATISTICS");
  51981. this._statsSubsetDiv = document.createElement("div");
  51982. this._statsSubsetDiv.style.paddingTop = "5px";
  51983. this._statsSubsetDiv.style.paddingBottom = "5px";
  51984. this._statsSubsetDiv.style.overflowY = "auto";
  51985. this._statsDiv.appendChild(this._statsSubsetDiv);
  51986. // Tree
  51987. this._treeDiv = document.createElement("div");
  51988. this._treeDiv.id = "DebugLayerTree";
  51989. this._treeDiv.style.border = border;
  51990. this._treeDiv.style.position = "absolute";
  51991. this._treeDiv.style.background = background;
  51992. this._treeDiv.style.padding = "0px 0px 0px 5px";
  51993. this._treeDiv.style.display = "none";
  51994. this._generateheader(this._treeDiv, "MESHES TREE");
  51995. this._treeSubsetDiv = document.createElement("div");
  51996. this._treeSubsetDiv.style.paddingTop = "5px";
  51997. this._treeSubsetDiv.style.paddingRight = "5px";
  51998. this._treeSubsetDiv.style.overflowY = "auto";
  51999. this._treeSubsetDiv.style.maxHeight = "300px";
  52000. this._treeDiv.appendChild(this._treeSubsetDiv);
  52001. this._needToRefreshMeshesTree = true;
  52002. // Logs
  52003. this._logDiv = document.createElement("div");
  52004. this._logDiv.style.border = border;
  52005. this._logDiv.id = "DebugLayerLogs";
  52006. this._logDiv.style.position = "absolute";
  52007. this._logDiv.style.background = background;
  52008. this._logDiv.style.padding = "0px 0px 0px 5px";
  52009. this._logDiv.style.display = "none";
  52010. this._generateheader(this._logDiv, "LOGS");
  52011. this._logSubsetDiv = document.createElement("div");
  52012. this._logSubsetDiv.style.height = "127px";
  52013. this._logSubsetDiv.style.paddingTop = "5px";
  52014. this._logSubsetDiv.style.overflowY = "auto";
  52015. this._logSubsetDiv.style.fontSize = "12px";
  52016. this._logSubsetDiv.style.fontFamily = "consolas";
  52017. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  52018. this._logDiv.appendChild(this._logSubsetDiv);
  52019. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  52020. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  52021. };
  52022. // Options
  52023. this._optionsDiv = document.createElement("div");
  52024. this._optionsDiv.id = "DebugLayerOptions";
  52025. this._optionsDiv.style.border = border;
  52026. this._optionsDiv.style.position = "absolute";
  52027. this._optionsDiv.style.background = background;
  52028. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  52029. this._optionsDiv.style.overflowY = "auto";
  52030. this._generateheader(this._optionsDiv, "OPTIONS");
  52031. this._optionsSubsetDiv = document.createElement("div");
  52032. this._optionsSubsetDiv.style.paddingTop = "5px";
  52033. this._optionsSubsetDiv.style.paddingBottom = "5px";
  52034. this._optionsSubsetDiv.style.overflowY = "auto";
  52035. this._optionsSubsetDiv.style.maxHeight = "200px";
  52036. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  52037. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  52038. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  52039. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  52040. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  52041. _this._displayTree = element.checked;
  52042. _this._needToRefreshMeshesTree = true;
  52043. });
  52044. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52045. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  52046. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  52047. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  52048. _this._labelsEnabled = element.checked;
  52049. if (!_this._labelsEnabled) {
  52050. _this._clearLabels();
  52051. }
  52052. });
  52053. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  52054. if (element.checked) {
  52055. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  52056. }
  52057. else {
  52058. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  52059. }
  52060. });
  52061. ;
  52062. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52063. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  52064. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  52065. if (element.checked) {
  52066. _this._scene.forceWireframe = false;
  52067. _this._scene.forcePointsCloud = false;
  52068. }
  52069. });
  52070. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  52071. if (element.checked) {
  52072. _this._scene.forceWireframe = true;
  52073. _this._scene.forcePointsCloud = false;
  52074. }
  52075. });
  52076. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  52077. if (element.checked) {
  52078. _this._scene.forceWireframe = false;
  52079. _this._scene.forcePointsCloud = true;
  52080. }
  52081. });
  52082. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52083. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  52084. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  52085. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  52086. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  52087. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  52088. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  52089. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  52090. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  52091. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  52092. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  52093. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  52094. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52095. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  52096. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  52097. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  52098. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  52099. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  52100. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  52101. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  52102. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  52103. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  52104. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  52105. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  52106. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  52107. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  52108. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  52109. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  52110. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  52111. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52112. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  52113. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  52114. if (element.checked) {
  52115. _this._scene.headphone = true;
  52116. }
  52117. });
  52118. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  52119. if (element.checked) {
  52120. _this._scene.headphone = false;
  52121. }
  52122. });
  52123. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  52124. _this._scene.audioEnabled = !element.checked;
  52125. });
  52126. }
  52127. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52128. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  52129. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  52130. if (!element.checked) {
  52131. _this._clearSkeletonViewers();
  52132. return;
  52133. }
  52134. for (var index = 0; index < _this._scene.meshes.length; index++) {
  52135. var mesh = _this._scene.meshes[index];
  52136. if (mesh.skeleton) {
  52137. var found = false;
  52138. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  52139. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  52140. found = true;
  52141. break;
  52142. }
  52143. }
  52144. if (found) {
  52145. continue;
  52146. }
  52147. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  52148. viewer.isEnabled = true;
  52149. _this._skeletonViewers.push(viewer);
  52150. }
  52151. }
  52152. });
  52153. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52154. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  52155. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  52156. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  52157. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  52158. if (_this._camera) {
  52159. console.log(_this._camera);
  52160. }
  52161. else {
  52162. console.warn("No camera defined, or debug layer created before camera creation!");
  52163. }
  52164. });
  52165. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52166. this._globalDiv.appendChild(this._statsDiv);
  52167. this._globalDiv.appendChild(this._logDiv);
  52168. this._globalDiv.appendChild(this._optionsDiv);
  52169. this._globalDiv.appendChild(this._treeDiv);
  52170. }
  52171. };
  52172. DebugLayer.prototype._displayStats = function () {
  52173. var scene = this._scene;
  52174. var engine = scene.getEngine();
  52175. var glInfo = engine.getGlInfo();
  52176. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  52177. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  52178. + "<b>Count</b><br>"
  52179. + "Total meshes: " + scene.meshes.length + "<br>"
  52180. + "Total lights: " + scene.lights.length + "<br>"
  52181. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  52182. + "Total materials: " + scene.materials.length + "<br>"
  52183. + "Total textures: " + scene.textures.length + "<br>"
  52184. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  52185. + "Active indices: " + scene.getActiveIndices() + "<br>"
  52186. + "Active bones: " + scene.getActiveBones() + "<br>"
  52187. + "Active particles: " + scene.getActiveParticles() + "<br>"
  52188. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  52189. + "<b>Duration</b><br>"
  52190. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  52191. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  52192. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  52193. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  52194. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  52195. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  52196. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  52197. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  52198. + "</div>"
  52199. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  52200. + "<b>Extensions</b><br>"
  52201. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  52202. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  52203. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  52204. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  52205. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  52206. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  52207. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  52208. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  52209. + "</div><br>"
  52210. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  52211. + "<b>Caps.</b><br>"
  52212. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  52213. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  52214. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  52215. + "<b>Info</b><br>"
  52216. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  52217. + glInfo.version + "<br>"
  52218. + "</div><br>"
  52219. + glInfo.renderer + "<br>";
  52220. if (this.customStatsFunction) {
  52221. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  52222. }
  52223. };
  52224. return DebugLayer;
  52225. })();
  52226. BABYLON.DebugLayer = DebugLayer;
  52227. })(BABYLON || (BABYLON = {}));
  52228. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec2 origin;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n} \nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\n}\nelse \n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvec4 pos;\npos.xy=(pos2.xy-origin)*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,zBias.y);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.w == 0.0) {\ndiscard;\n}\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 origin;\natt vec2 textureSize;\natt float frame;\natt float invertY;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\n\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x)+off.x,(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\npos.xy=(pos2.xy*sizeUV*textureSize)-origin;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,zBias.y);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 origin;\natt vec2 textureSize;\natt vec4 color;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\nvColor=color;\nvec4 pos;\npos.xy=(pos2.xy-origin)*sizeUV*textureSize;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,zBias.y);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  52229. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef OPENGLNORMALMAP\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,vec3(1.,1.,1.));\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\nfloat computeLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\nreturn lightDistanceFalloff;\n#else\nfloat lightFalloff=max(0.,1.0-length(lightOffset)/range);\nreturn lightFalloff;\n#endif\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif\n#ifdef CAMERACOLORGRADING\nvec4 colorGrades(vec4 color,sampler2D texture,vec4 vCameraColorGradingInfos,vec4 vCameraColorGradingScaleOffset) \n{\n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(texture,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(texture,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(lightOffset);\n\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nattenuation*=cosAngle;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  52230. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];n.x=r,n.y=o},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var _=M.Vector3[2],b=M.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=l,_.y=x,_.z=z,_.normalize(),n.CrossToRef(_,R,b),b.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,n.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=c,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new s(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,b=-(s*v-e*g+h*T),F=1/(i*R+n*_+r*M+o*b),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,D=e*y-h*m,E=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(n*z-r*w+o*v)*F,t.m[5]=(i*z-r*d+o*g)*F,t.m[9]=-(i*w-n*d+o*T)*F,t.m[13]=(i*v-n*g+r*T)*F,t.m[2]=(n*A-r*L+o*P)*F,t.m[6]=-(i*A-r*Z+o*C)*F,t.m[10]=(i*L-n*Z+o*S)*F,t.m[14]=-(i*P-n*C+r*S)*F,t.m[3]=-(n*I-r*q+o*D)*F,t.m[7]=(i*I-r*E+o*V)*F,t.m[11]=-(i*q-n*E+o*W)*F,t.m[15]=(i*D-n*V+r*W)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new s(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],b=t.m[7],F=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*F+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*b+s*P+e*I,i[n+4]=h*v+a*R+u*F+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*b+u*P+m*I,i[n+8]=y*v+c*R+p*F+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*b+p*P+f*I,i[n+12]=l*v+x*R+z*F+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*b+z*P+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new e(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,\nz.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),s=0;16>s;s++)o.m[s]=i.m[s]*(1-r)+n.m[s]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new s(0,0,0),e=new a,h=new s(0,0,0);i.decompose(o,e,h);var u=new s(0,0,0),m=new a,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=a.Slerp(e,m,r),f=s.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new s(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return s.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var l=t.Orientation,x=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=x;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(e,h,a),m=u.angle.radians()/s;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  52231. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  52232. module.exports = BABYLON;
  52233. };