babylon.max.js 2.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449
  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. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = 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.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. })();
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. })();
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addVector3 = function (otherVector) {
  412. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  413. };
  414. Vector2.prototype.subtract = function (otherVector) {
  415. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  416. };
  417. Vector2.prototype.subtractToRef = function (otherVector, result) {
  418. result.x = this.x - otherVector.x;
  419. result.y = this.y - otherVector.y;
  420. return this;
  421. };
  422. Vector2.prototype.subtractInPlace = function (otherVector) {
  423. this.x -= otherVector.x;
  424. this.y -= otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.multiplyInPlace = function (otherVector) {
  428. this.x *= otherVector.x;
  429. this.y *= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiply = function (otherVector) {
  433. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  434. };
  435. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  436. result.x = this.x * otherVector.x;
  437. result.y = this.y * otherVector.y;
  438. return this;
  439. };
  440. Vector2.prototype.multiplyByFloats = function (x, y) {
  441. return new Vector2(this.x * x, this.y * y);
  442. };
  443. Vector2.prototype.divide = function (otherVector) {
  444. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  445. };
  446. Vector2.prototype.divideToRef = function (otherVector, result) {
  447. result.x = this.x / otherVector.x;
  448. result.y = this.y / otherVector.y;
  449. return this;
  450. };
  451. Vector2.prototype.negate = function () {
  452. return new Vector2(-this.x, -this.y);
  453. };
  454. Vector2.prototype.scaleInPlace = function (scale) {
  455. this.x *= scale;
  456. this.y *= scale;
  457. return this;
  458. };
  459. Vector2.prototype.scale = function (scale) {
  460. return new Vector2(this.x * scale, this.y * scale);
  461. };
  462. Vector2.prototype.equals = function (otherVector) {
  463. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  464. };
  465. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  466. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  467. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  468. };
  469. // Properties
  470. Vector2.prototype.length = function () {
  471. return Math.sqrt(this.x * this.x + this.y * this.y);
  472. };
  473. Vector2.prototype.lengthSquared = function () {
  474. return (this.x * this.x + this.y * this.y);
  475. };
  476. // Methods
  477. Vector2.prototype.normalize = function () {
  478. var len = this.length();
  479. if (len === 0)
  480. return this;
  481. var num = 1.0 / len;
  482. this.x *= num;
  483. this.y *= num;
  484. return this;
  485. };
  486. Vector2.prototype.clone = function () {
  487. return new Vector2(this.x, this.y);
  488. };
  489. // Statics
  490. Vector2.Zero = function () {
  491. return new Vector2(0, 0);
  492. };
  493. Vector2.FromArray = function (array, offset) {
  494. if (offset === void 0) { offset = 0; }
  495. return new Vector2(array[offset], array[offset + 1]);
  496. };
  497. Vector2.FromArrayToRef = function (array, offset, result) {
  498. result.x = array[offset];
  499. result.y = array[offset + 1];
  500. };
  501. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  502. var squared = amount * amount;
  503. var cubed = amount * squared;
  504. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  505. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  506. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  507. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  508. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  509. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  510. return new Vector2(x, y);
  511. };
  512. Vector2.Clamp = function (value, min, max) {
  513. var x = value.x;
  514. x = (x > max.x) ? max.x : x;
  515. x = (x < min.x) ? min.x : x;
  516. var y = value.y;
  517. y = (y > max.y) ? max.y : y;
  518. y = (y < min.y) ? min.y : y;
  519. return new Vector2(x, y);
  520. };
  521. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  522. var squared = amount * amount;
  523. var cubed = amount * squared;
  524. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  525. var part2 = (-2.0 * cubed) + (3.0 * squared);
  526. var part3 = (cubed - (2.0 * squared)) + amount;
  527. var part4 = cubed - squared;
  528. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  529. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  530. return new Vector2(x, y);
  531. };
  532. Vector2.Lerp = function (start, end, amount) {
  533. var x = start.x + ((end.x - start.x) * amount);
  534. var y = start.y + ((end.y - start.y) * amount);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Dot = function (left, right) {
  538. return left.x * right.x + left.y * right.y;
  539. };
  540. Vector2.Normalize = function (vector) {
  541. var newVector = vector.clone();
  542. newVector.normalize();
  543. return newVector;
  544. };
  545. Vector2.Minimize = function (left, right) {
  546. var x = (left.x < right.x) ? left.x : right.x;
  547. var y = (left.y < right.y) ? left.y : right.y;
  548. return new Vector2(x, y);
  549. };
  550. Vector2.Maximize = function (left, right) {
  551. var x = (left.x > right.x) ? left.x : right.x;
  552. var y = (left.y > right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Transform = function (vector, transformation) {
  556. var r = Vector2.Zero();
  557. Vector2.TransformToRef(vector, transformation, r);
  558. return r;
  559. };
  560. Vector2.TransformToRef = function (vector, transformation, result) {
  561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  563. result.x = x;
  564. result.y = y;
  565. };
  566. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  567. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  568. var sign = a < 0 ? -1 : 1;
  569. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  570. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  571. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  572. };
  573. Vector2.Distance = function (value1, value2) {
  574. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  575. };
  576. Vector2.DistanceSquared = function (value1, value2) {
  577. var x = value1.x - value2.x;
  578. var y = value1.y - value2.y;
  579. return (x * x) + (y * y);
  580. };
  581. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  582. var l2 = Vector2.DistanceSquared(segA, segB);
  583. if (l2 === 0.0) {
  584. return Vector2.Distance(p, segA);
  585. }
  586. var v = segB.subtract(segA);
  587. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  588. var proj = segA.add(v.multiplyByFloats(t, t));
  589. return Vector2.Distance(p, proj);
  590. };
  591. return Vector2;
  592. })();
  593. BABYLON.Vector2 = Vector2;
  594. var Vector3 = (function () {
  595. function Vector3(x, y, z) {
  596. this.x = x;
  597. this.y = y;
  598. this.z = z;
  599. }
  600. Vector3.prototype.toString = function () {
  601. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  602. };
  603. Vector3.prototype.getClassName = function () {
  604. return "Vector3";
  605. };
  606. Vector3.prototype.getHashCode = function () {
  607. var hash = this.x || 0;
  608. hash = (hash * 397) ^ (this.y || 0);
  609. hash = (hash * 397) ^ (this.z || 0);
  610. return hash;
  611. };
  612. // Operators
  613. Vector3.prototype.asArray = function () {
  614. var result = [];
  615. this.toArray(result, 0);
  616. return result;
  617. };
  618. Vector3.prototype.toArray = function (array, index) {
  619. if (index === void 0) { index = 0; }
  620. array[index] = this.x;
  621. array[index + 1] = this.y;
  622. array[index + 2] = this.z;
  623. return this;
  624. };
  625. Vector3.prototype.toQuaternion = function () {
  626. var result = new Quaternion(0, 0, 0, 1);
  627. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  628. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  629. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  630. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  631. var cosy = Math.cos(this.y * 0.5);
  632. var siny = Math.sin(this.y * 0.5);
  633. result.x = coszMinusx * siny;
  634. result.y = -sinzMinusx * siny;
  635. result.z = sinxPlusz * cosy;
  636. result.w = cosxPlusz * cosy;
  637. return result;
  638. };
  639. Vector3.prototype.addInPlace = function (otherVector) {
  640. this.x += otherVector.x;
  641. this.y += otherVector.y;
  642. this.z += otherVector.z;
  643. return this;
  644. };
  645. Vector3.prototype.add = function (otherVector) {
  646. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  647. };
  648. Vector3.prototype.addToRef = function (otherVector, result) {
  649. result.x = this.x + otherVector.x;
  650. result.y = this.y + otherVector.y;
  651. result.z = this.z + otherVector.z;
  652. return this;
  653. };
  654. Vector3.prototype.subtractInPlace = function (otherVector) {
  655. this.x -= otherVector.x;
  656. this.y -= otherVector.y;
  657. this.z -= otherVector.z;
  658. return this;
  659. };
  660. Vector3.prototype.subtract = function (otherVector) {
  661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  662. };
  663. Vector3.prototype.subtractToRef = function (otherVector, result) {
  664. result.x = this.x - otherVector.x;
  665. result.y = this.y - otherVector.y;
  666. result.z = this.z - otherVector.z;
  667. return this;
  668. };
  669. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  670. return new Vector3(this.x - x, this.y - y, this.z - z);
  671. };
  672. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  673. result.x = this.x - x;
  674. result.y = this.y - y;
  675. result.z = this.z - z;
  676. return this;
  677. };
  678. Vector3.prototype.negate = function () {
  679. return new Vector3(-this.x, -this.y, -this.z);
  680. };
  681. Vector3.prototype.scaleInPlace = function (scale) {
  682. this.x *= scale;
  683. this.y *= scale;
  684. this.z *= scale;
  685. return this;
  686. };
  687. Vector3.prototype.scale = function (scale) {
  688. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  689. };
  690. Vector3.prototype.scaleToRef = function (scale, result) {
  691. result.x = this.x * scale;
  692. result.y = this.y * scale;
  693. result.z = this.z * scale;
  694. };
  695. Vector3.prototype.equals = function (otherVector) {
  696. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  697. };
  698. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  699. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  700. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  701. };
  702. Vector3.prototype.equalsToFloats = function (x, y, z) {
  703. return this.x === x && this.y === y && this.z === z;
  704. };
  705. Vector3.prototype.multiplyInPlace = function (otherVector) {
  706. this.x *= otherVector.x;
  707. this.y *= otherVector.y;
  708. this.z *= otherVector.z;
  709. return this;
  710. };
  711. Vector3.prototype.multiply = function (otherVector) {
  712. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  713. };
  714. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  715. result.x = this.x * otherVector.x;
  716. result.y = this.y * otherVector.y;
  717. result.z = this.z * otherVector.z;
  718. return this;
  719. };
  720. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  721. return new Vector3(this.x * x, this.y * y, this.z * z);
  722. };
  723. Vector3.prototype.divide = function (otherVector) {
  724. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  725. };
  726. Vector3.prototype.divideToRef = function (otherVector, result) {
  727. result.x = this.x / otherVector.x;
  728. result.y = this.y / otherVector.y;
  729. result.z = this.z / otherVector.z;
  730. return this;
  731. };
  732. Vector3.prototype.MinimizeInPlace = function (other) {
  733. if (other.x < this.x)
  734. this.x = other.x;
  735. if (other.y < this.y)
  736. this.y = other.y;
  737. if (other.z < this.z)
  738. this.z = other.z;
  739. return this;
  740. };
  741. Vector3.prototype.MaximizeInPlace = function (other) {
  742. if (other.x > this.x)
  743. this.x = other.x;
  744. if (other.y > this.y)
  745. this.y = other.y;
  746. if (other.z > this.z)
  747. this.z = other.z;
  748. return this;
  749. };
  750. // Properties
  751. Vector3.prototype.length = function () {
  752. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  753. };
  754. Vector3.prototype.lengthSquared = function () {
  755. return (this.x * this.x + this.y * this.y + this.z * this.z);
  756. };
  757. // Methods
  758. Vector3.prototype.normalize = function () {
  759. var len = this.length();
  760. if (len === 0 || len === 1.0)
  761. return this;
  762. var num = 1.0 / len;
  763. this.x *= num;
  764. this.y *= num;
  765. this.z *= num;
  766. return this;
  767. };
  768. Vector3.prototype.clone = function () {
  769. return new Vector3(this.x, this.y, this.z);
  770. };
  771. Vector3.prototype.copyFrom = function (source) {
  772. this.x = source.x;
  773. this.y = source.y;
  774. this.z = source.z;
  775. return this;
  776. };
  777. Vector3.prototype.copyFromFloats = function (x, y, z) {
  778. this.x = x;
  779. this.y = y;
  780. this.z = z;
  781. return this;
  782. };
  783. // Statics
  784. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  785. var d0 = Vector3.Dot(vector0, axis) - size;
  786. var d1 = Vector3.Dot(vector1, axis) - size;
  787. var s = d0 / (d0 - d1);
  788. return s;
  789. };
  790. Vector3.FromArray = function (array, offset) {
  791. if (!offset) {
  792. offset = 0;
  793. }
  794. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  795. };
  796. Vector3.FromFloatArray = function (array, offset) {
  797. if (!offset) {
  798. offset = 0;
  799. }
  800. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  801. };
  802. Vector3.FromArrayToRef = function (array, offset, result) {
  803. result.x = array[offset];
  804. result.y = array[offset + 1];
  805. result.z = array[offset + 2];
  806. };
  807. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  808. result.x = array[offset];
  809. result.y = array[offset + 1];
  810. result.z = array[offset + 2];
  811. };
  812. Vector3.FromFloatsToRef = function (x, y, z, result) {
  813. result.x = x;
  814. result.y = y;
  815. result.z = z;
  816. };
  817. Vector3.Zero = function () {
  818. return new Vector3(0, 0, 0);
  819. };
  820. Vector3.Up = function () {
  821. return new Vector3(0, 1.0, 0);
  822. };
  823. Vector3.TransformCoordinates = function (vector, transformation) {
  824. var result = Vector3.Zero();
  825. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  826. return result;
  827. };
  828. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  829. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  830. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  831. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  832. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  833. result.x = x / w;
  834. result.y = y / w;
  835. result.z = z / w;
  836. };
  837. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  838. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  839. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  840. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  841. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  842. result.x = rx / rw;
  843. result.y = ry / rw;
  844. result.z = rz / rw;
  845. };
  846. Vector3.TransformNormal = function (vector, transformation) {
  847. var result = Vector3.Zero();
  848. Vector3.TransformNormalToRef(vector, transformation, result);
  849. return result;
  850. };
  851. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  852. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  853. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  854. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  855. };
  856. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  857. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  858. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  859. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  860. };
  861. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  862. var squared = amount * amount;
  863. var cubed = amount * squared;
  864. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  865. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  866. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  867. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  868. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  869. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  870. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  871. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  872. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  873. return new Vector3(x, y, z);
  874. };
  875. Vector3.Clamp = function (value, min, max) {
  876. var x = value.x;
  877. x = (x > max.x) ? max.x : x;
  878. x = (x < min.x) ? min.x : x;
  879. var y = value.y;
  880. y = (y > max.y) ? max.y : y;
  881. y = (y < min.y) ? min.y : y;
  882. var z = value.z;
  883. z = (z > max.z) ? max.z : z;
  884. z = (z < min.z) ? min.z : z;
  885. return new Vector3(x, y, z);
  886. };
  887. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  888. var squared = amount * amount;
  889. var cubed = amount * squared;
  890. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  891. var part2 = (-2.0 * cubed) + (3.0 * squared);
  892. var part3 = (cubed - (2.0 * squared)) + amount;
  893. var part4 = cubed - squared;
  894. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  895. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  896. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  897. return new Vector3(x, y, z);
  898. };
  899. Vector3.Lerp = function (start, end, amount) {
  900. var x = start.x + ((end.x - start.x) * amount);
  901. var y = start.y + ((end.y - start.y) * amount);
  902. var z = start.z + ((end.z - start.z) * amount);
  903. return new Vector3(x, y, z);
  904. };
  905. Vector3.Dot = function (left, right) {
  906. return (left.x * right.x + left.y * right.y + left.z * right.z);
  907. };
  908. Vector3.Cross = function (left, right) {
  909. var result = Vector3.Zero();
  910. Vector3.CrossToRef(left, right, result);
  911. return result;
  912. };
  913. Vector3.CrossToRef = function (left, right, result) {
  914. result.x = left.y * right.z - left.z * right.y;
  915. result.y = left.z * right.x - left.x * right.z;
  916. result.z = left.x * right.y - left.y * right.x;
  917. };
  918. Vector3.Normalize = function (vector) {
  919. var result = Vector3.Zero();
  920. Vector3.NormalizeToRef(vector, result);
  921. return result;
  922. };
  923. Vector3.NormalizeToRef = function (vector, result) {
  924. result.copyFrom(vector);
  925. result.normalize();
  926. };
  927. Vector3.Project = function (vector, world, transform, viewport) {
  928. var cw = viewport.width;
  929. var ch = viewport.height;
  930. var cx = viewport.x;
  931. var cy = viewport.y;
  932. 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);
  933. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  934. return Vector3.TransformCoordinates(vector, finalMatrix);
  935. };
  936. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  937. var matrix = world.multiply(transform);
  938. matrix.invert();
  939. source.x = source.x / viewportWidth * 2 - 1;
  940. source.y = -(source.y / viewportHeight * 2 - 1);
  941. var vector = Vector3.TransformCoordinates(source, matrix);
  942. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  943. if (MathTools.WithinEpsilon(num, 1.0)) {
  944. vector = vector.scale(1.0 / num);
  945. }
  946. return vector;
  947. };
  948. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  949. var matrix = world.multiply(view).multiply(projection);
  950. matrix.invert();
  951. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  952. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  953. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  954. if (MathTools.WithinEpsilon(num, 1.0)) {
  955. vector = vector.scale(1.0 / num);
  956. }
  957. return vector;
  958. };
  959. Vector3.Minimize = function (left, right) {
  960. var min = left.clone();
  961. min.MinimizeInPlace(right);
  962. return min;
  963. };
  964. Vector3.Maximize = function (left, right) {
  965. var max = left.clone();
  966. max.MaximizeInPlace(right);
  967. return max;
  968. };
  969. Vector3.Distance = function (value1, value2) {
  970. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  971. };
  972. Vector3.DistanceSquared = function (value1, value2) {
  973. var x = value1.x - value2.x;
  974. var y = value1.y - value2.y;
  975. var z = value1.z - value2.z;
  976. return (x * x) + (y * y) + (z * z);
  977. };
  978. Vector3.Center = function (value1, value2) {
  979. var center = value1.add(value2);
  980. center.scaleInPlace(0.5);
  981. return center;
  982. };
  983. /**
  984. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  985. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  986. * to something in order to rotate it from its local system to the given target system.
  987. */
  988. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  989. var rotation = Vector3.Zero();
  990. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  991. return rotation;
  992. };
  993. /**
  994. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  995. */
  996. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  997. var u = axis1.normalize();
  998. var w = axis3.normalize();
  999. // world axis
  1000. var X = Axis.X;
  1001. var Y = Axis.Y;
  1002. // equation unknowns and vars
  1003. var yaw = 0.0;
  1004. var pitch = 0.0;
  1005. var roll = 0.0;
  1006. var x = 0.0;
  1007. var y = 0.0;
  1008. var z = 0.0;
  1009. var t = 0.0;
  1010. var sign = -1.0;
  1011. var nbRevert = 0;
  1012. var cross = Tmp.Vector3[0];
  1013. var dot = 0.0;
  1014. // step 1 : rotation around w
  1015. // Rv3(u) = u1, and u1 belongs to plane xOz
  1016. // Rv3(w) = w1 = w invariant
  1017. var u1 = Tmp.Vector3[1];
  1018. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1019. z = 1.0;
  1020. }
  1021. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1022. x = 1.0;
  1023. }
  1024. else {
  1025. t = w.z / w.x;
  1026. x = -t * Math.sqrt(1 / (1 + t * t));
  1027. z = Math.sqrt(1 / (1 + t * t));
  1028. }
  1029. u1.x = x;
  1030. u1.y = y;
  1031. u1.z = z;
  1032. u1.normalize();
  1033. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1034. cross.normalize();
  1035. if (Vector3.Dot(w, cross) < 0) {
  1036. sign = 1.0;
  1037. }
  1038. dot = Vector3.Dot(u, u1);
  1039. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1040. roll = Math.acos(dot) * sign;
  1041. if (Vector3.Dot(u1, X) < 0) {
  1042. roll = Math.PI + roll;
  1043. u1 = u1.scaleInPlace(-1);
  1044. nbRevert++;
  1045. }
  1046. // step 2 : rotate around u1
  1047. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1048. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1049. var w2 = Tmp.Vector3[2];
  1050. var v2 = Tmp.Vector3[3];
  1051. x = 0.0;
  1052. y = 0.0;
  1053. z = 0.0;
  1054. sign = -1.0;
  1055. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1056. x = 1.0;
  1057. }
  1058. else {
  1059. t = u1.z / u1.x;
  1060. x = -t * Math.sqrt(1 / (1 + t * t));
  1061. z = Math.sqrt(1 / (1 + t * t));
  1062. }
  1063. w2.x = x;
  1064. w2.y = y;
  1065. w2.z = z;
  1066. w2.normalize();
  1067. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1068. v2.normalize();
  1069. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1070. cross.normalize();
  1071. if (Vector3.Dot(u1, cross) < 0) {
  1072. sign = 1.0;
  1073. }
  1074. dot = Vector3.Dot(w, w2);
  1075. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1076. pitch = Math.acos(dot) * sign;
  1077. if (Vector3.Dot(v2, Y) < 0) {
  1078. pitch = Math.PI + pitch;
  1079. nbRevert++;
  1080. }
  1081. // step 3 : rotate around v2
  1082. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1083. sign = -1.0;
  1084. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1085. cross.normalize();
  1086. if (Vector3.Dot(cross, Y) < 0) {
  1087. sign = 1.0;
  1088. }
  1089. dot = Vector3.Dot(u1, X);
  1090. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1091. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1092. if (dot < 0 && nbRevert < 2) {
  1093. yaw = Math.PI + yaw;
  1094. }
  1095. ref.x = pitch;
  1096. ref.y = yaw;
  1097. ref.z = roll;
  1098. };
  1099. return Vector3;
  1100. })();
  1101. BABYLON.Vector3 = Vector3;
  1102. //Vector4 class created for EulerAngle class conversion to Quaternion
  1103. var Vector4 = (function () {
  1104. function Vector4(x, y, z, w) {
  1105. this.x = x;
  1106. this.y = y;
  1107. this.z = z;
  1108. this.w = w;
  1109. }
  1110. Vector4.prototype.toString = function () {
  1111. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1112. };
  1113. Vector4.prototype.getClassName = function () {
  1114. return "Vector4";
  1115. };
  1116. Vector4.prototype.getHashCode = function () {
  1117. var hash = this.x || 0;
  1118. hash = (hash * 397) ^ (this.y || 0);
  1119. hash = (hash * 397) ^ (this.z || 0);
  1120. hash = (hash * 397) ^ (this.w || 0);
  1121. return hash;
  1122. };
  1123. // Operators
  1124. Vector4.prototype.asArray = function () {
  1125. var result = [];
  1126. this.toArray(result, 0);
  1127. return result;
  1128. };
  1129. Vector4.prototype.toArray = function (array, index) {
  1130. if (index === undefined) {
  1131. index = 0;
  1132. }
  1133. array[index] = this.x;
  1134. array[index + 1] = this.y;
  1135. array[index + 2] = this.z;
  1136. array[index + 3] = this.w;
  1137. return this;
  1138. };
  1139. Vector4.prototype.addInPlace = function (otherVector) {
  1140. this.x += otherVector.x;
  1141. this.y += otherVector.y;
  1142. this.z += otherVector.z;
  1143. this.w += otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.add = function (otherVector) {
  1147. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1148. };
  1149. Vector4.prototype.addToRef = function (otherVector, result) {
  1150. result.x = this.x + otherVector.x;
  1151. result.y = this.y + otherVector.y;
  1152. result.z = this.z + otherVector.z;
  1153. result.w = this.w + otherVector.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.subtractInPlace = function (otherVector) {
  1157. this.x -= otherVector.x;
  1158. this.y -= otherVector.y;
  1159. this.z -= otherVector.z;
  1160. this.w -= otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.subtract = function (otherVector) {
  1164. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1165. };
  1166. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1167. result.x = this.x - otherVector.x;
  1168. result.y = this.y - otherVector.y;
  1169. result.z = this.z - otherVector.z;
  1170. result.w = this.w - otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1174. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1175. };
  1176. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1177. result.x = this.x - x;
  1178. result.y = this.y - y;
  1179. result.z = this.z - z;
  1180. result.w = this.w - w;
  1181. return this;
  1182. };
  1183. Vector4.prototype.negate = function () {
  1184. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1185. };
  1186. Vector4.prototype.scaleInPlace = function (scale) {
  1187. this.x *= scale;
  1188. this.y *= scale;
  1189. this.z *= scale;
  1190. this.w *= scale;
  1191. return this;
  1192. };
  1193. Vector4.prototype.scale = function (scale) {
  1194. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1195. };
  1196. Vector4.prototype.scaleToRef = function (scale, result) {
  1197. result.x = this.x * scale;
  1198. result.y = this.y * scale;
  1199. result.z = this.z * scale;
  1200. result.w = this.w * scale;
  1201. };
  1202. Vector4.prototype.equals = function (otherVector) {
  1203. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1204. };
  1205. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1206. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1207. return otherVector
  1208. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1209. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1210. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1211. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1212. };
  1213. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1214. return this.x === x && this.y === y && this.z === z && this.w === w;
  1215. };
  1216. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1217. this.x *= otherVector.x;
  1218. this.y *= otherVector.y;
  1219. this.z *= otherVector.z;
  1220. this.w *= otherVector.w;
  1221. return this;
  1222. };
  1223. Vector4.prototype.multiply = function (otherVector) {
  1224. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1225. };
  1226. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1227. result.x = this.x * otherVector.x;
  1228. result.y = this.y * otherVector.y;
  1229. result.z = this.z * otherVector.z;
  1230. result.w = this.w * otherVector.w;
  1231. return this;
  1232. };
  1233. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1234. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1235. };
  1236. Vector4.prototype.divide = function (otherVector) {
  1237. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1238. };
  1239. Vector4.prototype.divideToRef = function (otherVector, result) {
  1240. result.x = this.x / otherVector.x;
  1241. result.y = this.y / otherVector.y;
  1242. result.z = this.z / otherVector.z;
  1243. result.w = this.w / otherVector.w;
  1244. return this;
  1245. };
  1246. Vector4.prototype.MinimizeInPlace = function (other) {
  1247. if (other.x < this.x)
  1248. this.x = other.x;
  1249. if (other.y < this.y)
  1250. this.y = other.y;
  1251. if (other.z < this.z)
  1252. this.z = other.z;
  1253. if (other.w < this.w)
  1254. this.w = other.w;
  1255. return this;
  1256. };
  1257. Vector4.prototype.MaximizeInPlace = function (other) {
  1258. if (other.x > this.x)
  1259. this.x = other.x;
  1260. if (other.y > this.y)
  1261. this.y = other.y;
  1262. if (other.z > this.z)
  1263. this.z = other.z;
  1264. if (other.w > this.w)
  1265. this.w = other.w;
  1266. return this;
  1267. };
  1268. // Properties
  1269. Vector4.prototype.length = function () {
  1270. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1271. };
  1272. Vector4.prototype.lengthSquared = function () {
  1273. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1274. };
  1275. // Methods
  1276. Vector4.prototype.normalize = function () {
  1277. var len = this.length();
  1278. if (len === 0)
  1279. return this;
  1280. var num = 1.0 / len;
  1281. this.x *= num;
  1282. this.y *= num;
  1283. this.z *= num;
  1284. this.w *= num;
  1285. return this;
  1286. };
  1287. Vector4.prototype.toVector3 = function () {
  1288. return new Vector3(this.x, this.y, this.z);
  1289. };
  1290. Vector4.prototype.clone = function () {
  1291. return new Vector4(this.x, this.y, this.z, this.w);
  1292. };
  1293. Vector4.prototype.copyFrom = function (source) {
  1294. this.x = source.x;
  1295. this.y = source.y;
  1296. this.z = source.z;
  1297. this.w = source.w;
  1298. return this;
  1299. };
  1300. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1301. this.x = x;
  1302. this.y = y;
  1303. this.z = z;
  1304. this.w = w;
  1305. return this;
  1306. };
  1307. // Statics
  1308. Vector4.FromArray = function (array, offset) {
  1309. if (!offset) {
  1310. offset = 0;
  1311. }
  1312. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1313. };
  1314. Vector4.FromArrayToRef = function (array, offset, result) {
  1315. result.x = array[offset];
  1316. result.y = array[offset + 1];
  1317. result.z = array[offset + 2];
  1318. result.w = array[offset + 3];
  1319. };
  1320. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1321. result.x = array[offset];
  1322. result.y = array[offset + 1];
  1323. result.z = array[offset + 2];
  1324. result.w = array[offset + 3];
  1325. };
  1326. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1327. result.x = x;
  1328. result.y = y;
  1329. result.z = z;
  1330. result.w = w;
  1331. };
  1332. Vector4.Zero = function () {
  1333. return new Vector4(0, 0, 0, 0);
  1334. };
  1335. Vector4.Normalize = function (vector) {
  1336. var result = Vector4.Zero();
  1337. Vector4.NormalizeToRef(vector, result);
  1338. return result;
  1339. };
  1340. Vector4.NormalizeToRef = function (vector, result) {
  1341. result.copyFrom(vector);
  1342. result.normalize();
  1343. };
  1344. Vector4.Minimize = function (left, right) {
  1345. var min = left.clone();
  1346. min.MinimizeInPlace(right);
  1347. return min;
  1348. };
  1349. Vector4.Maximize = function (left, right) {
  1350. var max = left.clone();
  1351. max.MaximizeInPlace(right);
  1352. return max;
  1353. };
  1354. Vector4.Distance = function (value1, value2) {
  1355. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1356. };
  1357. Vector4.DistanceSquared = function (value1, value2) {
  1358. var x = value1.x - value2.x;
  1359. var y = value1.y - value2.y;
  1360. var z = value1.z - value2.z;
  1361. var w = value1.w - value2.w;
  1362. return (x * x) + (y * y) + (z * z) + (w * w);
  1363. };
  1364. Vector4.Center = function (value1, value2) {
  1365. var center = value1.add(value2);
  1366. center.scaleInPlace(0.5);
  1367. return center;
  1368. };
  1369. return Vector4;
  1370. })();
  1371. BABYLON.Vector4 = Vector4;
  1372. var Size = (function () {
  1373. function Size(width, height) {
  1374. this.width = width;
  1375. this.height = height;
  1376. }
  1377. Size.prototype.toString = function () {
  1378. return "{W: " + this.width + ", H: " + this.height + "}";
  1379. };
  1380. Size.prototype.getClassName = function () {
  1381. return "Size";
  1382. };
  1383. Size.prototype.getHashCode = function () {
  1384. var hash = this.width || 0;
  1385. hash = (hash * 397) ^ (this.height || 0);
  1386. return hash;
  1387. };
  1388. Size.prototype.clone = function () {
  1389. return new Size(this.width, this.height);
  1390. };
  1391. Size.prototype.equals = function (other) {
  1392. if (!other) {
  1393. return false;
  1394. }
  1395. return (this.width === other.width) && (this.height === other.height);
  1396. };
  1397. Object.defineProperty(Size.prototype, "surface", {
  1398. get: function () {
  1399. return this.width * this.height;
  1400. },
  1401. enumerable: true,
  1402. configurable: true
  1403. });
  1404. Size.Zero = function () {
  1405. return new Size(0, 0);
  1406. };
  1407. Size.prototype.add = function (otherSize) {
  1408. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1409. return r;
  1410. };
  1411. Size.prototype.substract = function (otherSize) {
  1412. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1413. return r;
  1414. };
  1415. Size.Lerp = function (start, end, amount) {
  1416. var w = start.width + ((end.width - start.width) * amount);
  1417. var h = start.height + ((end.height - start.height) * amount);
  1418. return new Size(w, h);
  1419. };
  1420. return Size;
  1421. })();
  1422. BABYLON.Size = Size;
  1423. var Quaternion = (function () {
  1424. function Quaternion(x, y, z, w) {
  1425. if (x === void 0) { x = 0; }
  1426. if (y === void 0) { y = 0; }
  1427. if (z === void 0) { z = 0; }
  1428. if (w === void 0) { w = 1; }
  1429. this.x = x;
  1430. this.y = y;
  1431. this.z = z;
  1432. this.w = w;
  1433. }
  1434. Quaternion.prototype.toString = function () {
  1435. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1436. };
  1437. Quaternion.prototype.getClassName = function () {
  1438. return "Quaternion";
  1439. };
  1440. Quaternion.prototype.getHashCode = function () {
  1441. var hash = this.x || 0;
  1442. hash = (hash * 397) ^ (this.y || 0);
  1443. hash = (hash * 397) ^ (this.z || 0);
  1444. hash = (hash * 397) ^ (this.w || 0);
  1445. return hash;
  1446. };
  1447. Quaternion.prototype.asArray = function () {
  1448. return [this.x, this.y, this.z, this.w];
  1449. };
  1450. Quaternion.prototype.equals = function (otherQuaternion) {
  1451. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1452. };
  1453. Quaternion.prototype.clone = function () {
  1454. return new Quaternion(this.x, this.y, this.z, this.w);
  1455. };
  1456. Quaternion.prototype.copyFrom = function (other) {
  1457. this.x = other.x;
  1458. this.y = other.y;
  1459. this.z = other.z;
  1460. this.w = other.w;
  1461. return this;
  1462. };
  1463. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1464. this.x = x;
  1465. this.y = y;
  1466. this.z = z;
  1467. this.w = w;
  1468. return this;
  1469. };
  1470. Quaternion.prototype.add = function (other) {
  1471. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1472. };
  1473. Quaternion.prototype.subtract = function (other) {
  1474. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1475. };
  1476. Quaternion.prototype.scale = function (value) {
  1477. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1478. };
  1479. Quaternion.prototype.multiply = function (q1) {
  1480. var result = new Quaternion(0, 0, 0, 1.0);
  1481. this.multiplyToRef(q1, result);
  1482. return result;
  1483. };
  1484. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1485. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1486. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1487. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1488. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1489. result.copyFromFloats(x, y, z, w);
  1490. return this;
  1491. };
  1492. Quaternion.prototype.multiplyInPlace = function (q1) {
  1493. this.multiplyToRef(q1, this);
  1494. return this;
  1495. };
  1496. Quaternion.prototype.conjugateToRef = function (ref) {
  1497. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1498. return this;
  1499. };
  1500. Quaternion.prototype.conjugateInPlace = function () {
  1501. this.x *= -1;
  1502. this.y *= -1;
  1503. this.z *= -1;
  1504. return this;
  1505. };
  1506. Quaternion.prototype.conjugate = function () {
  1507. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1508. return result;
  1509. };
  1510. Quaternion.prototype.length = function () {
  1511. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1512. };
  1513. Quaternion.prototype.normalize = function () {
  1514. var length = 1.0 / this.length();
  1515. this.x *= length;
  1516. this.y *= length;
  1517. this.z *= length;
  1518. this.w *= length;
  1519. return this;
  1520. };
  1521. Quaternion.prototype.toEulerAngles = function (order) {
  1522. if (order === void 0) { order = "YZX"; }
  1523. var result = Vector3.Zero();
  1524. this.toEulerAnglesToRef(result, order);
  1525. return result;
  1526. };
  1527. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1528. if (order === void 0) { order = "YZX"; }
  1529. var heading, attitude, bank;
  1530. var x = this.x, y = this.y, z = this.z, w = this.w;
  1531. switch (order) {
  1532. case "YZX":
  1533. var test = x * y + z * w;
  1534. if (test > 0.499) {
  1535. heading = 2 * Math.atan2(x, w);
  1536. attitude = Math.PI / 2;
  1537. bank = 0;
  1538. }
  1539. if (test < -0.499) {
  1540. heading = -2 * Math.atan2(x, w);
  1541. attitude = -Math.PI / 2;
  1542. bank = 0;
  1543. }
  1544. if (isNaN(heading)) {
  1545. var sqx = x * x;
  1546. var sqy = y * y;
  1547. var sqz = z * z;
  1548. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1549. attitude = Math.asin(2 * test); // attitude
  1550. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1551. }
  1552. break;
  1553. default:
  1554. throw new Error("Euler order " + order + " not supported yet.");
  1555. }
  1556. result.y = heading;
  1557. result.z = attitude;
  1558. result.x = bank;
  1559. return this;
  1560. };
  1561. ;
  1562. Quaternion.prototype.toRotationMatrix = function (result) {
  1563. var xx = this.x * this.x;
  1564. var yy = this.y * this.y;
  1565. var zz = this.z * this.z;
  1566. var xy = this.x * this.y;
  1567. var zw = this.z * this.w;
  1568. var zx = this.z * this.x;
  1569. var yw = this.y * this.w;
  1570. var yz = this.y * this.z;
  1571. var xw = this.x * this.w;
  1572. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1573. result.m[1] = 2.0 * (xy + zw);
  1574. result.m[2] = 2.0 * (zx - yw);
  1575. result.m[3] = 0;
  1576. result.m[4] = 2.0 * (xy - zw);
  1577. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1578. result.m[6] = 2.0 * (yz + xw);
  1579. result.m[7] = 0;
  1580. result.m[8] = 2.0 * (zx + yw);
  1581. result.m[9] = 2.0 * (yz - xw);
  1582. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1583. result.m[11] = 0;
  1584. result.m[12] = 0;
  1585. result.m[13] = 0;
  1586. result.m[14] = 0;
  1587. result.m[15] = 1.0;
  1588. return this;
  1589. };
  1590. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1591. Quaternion.FromRotationMatrixToRef(matrix, this);
  1592. return this;
  1593. };
  1594. // Statics
  1595. Quaternion.FromRotationMatrix = function (matrix) {
  1596. var result = new Quaternion();
  1597. Quaternion.FromRotationMatrixToRef(matrix, result);
  1598. return result;
  1599. };
  1600. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1601. var data = matrix.m;
  1602. var m11 = data[0], m12 = data[4], m13 = data[8];
  1603. var m21 = data[1], m22 = data[5], m23 = data[9];
  1604. var m31 = data[2], m32 = data[6], m33 = data[10];
  1605. var trace = m11 + m22 + m33;
  1606. var s;
  1607. if (trace > 0) {
  1608. s = 0.5 / Math.sqrt(trace + 1.0);
  1609. result.w = 0.25 / s;
  1610. result.x = (m32 - m23) * s;
  1611. result.y = (m13 - m31) * s;
  1612. result.z = (m21 - m12) * s;
  1613. }
  1614. else if (m11 > m22 && m11 > m33) {
  1615. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1616. result.w = (m32 - m23) / s;
  1617. result.x = 0.25 * s;
  1618. result.y = (m12 + m21) / s;
  1619. result.z = (m13 + m31) / s;
  1620. }
  1621. else if (m22 > m33) {
  1622. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1623. result.w = (m13 - m31) / s;
  1624. result.x = (m12 + m21) / s;
  1625. result.y = 0.25 * s;
  1626. result.z = (m23 + m32) / s;
  1627. }
  1628. else {
  1629. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1630. result.w = (m21 - m12) / s;
  1631. result.x = (m13 + m31) / s;
  1632. result.y = (m23 + m32) / s;
  1633. result.z = 0.25 * s;
  1634. }
  1635. };
  1636. Quaternion.Inverse = function (q) {
  1637. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1638. };
  1639. Quaternion.Identity = function () {
  1640. return new Quaternion(0, 0, 0, 1);
  1641. };
  1642. Quaternion.RotationAxis = function (axis, angle) {
  1643. var result = new Quaternion();
  1644. var sin = Math.sin(angle / 2);
  1645. axis.normalize();
  1646. result.w = Math.cos(angle / 2);
  1647. result.x = axis.x * sin;
  1648. result.y = axis.y * sin;
  1649. result.z = axis.z * sin;
  1650. return result;
  1651. };
  1652. Quaternion.FromArray = function (array, offset) {
  1653. if (!offset) {
  1654. offset = 0;
  1655. }
  1656. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1657. };
  1658. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1659. var result = new Quaternion();
  1660. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1661. return result;
  1662. };
  1663. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1664. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1665. var halfRoll = roll * 0.5;
  1666. var halfPitch = pitch * 0.5;
  1667. var halfYaw = yaw * 0.5;
  1668. var sinRoll = Math.sin(halfRoll);
  1669. var cosRoll = Math.cos(halfRoll);
  1670. var sinPitch = Math.sin(halfPitch);
  1671. var cosPitch = Math.cos(halfPitch);
  1672. var sinYaw = Math.sin(halfYaw);
  1673. var cosYaw = Math.cos(halfYaw);
  1674. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1675. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1676. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1677. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1678. };
  1679. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1680. var result = new Quaternion();
  1681. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1682. return result;
  1683. };
  1684. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1685. // Produces a quaternion from Euler angles in the z-x-z orientation
  1686. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1687. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1688. var halfBeta = beta * 0.5;
  1689. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1690. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1691. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1692. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1693. };
  1694. Quaternion.Slerp = function (left, right, amount) {
  1695. var num2;
  1696. var num3;
  1697. var num = amount;
  1698. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1699. var flag = false;
  1700. if (num4 < 0) {
  1701. flag = true;
  1702. num4 = -num4;
  1703. }
  1704. if (num4 > 0.999999) {
  1705. num3 = 1 - num;
  1706. num2 = flag ? -num : num;
  1707. }
  1708. else {
  1709. var num5 = Math.acos(num4);
  1710. var num6 = (1.0 / Math.sin(num5));
  1711. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1712. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1713. }
  1714. 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));
  1715. };
  1716. return Quaternion;
  1717. })();
  1718. BABYLON.Quaternion = Quaternion;
  1719. var Matrix = (function () {
  1720. function Matrix() {
  1721. this.m = new Float32Array(16);
  1722. }
  1723. // Properties
  1724. Matrix.prototype.isIdentity = function () {
  1725. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1726. return false;
  1727. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1728. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1729. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1730. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1731. return false;
  1732. return true;
  1733. };
  1734. Matrix.prototype.determinant = function () {
  1735. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1736. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1737. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1738. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1739. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1740. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1741. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1742. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1743. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1744. };
  1745. // Methods
  1746. Matrix.prototype.toArray = function () {
  1747. return this.m;
  1748. };
  1749. Matrix.prototype.asArray = function () {
  1750. return this.toArray();
  1751. };
  1752. Matrix.prototype.invert = function () {
  1753. this.invertToRef(this);
  1754. return this;
  1755. };
  1756. Matrix.prototype.reset = function () {
  1757. for (var index = 0; index < 16; index++) {
  1758. this.m[index] = 0;
  1759. }
  1760. return this;
  1761. };
  1762. Matrix.prototype.add = function (other) {
  1763. var result = new Matrix();
  1764. this.addToRef(other, result);
  1765. return result;
  1766. };
  1767. Matrix.prototype.addToRef = function (other, result) {
  1768. for (var index = 0; index < 16; index++) {
  1769. result.m[index] = this.m[index] + other.m[index];
  1770. }
  1771. return this;
  1772. };
  1773. Matrix.prototype.addToSelf = function (other) {
  1774. for (var index = 0; index < 16; index++) {
  1775. this.m[index] += other.m[index];
  1776. }
  1777. return this;
  1778. };
  1779. Matrix.prototype.invertToRef = function (other) {
  1780. var l1 = this.m[0];
  1781. var l2 = this.m[1];
  1782. var l3 = this.m[2];
  1783. var l4 = this.m[3];
  1784. var l5 = this.m[4];
  1785. var l6 = this.m[5];
  1786. var l7 = this.m[6];
  1787. var l8 = this.m[7];
  1788. var l9 = this.m[8];
  1789. var l10 = this.m[9];
  1790. var l11 = this.m[10];
  1791. var l12 = this.m[11];
  1792. var l13 = this.m[12];
  1793. var l14 = this.m[13];
  1794. var l15 = this.m[14];
  1795. var l16 = this.m[15];
  1796. var l17 = (l11 * l16) - (l12 * l15);
  1797. var l18 = (l10 * l16) - (l12 * l14);
  1798. var l19 = (l10 * l15) - (l11 * l14);
  1799. var l20 = (l9 * l16) - (l12 * l13);
  1800. var l21 = (l9 * l15) - (l11 * l13);
  1801. var l22 = (l9 * l14) - (l10 * l13);
  1802. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1803. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1804. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1805. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1806. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1807. var l28 = (l7 * l16) - (l8 * l15);
  1808. var l29 = (l6 * l16) - (l8 * l14);
  1809. var l30 = (l6 * l15) - (l7 * l14);
  1810. var l31 = (l5 * l16) - (l8 * l13);
  1811. var l32 = (l5 * l15) - (l7 * l13);
  1812. var l33 = (l5 * l14) - (l6 * l13);
  1813. var l34 = (l7 * l12) - (l8 * l11);
  1814. var l35 = (l6 * l12) - (l8 * l10);
  1815. var l36 = (l6 * l11) - (l7 * l10);
  1816. var l37 = (l5 * l12) - (l8 * l9);
  1817. var l38 = (l5 * l11) - (l7 * l9);
  1818. var l39 = (l5 * l10) - (l6 * l9);
  1819. other.m[0] = l23 * l27;
  1820. other.m[4] = l24 * l27;
  1821. other.m[8] = l25 * l27;
  1822. other.m[12] = l26 * l27;
  1823. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1824. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1825. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1826. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1827. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1828. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1829. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1830. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1831. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1832. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1833. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1834. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1835. return this;
  1836. };
  1837. Matrix.prototype.setTranslation = function (vector3) {
  1838. this.m[12] = vector3.x;
  1839. this.m[13] = vector3.y;
  1840. this.m[14] = vector3.z;
  1841. return this;
  1842. };
  1843. Matrix.prototype.getTranslation = function () {
  1844. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1845. };
  1846. Matrix.prototype.multiply = function (other) {
  1847. var result = new Matrix();
  1848. this.multiplyToRef(other, result);
  1849. return result;
  1850. };
  1851. Matrix.prototype.copyFrom = function (other) {
  1852. for (var index = 0; index < 16; index++) {
  1853. this.m[index] = other.m[index];
  1854. }
  1855. return this;
  1856. };
  1857. Matrix.prototype.copyToArray = function (array, offset) {
  1858. if (offset === void 0) { offset = 0; }
  1859. for (var index = 0; index < 16; index++) {
  1860. array[offset + index] = this.m[index];
  1861. }
  1862. return this;
  1863. };
  1864. Matrix.prototype.multiplyToRef = function (other, result) {
  1865. this.multiplyToArray(other, result.m, 0);
  1866. return this;
  1867. };
  1868. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1869. var tm0 = this.m[0];
  1870. var tm1 = this.m[1];
  1871. var tm2 = this.m[2];
  1872. var tm3 = this.m[3];
  1873. var tm4 = this.m[4];
  1874. var tm5 = this.m[5];
  1875. var tm6 = this.m[6];
  1876. var tm7 = this.m[7];
  1877. var tm8 = this.m[8];
  1878. var tm9 = this.m[9];
  1879. var tm10 = this.m[10];
  1880. var tm11 = this.m[11];
  1881. var tm12 = this.m[12];
  1882. var tm13 = this.m[13];
  1883. var tm14 = this.m[14];
  1884. var tm15 = this.m[15];
  1885. var om0 = other.m[0];
  1886. var om1 = other.m[1];
  1887. var om2 = other.m[2];
  1888. var om3 = other.m[3];
  1889. var om4 = other.m[4];
  1890. var om5 = other.m[5];
  1891. var om6 = other.m[6];
  1892. var om7 = other.m[7];
  1893. var om8 = other.m[8];
  1894. var om9 = other.m[9];
  1895. var om10 = other.m[10];
  1896. var om11 = other.m[11];
  1897. var om12 = other.m[12];
  1898. var om13 = other.m[13];
  1899. var om14 = other.m[14];
  1900. var om15 = other.m[15];
  1901. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1902. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1903. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1904. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1905. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1906. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1907. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1908. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1909. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1910. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1911. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1912. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1913. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1914. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1915. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1916. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1917. return this;
  1918. };
  1919. Matrix.prototype.equals = function (value) {
  1920. return value &&
  1921. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1922. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1923. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1924. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1925. };
  1926. Matrix.prototype.clone = function () {
  1927. 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]);
  1928. };
  1929. Matrix.prototype.getClassName = function () {
  1930. return "Matrix";
  1931. };
  1932. Matrix.prototype.getHashCode = function () {
  1933. var hash = this.m[0] || 0;
  1934. for (var i = 1; i < 16; i++) {
  1935. hash = (hash * 397) ^ (this.m[i] || 0);
  1936. }
  1937. return hash;
  1938. };
  1939. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1940. translation.x = this.m[12];
  1941. translation.y = this.m[13];
  1942. translation.z = this.m[14];
  1943. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1944. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1945. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1946. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1947. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1948. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1949. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1950. rotation.x = 0;
  1951. rotation.y = 0;
  1952. rotation.z = 0;
  1953. rotation.w = 1;
  1954. return false;
  1955. }
  1956. 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);
  1957. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1958. return true;
  1959. };
  1960. // Statics
  1961. Matrix.FromArray = function (array, offset) {
  1962. var result = new Matrix();
  1963. if (!offset) {
  1964. offset = 0;
  1965. }
  1966. Matrix.FromArrayToRef(array, offset, result);
  1967. return result;
  1968. };
  1969. Matrix.FromArrayToRef = function (array, offset, result) {
  1970. for (var index = 0; index < 16; index++) {
  1971. result.m[index] = array[index + offset];
  1972. }
  1973. };
  1974. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1975. for (var index = 0; index < 16; index++) {
  1976. result.m[index] = array[index + offset] * scale;
  1977. }
  1978. };
  1979. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1980. result.m[0] = initialM11;
  1981. result.m[1] = initialM12;
  1982. result.m[2] = initialM13;
  1983. result.m[3] = initialM14;
  1984. result.m[4] = initialM21;
  1985. result.m[5] = initialM22;
  1986. result.m[6] = initialM23;
  1987. result.m[7] = initialM24;
  1988. result.m[8] = initialM31;
  1989. result.m[9] = initialM32;
  1990. result.m[10] = initialM33;
  1991. result.m[11] = initialM34;
  1992. result.m[12] = initialM41;
  1993. result.m[13] = initialM42;
  1994. result.m[14] = initialM43;
  1995. result.m[15] = initialM44;
  1996. };
  1997. Matrix.prototype.getRow = function (index) {
  1998. if (index < 0 || index > 3) {
  1999. return null;
  2000. }
  2001. var i = index * 4;
  2002. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2003. };
  2004. Matrix.prototype.setRow = function (index, row) {
  2005. if (index < 0 || index > 3) {
  2006. return this;
  2007. }
  2008. var i = index * 4;
  2009. this.m[i + 0] = row.x;
  2010. this.m[i + 1] = row.y;
  2011. this.m[i + 2] = row.z;
  2012. this.m[i + 3] = row.w;
  2013. return this;
  2014. };
  2015. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2016. var result = new Matrix();
  2017. result.m[0] = initialM11;
  2018. result.m[1] = initialM12;
  2019. result.m[2] = initialM13;
  2020. result.m[3] = initialM14;
  2021. result.m[4] = initialM21;
  2022. result.m[5] = initialM22;
  2023. result.m[6] = initialM23;
  2024. result.m[7] = initialM24;
  2025. result.m[8] = initialM31;
  2026. result.m[9] = initialM32;
  2027. result.m[10] = initialM33;
  2028. result.m[11] = initialM34;
  2029. result.m[12] = initialM41;
  2030. result.m[13] = initialM42;
  2031. result.m[14] = initialM43;
  2032. result.m[15] = initialM44;
  2033. return result;
  2034. };
  2035. Matrix.Compose = function (scale, rotation, translation) {
  2036. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2037. var rotationMatrix = Matrix.Identity();
  2038. rotation.toRotationMatrix(rotationMatrix);
  2039. result = result.multiply(rotationMatrix);
  2040. result.setTranslation(translation);
  2041. return result;
  2042. };
  2043. Matrix.Identity = function () {
  2044. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2045. };
  2046. Matrix.IdentityToRef = function (result) {
  2047. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2048. };
  2049. Matrix.Zero = function () {
  2050. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2051. };
  2052. Matrix.RotationX = function (angle) {
  2053. var result = new Matrix();
  2054. Matrix.RotationXToRef(angle, result);
  2055. return result;
  2056. };
  2057. Matrix.Invert = function (source) {
  2058. var result = new Matrix();
  2059. source.invertToRef(result);
  2060. return result;
  2061. };
  2062. Matrix.RotationXToRef = function (angle, result) {
  2063. var s = Math.sin(angle);
  2064. var c = Math.cos(angle);
  2065. result.m[0] = 1.0;
  2066. result.m[15] = 1.0;
  2067. result.m[5] = c;
  2068. result.m[10] = c;
  2069. result.m[9] = -s;
  2070. result.m[6] = s;
  2071. result.m[1] = 0;
  2072. result.m[2] = 0;
  2073. result.m[3] = 0;
  2074. result.m[4] = 0;
  2075. result.m[7] = 0;
  2076. result.m[8] = 0;
  2077. result.m[11] = 0;
  2078. result.m[12] = 0;
  2079. result.m[13] = 0;
  2080. result.m[14] = 0;
  2081. };
  2082. Matrix.RotationY = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationYToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.RotationYToRef = function (angle, result) {
  2088. var s = Math.sin(angle);
  2089. var c = Math.cos(angle);
  2090. result.m[5] = 1.0;
  2091. result.m[15] = 1.0;
  2092. result.m[0] = c;
  2093. result.m[2] = -s;
  2094. result.m[8] = s;
  2095. result.m[10] = c;
  2096. result.m[1] = 0;
  2097. result.m[3] = 0;
  2098. result.m[4] = 0;
  2099. result.m[6] = 0;
  2100. result.m[7] = 0;
  2101. result.m[9] = 0;
  2102. result.m[11] = 0;
  2103. result.m[12] = 0;
  2104. result.m[13] = 0;
  2105. result.m[14] = 0;
  2106. };
  2107. Matrix.RotationZ = function (angle) {
  2108. var result = new Matrix();
  2109. Matrix.RotationZToRef(angle, result);
  2110. return result;
  2111. };
  2112. Matrix.RotationZToRef = function (angle, result) {
  2113. var s = Math.sin(angle);
  2114. var c = Math.cos(angle);
  2115. result.m[10] = 1.0;
  2116. result.m[15] = 1.0;
  2117. result.m[0] = c;
  2118. result.m[1] = s;
  2119. result.m[4] = -s;
  2120. result.m[5] = c;
  2121. result.m[2] = 0;
  2122. result.m[3] = 0;
  2123. result.m[6] = 0;
  2124. result.m[7] = 0;
  2125. result.m[8] = 0;
  2126. result.m[9] = 0;
  2127. result.m[11] = 0;
  2128. result.m[12] = 0;
  2129. result.m[13] = 0;
  2130. result.m[14] = 0;
  2131. };
  2132. Matrix.RotationAxis = function (axis, angle) {
  2133. var result = Matrix.Zero();
  2134. Matrix.RotationAxisToRef(axis, angle, result);
  2135. return result;
  2136. };
  2137. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2138. var s = Math.sin(-angle);
  2139. var c = Math.cos(-angle);
  2140. var c1 = 1 - c;
  2141. axis.normalize();
  2142. result.m[0] = (axis.x * axis.x) * c1 + c;
  2143. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2144. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2145. result.m[3] = 0.0;
  2146. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2147. result.m[5] = (axis.y * axis.y) * c1 + c;
  2148. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2149. result.m[7] = 0.0;
  2150. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2151. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2152. result.m[10] = (axis.z * axis.z) * c1 + c;
  2153. result.m[11] = 0.0;
  2154. result.m[15] = 1.0;
  2155. };
  2156. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2157. var result = new Matrix();
  2158. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2159. return result;
  2160. };
  2161. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2162. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2163. this._tempQuaternion.toRotationMatrix(result);
  2164. };
  2165. Matrix.Scaling = function (x, y, z) {
  2166. var result = Matrix.Zero();
  2167. Matrix.ScalingToRef(x, y, z, result);
  2168. return result;
  2169. };
  2170. Matrix.ScalingToRef = function (x, y, z, result) {
  2171. result.m[0] = x;
  2172. result.m[1] = 0;
  2173. result.m[2] = 0;
  2174. result.m[3] = 0;
  2175. result.m[4] = 0;
  2176. result.m[5] = y;
  2177. result.m[6] = 0;
  2178. result.m[7] = 0;
  2179. result.m[8] = 0;
  2180. result.m[9] = 0;
  2181. result.m[10] = z;
  2182. result.m[11] = 0;
  2183. result.m[12] = 0;
  2184. result.m[13] = 0;
  2185. result.m[14] = 0;
  2186. result.m[15] = 1.0;
  2187. };
  2188. Matrix.Translation = function (x, y, z) {
  2189. var result = Matrix.Identity();
  2190. Matrix.TranslationToRef(x, y, z, result);
  2191. return result;
  2192. };
  2193. Matrix.TranslationToRef = function (x, y, z, result) {
  2194. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2195. };
  2196. Matrix.Lerp = function (startValue, endValue, gradient) {
  2197. var result = Matrix.Zero();
  2198. for (var index = 0; index < 16; index++) {
  2199. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2200. }
  2201. return result;
  2202. };
  2203. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2204. var startScale = new Vector3(0, 0, 0);
  2205. var startRotation = new Quaternion();
  2206. var startTranslation = new Vector3(0, 0, 0);
  2207. startValue.decompose(startScale, startRotation, startTranslation);
  2208. var endScale = new Vector3(0, 0, 0);
  2209. var endRotation = new Quaternion();
  2210. var endTranslation = new Vector3(0, 0, 0);
  2211. endValue.decompose(endScale, endRotation, endTranslation);
  2212. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2213. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2214. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2215. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2216. };
  2217. Matrix.LookAtLH = function (eye, target, up) {
  2218. var result = Matrix.Zero();
  2219. Matrix.LookAtLHToRef(eye, target, up, result);
  2220. return result;
  2221. };
  2222. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2223. // Z axis
  2224. target.subtractToRef(eye, this._zAxis);
  2225. this._zAxis.normalize();
  2226. // X axis
  2227. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2228. if (this._xAxis.lengthSquared() === 0) {
  2229. this._xAxis.x = 1.0;
  2230. }
  2231. else {
  2232. this._xAxis.normalize();
  2233. }
  2234. // Y axis
  2235. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2236. this._yAxis.normalize();
  2237. // Eye angles
  2238. var ex = -Vector3.Dot(this._xAxis, eye);
  2239. var ey = -Vector3.Dot(this._yAxis, eye);
  2240. var ez = -Vector3.Dot(this._zAxis, eye);
  2241. 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);
  2242. };
  2243. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2244. var matrix = Matrix.Zero();
  2245. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2246. return matrix;
  2247. };
  2248. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2249. var hw = 2.0 / width;
  2250. var hh = 2.0 / height;
  2251. var id = 1.0 / (zfar - znear);
  2252. var nid = znear / (znear - zfar);
  2253. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2254. };
  2255. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2256. var matrix = Matrix.Zero();
  2257. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2258. return matrix;
  2259. };
  2260. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2261. result.m[0] = 2.0 / (right - left);
  2262. result.m[1] = result.m[2] = result.m[3] = 0;
  2263. result.m[5] = 2.0 / (top - bottom);
  2264. result.m[4] = result.m[6] = result.m[7] = 0;
  2265. result.m[10] = -1.0 / (znear - zfar);
  2266. result.m[8] = result.m[9] = result.m[11] = 0;
  2267. result.m[12] = (left + right) / (left - right);
  2268. result.m[13] = (top + bottom) / (bottom - top);
  2269. result.m[14] = znear / (znear - zfar);
  2270. result.m[15] = 1.0;
  2271. };
  2272. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2273. var matrix = Matrix.Zero();
  2274. matrix.m[0] = (2.0 * znear) / width;
  2275. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2276. matrix.m[5] = (2.0 * znear) / height;
  2277. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2278. matrix.m[10] = -zfar / (znear - zfar);
  2279. matrix.m[8] = matrix.m[9] = 0.0;
  2280. matrix.m[11] = 1.0;
  2281. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2282. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2283. return matrix;
  2284. };
  2285. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2286. var matrix = Matrix.Zero();
  2287. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2288. return matrix;
  2289. };
  2290. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2291. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2292. var tan = 1.0 / (Math.tan(fov * 0.5));
  2293. if (isVerticalFovFixed) {
  2294. result.m[0] = tan / aspect;
  2295. }
  2296. else {
  2297. result.m[0] = tan;
  2298. }
  2299. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2300. if (isVerticalFovFixed) {
  2301. result.m[5] = tan;
  2302. }
  2303. else {
  2304. result.m[5] = tan * aspect;
  2305. }
  2306. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2307. result.m[8] = result.m[9] = 0.0;
  2308. result.m[10] = -zfar / (znear - zfar);
  2309. result.m[11] = 1.0;
  2310. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2311. result.m[14] = (znear * zfar) / (znear - zfar);
  2312. };
  2313. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2314. var cw = viewport.width;
  2315. var ch = viewport.height;
  2316. var cx = viewport.x;
  2317. var cy = viewport.y;
  2318. 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);
  2319. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2320. };
  2321. Matrix.GetAsMatrix2x2 = function (matrix) {
  2322. return new Float32Array([
  2323. matrix.m[0], matrix.m[1],
  2324. matrix.m[4], matrix.m[5]
  2325. ]);
  2326. };
  2327. Matrix.GetAsMatrix3x3 = function (matrix) {
  2328. return new Float32Array([
  2329. matrix.m[0], matrix.m[1], matrix.m[2],
  2330. matrix.m[4], matrix.m[5], matrix.m[6],
  2331. matrix.m[8], matrix.m[9], matrix.m[10]
  2332. ]);
  2333. };
  2334. Matrix.Transpose = function (matrix) {
  2335. var result = new Matrix();
  2336. result.m[0] = matrix.m[0];
  2337. result.m[1] = matrix.m[4];
  2338. result.m[2] = matrix.m[8];
  2339. result.m[3] = matrix.m[12];
  2340. result.m[4] = matrix.m[1];
  2341. result.m[5] = matrix.m[5];
  2342. result.m[6] = matrix.m[9];
  2343. result.m[7] = matrix.m[13];
  2344. result.m[8] = matrix.m[2];
  2345. result.m[9] = matrix.m[6];
  2346. result.m[10] = matrix.m[10];
  2347. result.m[11] = matrix.m[14];
  2348. result.m[12] = matrix.m[3];
  2349. result.m[13] = matrix.m[7];
  2350. result.m[14] = matrix.m[11];
  2351. result.m[15] = matrix.m[15];
  2352. return result;
  2353. };
  2354. Matrix.Reflection = function (plane) {
  2355. var matrix = new Matrix();
  2356. Matrix.ReflectionToRef(plane, matrix);
  2357. return matrix;
  2358. };
  2359. Matrix.ReflectionToRef = function (plane, result) {
  2360. plane.normalize();
  2361. var x = plane.normal.x;
  2362. var y = plane.normal.y;
  2363. var z = plane.normal.z;
  2364. var temp = -2 * x;
  2365. var temp2 = -2 * y;
  2366. var temp3 = -2 * z;
  2367. result.m[0] = (temp * x) + 1;
  2368. result.m[1] = temp2 * x;
  2369. result.m[2] = temp3 * x;
  2370. result.m[3] = 0.0;
  2371. result.m[4] = temp * y;
  2372. result.m[5] = (temp2 * y) + 1;
  2373. result.m[6] = temp3 * y;
  2374. result.m[7] = 0.0;
  2375. result.m[8] = temp * z;
  2376. result.m[9] = temp2 * z;
  2377. result.m[10] = (temp3 * z) + 1;
  2378. result.m[11] = 0.0;
  2379. result.m[12] = temp * plane.d;
  2380. result.m[13] = temp2 * plane.d;
  2381. result.m[14] = temp3 * plane.d;
  2382. result.m[15] = 1.0;
  2383. };
  2384. Matrix._tempQuaternion = new Quaternion();
  2385. Matrix._xAxis = Vector3.Zero();
  2386. Matrix._yAxis = Vector3.Zero();
  2387. Matrix._zAxis = Vector3.Zero();
  2388. return Matrix;
  2389. })();
  2390. BABYLON.Matrix = Matrix;
  2391. var Plane = (function () {
  2392. function Plane(a, b, c, d) {
  2393. this.normal = new Vector3(a, b, c);
  2394. this.d = d;
  2395. }
  2396. Plane.prototype.asArray = function () {
  2397. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2398. };
  2399. // Methods
  2400. Plane.prototype.clone = function () {
  2401. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2402. };
  2403. Plane.prototype.getClassName = function () {
  2404. return "Plane";
  2405. };
  2406. Plane.prototype.getHashCode = function () {
  2407. var hash = this.normal.getHashCode();
  2408. hash = (hash * 397) ^ (this.d || 0);
  2409. return hash;
  2410. };
  2411. Plane.prototype.normalize = function () {
  2412. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2413. var magnitude = 0;
  2414. if (norm !== 0) {
  2415. magnitude = 1.0 / norm;
  2416. }
  2417. this.normal.x *= magnitude;
  2418. this.normal.y *= magnitude;
  2419. this.normal.z *= magnitude;
  2420. this.d *= magnitude;
  2421. return this;
  2422. };
  2423. Plane.prototype.transform = function (transformation) {
  2424. var transposedMatrix = Matrix.Transpose(transformation);
  2425. var x = this.normal.x;
  2426. var y = this.normal.y;
  2427. var z = this.normal.z;
  2428. var d = this.d;
  2429. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2430. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2431. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2432. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2433. return new Plane(normalX, normalY, normalZ, finalD);
  2434. };
  2435. Plane.prototype.dotCoordinate = function (point) {
  2436. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2437. };
  2438. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2439. var x1 = point2.x - point1.x;
  2440. var y1 = point2.y - point1.y;
  2441. var z1 = point2.z - point1.z;
  2442. var x2 = point3.x - point1.x;
  2443. var y2 = point3.y - point1.y;
  2444. var z2 = point3.z - point1.z;
  2445. var yz = (y1 * z2) - (z1 * y2);
  2446. var xz = (z1 * x2) - (x1 * z2);
  2447. var xy = (x1 * y2) - (y1 * x2);
  2448. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2449. var invPyth;
  2450. if (pyth !== 0) {
  2451. invPyth = 1.0 / pyth;
  2452. }
  2453. else {
  2454. invPyth = 0;
  2455. }
  2456. this.normal.x = yz * invPyth;
  2457. this.normal.y = xz * invPyth;
  2458. this.normal.z = xy * invPyth;
  2459. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2460. return this;
  2461. };
  2462. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2463. var dot = Vector3.Dot(this.normal, direction);
  2464. return (dot <= epsilon);
  2465. };
  2466. Plane.prototype.signedDistanceTo = function (point) {
  2467. return Vector3.Dot(point, this.normal) + this.d;
  2468. };
  2469. // Statics
  2470. Plane.FromArray = function (array) {
  2471. return new Plane(array[0], array[1], array[2], array[3]);
  2472. };
  2473. Plane.FromPoints = function (point1, point2, point3) {
  2474. var result = new Plane(0, 0, 0, 0);
  2475. result.copyFromPoints(point1, point2, point3);
  2476. return result;
  2477. };
  2478. Plane.FromPositionAndNormal = function (origin, normal) {
  2479. var result = new Plane(0, 0, 0, 0);
  2480. normal.normalize();
  2481. result.normal = normal;
  2482. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2483. return result;
  2484. };
  2485. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2486. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2487. return Vector3.Dot(point, normal) + d;
  2488. };
  2489. return Plane;
  2490. })();
  2491. BABYLON.Plane = Plane;
  2492. var Viewport = (function () {
  2493. function Viewport(x, y, width, height) {
  2494. this.x = x;
  2495. this.y = y;
  2496. this.width = width;
  2497. this.height = height;
  2498. }
  2499. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2500. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2501. };
  2502. return Viewport;
  2503. })();
  2504. BABYLON.Viewport = Viewport;
  2505. var Frustum = (function () {
  2506. function Frustum() {
  2507. }
  2508. Frustum.GetPlanes = function (transform) {
  2509. var frustumPlanes = [];
  2510. for (var index = 0; index < 6; index++) {
  2511. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2512. }
  2513. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2514. return frustumPlanes;
  2515. };
  2516. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2517. // Near
  2518. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2519. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2520. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2521. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2522. frustumPlanes[0].normalize();
  2523. // Far
  2524. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2525. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2526. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2527. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2528. frustumPlanes[1].normalize();
  2529. // Left
  2530. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2531. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2532. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2533. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2534. frustumPlanes[2].normalize();
  2535. // Right
  2536. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2537. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2538. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2539. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2540. frustumPlanes[3].normalize();
  2541. // Top
  2542. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2543. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2544. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2545. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2546. frustumPlanes[4].normalize();
  2547. // Bottom
  2548. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2549. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2550. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2551. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2552. frustumPlanes[5].normalize();
  2553. };
  2554. return Frustum;
  2555. })();
  2556. BABYLON.Frustum = Frustum;
  2557. (function (Space) {
  2558. Space[Space["LOCAL"] = 0] = "LOCAL";
  2559. Space[Space["WORLD"] = 1] = "WORLD";
  2560. })(BABYLON.Space || (BABYLON.Space = {}));
  2561. var Space = BABYLON.Space;
  2562. var Axis = (function () {
  2563. function Axis() {
  2564. }
  2565. Axis.X = new Vector3(1, 0, 0);
  2566. Axis.Y = new Vector3(0, 1, 0);
  2567. Axis.Z = new Vector3(0, 0, 1);
  2568. return Axis;
  2569. })();
  2570. BABYLON.Axis = Axis;
  2571. ;
  2572. var BezierCurve = (function () {
  2573. function BezierCurve() {
  2574. }
  2575. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2576. // Extract X (which is equal to time here)
  2577. var f0 = 1 - 3 * x2 + 3 * x1;
  2578. var f1 = 3 * x2 - 6 * x1;
  2579. var f2 = 3 * x1;
  2580. var refinedT = t;
  2581. for (var i = 0; i < 5; i++) {
  2582. var refinedT2 = refinedT * refinedT;
  2583. var refinedT3 = refinedT2 * refinedT;
  2584. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2585. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2586. refinedT -= (x - t) * slope;
  2587. refinedT = Math.min(1, Math.max(0, refinedT));
  2588. }
  2589. // Resolve cubic bezier for the given x
  2590. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2591. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2592. Math.pow(refinedT, 3);
  2593. };
  2594. return BezierCurve;
  2595. })();
  2596. BABYLON.BezierCurve = BezierCurve;
  2597. (function (Orientation) {
  2598. Orientation[Orientation["CW"] = 0] = "CW";
  2599. Orientation[Orientation["CCW"] = 1] = "CCW";
  2600. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2601. var Orientation = BABYLON.Orientation;
  2602. var Angle = (function () {
  2603. function Angle(radians) {
  2604. var _this = this;
  2605. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2606. this.radians = function () { return _this._radians; };
  2607. this._radians = radians;
  2608. if (this._radians < 0)
  2609. this._radians += (2 * Math.PI);
  2610. }
  2611. Angle.BetweenTwoPoints = function (a, b) {
  2612. var delta = b.subtract(a);
  2613. var theta = Math.atan2(delta.y, delta.x);
  2614. return new Angle(theta);
  2615. };
  2616. Angle.FromRadians = function (radians) {
  2617. return new Angle(radians);
  2618. };
  2619. Angle.FromDegrees = function (degrees) {
  2620. return new Angle(degrees * Math.PI / 180);
  2621. };
  2622. return Angle;
  2623. })();
  2624. BABYLON.Angle = Angle;
  2625. var Arc2 = (function () {
  2626. function Arc2(startPoint, midPoint, endPoint) {
  2627. this.startPoint = startPoint;
  2628. this.midPoint = midPoint;
  2629. this.endPoint = endPoint;
  2630. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2631. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2632. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2633. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2634. 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);
  2635. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2636. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2637. var a1 = this.startAngle.degrees();
  2638. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2639. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2640. // angles correction
  2641. if (a2 - a1 > +180.0)
  2642. a2 -= 360.0;
  2643. if (a2 - a1 < -180.0)
  2644. a2 += 360.0;
  2645. if (a3 - a2 > +180.0)
  2646. a3 -= 360.0;
  2647. if (a3 - a2 < -180.0)
  2648. a3 += 360.0;
  2649. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2650. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2651. }
  2652. return Arc2;
  2653. })();
  2654. BABYLON.Arc2 = Arc2;
  2655. var Path2 = (function () {
  2656. function Path2(x, y) {
  2657. this._points = new Array();
  2658. this._length = 0;
  2659. this.closed = false;
  2660. this._points.push(new Vector2(x, y));
  2661. }
  2662. Path2.prototype.addLineTo = function (x, y) {
  2663. if (closed) {
  2664. //Tools.Error("cannot add lines to closed paths");
  2665. return this;
  2666. }
  2667. var newPoint = new Vector2(x, y);
  2668. var previousPoint = this._points[this._points.length - 1];
  2669. this._points.push(newPoint);
  2670. this._length += newPoint.subtract(previousPoint).length();
  2671. return this;
  2672. };
  2673. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2674. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2675. if (closed) {
  2676. //Tools.Error("cannot add arcs to closed paths");
  2677. return this;
  2678. }
  2679. var startPoint = this._points[this._points.length - 1];
  2680. var midPoint = new Vector2(midX, midY);
  2681. var endPoint = new Vector2(endX, endY);
  2682. var arc = new Arc2(startPoint, midPoint, endPoint);
  2683. var increment = arc.angle.radians() / numberOfSegments;
  2684. if (arc.orientation === Orientation.CW)
  2685. increment *= -1;
  2686. var currentAngle = arc.startAngle.radians() + increment;
  2687. for (var i = 0; i < numberOfSegments; i++) {
  2688. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2689. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2690. this.addLineTo(x, y);
  2691. currentAngle += increment;
  2692. }
  2693. return this;
  2694. };
  2695. Path2.prototype.close = function () {
  2696. this.closed = true;
  2697. return this;
  2698. };
  2699. Path2.prototype.length = function () {
  2700. var result = this._length;
  2701. if (!this.closed) {
  2702. var lastPoint = this._points[this._points.length - 1];
  2703. var firstPoint = this._points[0];
  2704. result += (firstPoint.subtract(lastPoint).length());
  2705. }
  2706. return result;
  2707. };
  2708. Path2.prototype.getPoints = function () {
  2709. return this._points;
  2710. };
  2711. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2712. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2713. //Tools.Error("normalized length position should be between 0 and 1.");
  2714. return Vector2.Zero();
  2715. }
  2716. var lengthPosition = normalizedLengthPosition * this.length();
  2717. var previousOffset = 0;
  2718. for (var i = 0; i < this._points.length; i++) {
  2719. var j = (i + 1) % this._points.length;
  2720. var a = this._points[i];
  2721. var b = this._points[j];
  2722. var bToA = b.subtract(a);
  2723. var nextOffset = (bToA.length() + previousOffset);
  2724. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2725. var dir = bToA.normalize();
  2726. var localOffset = lengthPosition - previousOffset;
  2727. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2728. }
  2729. previousOffset = nextOffset;
  2730. }
  2731. //Tools.Error("internal error");
  2732. return Vector2.Zero();
  2733. };
  2734. Path2.StartingAt = function (x, y) {
  2735. return new Path2(x, y);
  2736. };
  2737. return Path2;
  2738. })();
  2739. BABYLON.Path2 = Path2;
  2740. var Path3D = (function () {
  2741. /**
  2742. * new Path3D(path, normal, raw)
  2743. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2744. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2745. * path : an array of Vector3, the curve axis of the Path3D
  2746. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2747. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2748. */
  2749. function Path3D(path, firstNormal, raw) {
  2750. this.path = path;
  2751. this._curve = new Array();
  2752. this._distances = new Array();
  2753. this._tangents = new Array();
  2754. this._normals = new Array();
  2755. this._binormals = new Array();
  2756. for (var p = 0; p < path.length; p++) {
  2757. this._curve[p] = path[p].clone(); // hard copy
  2758. }
  2759. this._raw = raw || false;
  2760. this._compute(firstNormal);
  2761. }
  2762. /**
  2763. * Returns the Path3D array of successive Vector3 designing its curve.
  2764. */
  2765. Path3D.prototype.getCurve = function () {
  2766. return this._curve;
  2767. };
  2768. /**
  2769. * Returns an array populated with tangent vectors on each Path3D curve point.
  2770. */
  2771. Path3D.prototype.getTangents = function () {
  2772. return this._tangents;
  2773. };
  2774. /**
  2775. * Returns an array populated with normal vectors on each Path3D curve point.
  2776. */
  2777. Path3D.prototype.getNormals = function () {
  2778. return this._normals;
  2779. };
  2780. /**
  2781. * Returns an array populated with binormal vectors on each Path3D curve point.
  2782. */
  2783. Path3D.prototype.getBinormals = function () {
  2784. return this._binormals;
  2785. };
  2786. /**
  2787. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2788. */
  2789. Path3D.prototype.getDistances = function () {
  2790. return this._distances;
  2791. };
  2792. /**
  2793. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2794. * Returns the same object updated.
  2795. */
  2796. Path3D.prototype.update = function (path, firstNormal) {
  2797. for (var p = 0; p < path.length; p++) {
  2798. this._curve[p].x = path[p].x;
  2799. this._curve[p].y = path[p].y;
  2800. this._curve[p].z = path[p].z;
  2801. }
  2802. this._compute(firstNormal);
  2803. return this;
  2804. };
  2805. // private function compute() : computes tangents, normals and binormals
  2806. Path3D.prototype._compute = function (firstNormal) {
  2807. var l = this._curve.length;
  2808. // first and last tangents
  2809. this._tangents[0] = this._getFirstNonNullVector(0);
  2810. if (!this._raw) {
  2811. this._tangents[0].normalize();
  2812. }
  2813. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2814. if (!this._raw) {
  2815. this._tangents[l - 1].normalize();
  2816. }
  2817. // normals and binormals at first point : arbitrary vector with _normalVector()
  2818. var tg0 = this._tangents[0];
  2819. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2820. this._normals[0] = pp0;
  2821. if (!this._raw) {
  2822. this._normals[0].normalize();
  2823. }
  2824. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2825. if (!this._raw) {
  2826. this._binormals[0].normalize();
  2827. }
  2828. this._distances[0] = 0;
  2829. // normals and binormals : next points
  2830. var prev; // previous vector (segment)
  2831. var cur; // current vector (segment)
  2832. var curTang; // current tangent
  2833. // previous normal
  2834. var prevBinor; // previous binormal
  2835. for (var i = 1; i < l; i++) {
  2836. // tangents
  2837. prev = this._getLastNonNullVector(i);
  2838. if (i < l - 1) {
  2839. cur = this._getFirstNonNullVector(i);
  2840. this._tangents[i] = prev.add(cur);
  2841. this._tangents[i].normalize();
  2842. }
  2843. this._distances[i] = this._distances[i - 1] + prev.length();
  2844. // normals and binormals
  2845. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2846. curTang = this._tangents[i];
  2847. prevBinor = this._binormals[i - 1];
  2848. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2849. if (!this._raw) {
  2850. this._normals[i].normalize();
  2851. }
  2852. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2853. if (!this._raw) {
  2854. this._binormals[i].normalize();
  2855. }
  2856. }
  2857. };
  2858. // private function getFirstNonNullVector(index)
  2859. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2860. Path3D.prototype._getFirstNonNullVector = function (index) {
  2861. var i = 1;
  2862. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2863. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2864. i++;
  2865. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2866. }
  2867. return nNVector;
  2868. };
  2869. // private function getLastNonNullVector(index)
  2870. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2871. Path3D.prototype._getLastNonNullVector = function (index) {
  2872. var i = 1;
  2873. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2874. while (nLVector.length() === 0 && index > i + 1) {
  2875. i++;
  2876. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2877. }
  2878. return nLVector;
  2879. };
  2880. // private function normalVector(v0, vt, va) :
  2881. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2882. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2883. Path3D.prototype._normalVector = function (v0, vt, va) {
  2884. var normal0;
  2885. if (va === undefined || va === null) {
  2886. var point;
  2887. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2888. point = new Vector3(0, -1, 0);
  2889. }
  2890. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2891. point = new Vector3(1, 0, 0);
  2892. }
  2893. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2894. point = new Vector3(0, 0, 1);
  2895. }
  2896. normal0 = Vector3.Cross(vt, point);
  2897. }
  2898. else {
  2899. normal0 = Vector3.Cross(vt, va);
  2900. Vector3.CrossToRef(normal0, vt, normal0);
  2901. }
  2902. normal0.normalize();
  2903. return normal0;
  2904. };
  2905. return Path3D;
  2906. })();
  2907. BABYLON.Path3D = Path3D;
  2908. var Curve3 = (function () {
  2909. /**
  2910. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2911. * A Curve3 is designed from a series of successive Vector3.
  2912. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2913. */
  2914. function Curve3(points) {
  2915. this._length = 0;
  2916. this._points = points;
  2917. this._length = this._computeLength(points);
  2918. }
  2919. /**
  2920. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2921. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2922. * @param v1 (Vector3) the control point
  2923. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2924. * @param nbPoints (integer) the wanted number of points in the curve
  2925. */
  2926. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2927. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2928. var bez = new Array();
  2929. var equation = function (t, val0, val1, val2) {
  2930. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2931. return res;
  2932. };
  2933. for (var i = 0; i <= nbPoints; i++) {
  2934. 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)));
  2935. }
  2936. return new Curve3(bez);
  2937. };
  2938. /**
  2939. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2940. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2941. * @param v1 (Vector3) the first control point
  2942. * @param v2 (Vector3) the second control point
  2943. * @param v3 (Vector3) the end point of the Cubic Bezier
  2944. * @param nbPoints (integer) the wanted number of points in the curve
  2945. */
  2946. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2947. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2948. var bez = new Array();
  2949. var equation = function (t, val0, val1, val2, val3) {
  2950. 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;
  2951. return res;
  2952. };
  2953. for (var i = 0; i <= nbPoints; i++) {
  2954. 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)));
  2955. }
  2956. return new Curve3(bez);
  2957. };
  2958. /**
  2959. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2960. * @param p1 (Vector3) the origin point of the Hermite Spline
  2961. * @param t1 (Vector3) the tangent vector at the origin point
  2962. * @param p2 (Vector3) the end point of the Hermite Spline
  2963. * @param t2 (Vector3) the tangent vector at the end point
  2964. * @param nbPoints (integer) the wanted number of points in the curve
  2965. */
  2966. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2967. var hermite = new Array();
  2968. var step = 1 / nbPoints;
  2969. for (var i = 0; i <= nbPoints; i++) {
  2970. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2971. }
  2972. return new Curve3(hermite);
  2973. };
  2974. /**
  2975. * Returns the Curve3 stored array of successive Vector3
  2976. */
  2977. Curve3.prototype.getPoints = function () {
  2978. return this._points;
  2979. };
  2980. /**
  2981. * Returns the computed length (float) of the curve.
  2982. */
  2983. Curve3.prototype.length = function () {
  2984. return this._length;
  2985. };
  2986. /**
  2987. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2988. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2989. * curveA and curveB keep unchanged.
  2990. */
  2991. Curve3.prototype.continue = function (curve) {
  2992. var lastPoint = this._points[this._points.length - 1];
  2993. var continuedPoints = this._points.slice();
  2994. var curvePoints = curve.getPoints();
  2995. for (var i = 1; i < curvePoints.length; i++) {
  2996. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2997. }
  2998. var continuedCurve = new Curve3(continuedPoints);
  2999. return continuedCurve;
  3000. };
  3001. Curve3.prototype._computeLength = function (path) {
  3002. var l = 0;
  3003. for (var i = 1; i < path.length; i++) {
  3004. l += (path[i].subtract(path[i - 1])).length();
  3005. }
  3006. return l;
  3007. };
  3008. return Curve3;
  3009. })();
  3010. BABYLON.Curve3 = Curve3;
  3011. // SphericalHarmonics
  3012. var SphericalHarmonics = (function () {
  3013. function SphericalHarmonics() {
  3014. this.L00 = Vector3.Zero();
  3015. this.L1_1 = Vector3.Zero();
  3016. this.L10 = Vector3.Zero();
  3017. this.L11 = Vector3.Zero();
  3018. this.L2_2 = Vector3.Zero();
  3019. this.L2_1 = Vector3.Zero();
  3020. this.L20 = Vector3.Zero();
  3021. this.L21 = Vector3.Zero();
  3022. this.L22 = Vector3.Zero();
  3023. }
  3024. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3025. var colorVector = new Vector3(color.r, color.g, color.b);
  3026. var c = colorVector.scale(deltaSolidAngle);
  3027. this.L00 = this.L00.add(c.scale(0.282095));
  3028. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3029. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3030. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3031. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3032. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3033. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3034. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3035. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3036. };
  3037. SphericalHarmonics.prototype.scale = function (scale) {
  3038. this.L00 = this.L00.scale(scale);
  3039. this.L1_1 = this.L1_1.scale(scale);
  3040. this.L10 = this.L10.scale(scale);
  3041. this.L11 = this.L11.scale(scale);
  3042. this.L2_2 = this.L2_2.scale(scale);
  3043. this.L2_1 = this.L2_1.scale(scale);
  3044. this.L20 = this.L20.scale(scale);
  3045. this.L21 = this.L21.scale(scale);
  3046. this.L22 = this.L22.scale(scale);
  3047. };
  3048. return SphericalHarmonics;
  3049. })();
  3050. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3051. // SphericalPolynomial
  3052. var SphericalPolynomial = (function () {
  3053. function SphericalPolynomial() {
  3054. this.x = Vector3.Zero();
  3055. this.y = Vector3.Zero();
  3056. this.z = Vector3.Zero();
  3057. this.xx = Vector3.Zero();
  3058. this.yy = Vector3.Zero();
  3059. this.zz = Vector3.Zero();
  3060. this.xy = Vector3.Zero();
  3061. this.yz = Vector3.Zero();
  3062. this.zx = Vector3.Zero();
  3063. }
  3064. SphericalPolynomial.prototype.addAmbient = function (color) {
  3065. var colorVector = new Vector3(color.r, color.g, color.b);
  3066. this.xx = this.xx.add(colorVector);
  3067. this.yy = this.yy.add(colorVector);
  3068. this.zz = this.zz.add(colorVector);
  3069. };
  3070. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3071. var result = new SphericalPolynomial();
  3072. result.x = harmonics.L11.scale(1.02333);
  3073. result.y = harmonics.L1_1.scale(1.02333);
  3074. result.z = harmonics.L10.scale(1.02333);
  3075. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3076. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3077. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3078. result.yz = harmonics.L2_1.scale(0.858086);
  3079. result.zx = harmonics.L21.scale(0.858086);
  3080. result.xy = harmonics.L2_2.scale(0.858086);
  3081. return result;
  3082. };
  3083. return SphericalPolynomial;
  3084. })();
  3085. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3086. // Vertex formats
  3087. var PositionNormalVertex = (function () {
  3088. function PositionNormalVertex(position, normal) {
  3089. if (position === void 0) { position = Vector3.Zero(); }
  3090. if (normal === void 0) { normal = Vector3.Up(); }
  3091. this.position = position;
  3092. this.normal = normal;
  3093. }
  3094. PositionNormalVertex.prototype.clone = function () {
  3095. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3096. };
  3097. return PositionNormalVertex;
  3098. })();
  3099. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3100. var PositionNormalTextureVertex = (function () {
  3101. function PositionNormalTextureVertex(position, normal, uv) {
  3102. if (position === void 0) { position = Vector3.Zero(); }
  3103. if (normal === void 0) { normal = Vector3.Up(); }
  3104. if (uv === void 0) { uv = Vector2.Zero(); }
  3105. this.position = position;
  3106. this.normal = normal;
  3107. this.uv = uv;
  3108. }
  3109. PositionNormalTextureVertex.prototype.clone = function () {
  3110. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3111. };
  3112. return PositionNormalTextureVertex;
  3113. })();
  3114. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3115. // Temporary pre-allocated objects for engine internal use
  3116. // usage in any internal function :
  3117. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3118. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3119. var Tmp = (function () {
  3120. function Tmp() {
  3121. }
  3122. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3123. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3124. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3125. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3126. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3127. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3128. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3129. Matrix.Zero(), Matrix.Zero(),
  3130. Matrix.Zero(), Matrix.Zero(),
  3131. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3132. return Tmp;
  3133. })();
  3134. BABYLON.Tmp = Tmp;
  3135. })(BABYLON || (BABYLON = {}));
  3136. var BABYLON;
  3137. (function (BABYLON) {
  3138. function generateSerializableMember(type, sourceName) {
  3139. return function (target, propertyKey) {
  3140. if (!target.__serializableMembers) {
  3141. target.__serializableMembers = {};
  3142. }
  3143. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3144. };
  3145. }
  3146. function serialize(sourceName) {
  3147. return generateSerializableMember(0, sourceName); // value member
  3148. }
  3149. BABYLON.serialize = serialize;
  3150. function serializeAsTexture(sourceName) {
  3151. return generateSerializableMember(1, sourceName); // texture member
  3152. }
  3153. BABYLON.serializeAsTexture = serializeAsTexture;
  3154. function serializeAsColor3(sourceName) {
  3155. return generateSerializableMember(2, sourceName); // color3 member
  3156. }
  3157. BABYLON.serializeAsColor3 = serializeAsColor3;
  3158. function serializeAsFresnelParameters(sourceName) {
  3159. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3160. }
  3161. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3162. function serializeAsVector2(sourceName) {
  3163. return generateSerializableMember(4, sourceName); // vector2 member
  3164. }
  3165. BABYLON.serializeAsVector2 = serializeAsVector2;
  3166. function serializeAsVector3(sourceName) {
  3167. return generateSerializableMember(5, sourceName); // vector3 member
  3168. }
  3169. BABYLON.serializeAsVector3 = serializeAsVector3;
  3170. function serializeAsMeshReference(sourceName) {
  3171. return generateSerializableMember(6, sourceName); // mesh reference member
  3172. }
  3173. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3174. function serializeAsColorCurves(sourceName) {
  3175. return generateSerializableMember(7, sourceName); // color curves
  3176. }
  3177. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3178. var SerializationHelper = (function () {
  3179. function SerializationHelper() {
  3180. }
  3181. SerializationHelper.Serialize = function (entity, serializationObject) {
  3182. if (!serializationObject) {
  3183. serializationObject = {};
  3184. }
  3185. // Tags
  3186. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3187. // Properties
  3188. for (var property in entity.__serializableMembers) {
  3189. var propertyDescriptor = entity.__serializableMembers[property];
  3190. var targetPropertyName = propertyDescriptor.sourceName || property;
  3191. var propertyType = propertyDescriptor.type;
  3192. var sourceProperty = entity[property];
  3193. if (sourceProperty !== undefined && sourceProperty !== null) {
  3194. switch (propertyType) {
  3195. case 0:
  3196. serializationObject[targetPropertyName] = sourceProperty;
  3197. break;
  3198. case 1:
  3199. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3200. break;
  3201. case 2:
  3202. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3203. break;
  3204. case 3:
  3205. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3206. break;
  3207. case 4:
  3208. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3209. break;
  3210. case 5:
  3211. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3212. break;
  3213. case 6:
  3214. serializationObject[targetPropertyName] = sourceProperty.id;
  3215. break;
  3216. case 7:
  3217. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3218. break;
  3219. }
  3220. }
  3221. }
  3222. return serializationObject;
  3223. };
  3224. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3225. var destination = creationFunction();
  3226. // Tags
  3227. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3228. // Properties
  3229. for (var property in destination.__serializableMembers) {
  3230. var propertyDescriptor = destination.__serializableMembers[property];
  3231. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3232. var propertyType = propertyDescriptor.type;
  3233. if (sourceProperty !== undefined && sourceProperty !== null) {
  3234. switch (propertyType) {
  3235. case 0:
  3236. destination[property] = sourceProperty;
  3237. break;
  3238. case 1:
  3239. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3240. break;
  3241. case 2:
  3242. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3243. break;
  3244. case 3:
  3245. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3246. break;
  3247. case 4:
  3248. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3249. break;
  3250. case 5:
  3251. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3252. break;
  3253. case 6:
  3254. destination[property] = scene.getLastMeshByID(sourceProperty);
  3255. break;
  3256. case 7:
  3257. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3258. break;
  3259. }
  3260. }
  3261. }
  3262. return destination;
  3263. };
  3264. SerializationHelper.Clone = function (creationFunction, source) {
  3265. var destination = creationFunction();
  3266. // Tags
  3267. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3268. // Properties
  3269. for (var property in destination.__serializableMembers) {
  3270. var propertyDescriptor = destination.__serializableMembers[property];
  3271. var sourceProperty = source[property];
  3272. var propertyType = propertyDescriptor.type;
  3273. if (sourceProperty !== undefined && sourceProperty !== null) {
  3274. switch (propertyType) {
  3275. case 0: // Value
  3276. case 6:
  3277. destination[property] = sourceProperty;
  3278. break;
  3279. case 1: // Texture
  3280. case 2: // Color3
  3281. case 3: // FresnelParameters
  3282. case 4: // Vector2
  3283. case 5: // Vector3
  3284. case 7:
  3285. destination[property] = sourceProperty.clone();
  3286. break;
  3287. }
  3288. }
  3289. }
  3290. return destination;
  3291. };
  3292. return SerializationHelper;
  3293. })();
  3294. BABYLON.SerializationHelper = SerializationHelper;
  3295. })(BABYLON || (BABYLON = {}));
  3296. var BABYLON;
  3297. (function (BABYLON) {
  3298. /**
  3299. * A class serves as a medium between the observable and its observers
  3300. */
  3301. var EventState = (function () {
  3302. /**
  3303. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3304. */
  3305. function EventState(mask, skipNextObservers) {
  3306. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3307. this.mask = mask;
  3308. this.skipNextObservers = skipNextObservers;
  3309. }
  3310. return EventState;
  3311. })();
  3312. BABYLON.EventState = EventState;
  3313. /**
  3314. * Represent an Observer registered to a given Observable object.
  3315. */
  3316. var Observer = (function () {
  3317. function Observer(callback, mask) {
  3318. this.callback = callback;
  3319. this.mask = mask;
  3320. }
  3321. return Observer;
  3322. })();
  3323. BABYLON.Observer = Observer;
  3324. /**
  3325. * The Observable class is a simple implementation of the Observable pattern.
  3326. * 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.
  3327. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3328. * 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).
  3329. * 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.
  3330. */
  3331. var Observable = (function () {
  3332. function Observable() {
  3333. this._observers = new Array();
  3334. }
  3335. /**
  3336. * Create a new Observer with the specified callback
  3337. * @param callback the callback that will be executed for that Observer
  3338. * @param mask the mask used to filter observers
  3339. * @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.
  3340. */
  3341. Observable.prototype.add = function (callback, mask, insertFirst) {
  3342. if (mask === void 0) { mask = -1; }
  3343. if (insertFirst === void 0) { insertFirst = false; }
  3344. if (!callback) {
  3345. return null;
  3346. }
  3347. var observer = new Observer(callback, mask);
  3348. if (insertFirst) {
  3349. this._observers.unshift(observer);
  3350. }
  3351. else {
  3352. this._observers.push(observer);
  3353. }
  3354. return observer;
  3355. };
  3356. /**
  3357. * Remove an Observer from the Observable object
  3358. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3359. */
  3360. Observable.prototype.remove = function (observer) {
  3361. var index = this._observers.indexOf(observer);
  3362. if (index !== -1) {
  3363. this._observers.splice(index, 1);
  3364. return true;
  3365. }
  3366. return false;
  3367. };
  3368. /**
  3369. * Remove a callback from the Observable object
  3370. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3371. */
  3372. Observable.prototype.removeCallback = function (callback) {
  3373. for (var index = 0; index < this._observers.length; index++) {
  3374. if (this._observers[index].callback === callback) {
  3375. this._observers.splice(index, 1);
  3376. return true;
  3377. }
  3378. }
  3379. return false;
  3380. };
  3381. /**
  3382. * Notify all Observers by calling their respective callback with the given data
  3383. * @param eventData
  3384. * @param mask
  3385. */
  3386. Observable.prototype.notifyObservers = function (eventData, mask) {
  3387. if (mask === void 0) { mask = -1; }
  3388. var state = new EventState(mask);
  3389. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3390. var obs = _a[_i];
  3391. if (obs.mask & mask) {
  3392. obs.callback(eventData, state);
  3393. }
  3394. if (state.skipNextObservers) {
  3395. break;
  3396. }
  3397. }
  3398. };
  3399. /**
  3400. * return true is the Observable has at least one Observer registered
  3401. */
  3402. Observable.prototype.hasObservers = function () {
  3403. return this._observers.length > 0;
  3404. };
  3405. /**
  3406. * Clear the list of observers
  3407. */
  3408. Observable.prototype.clear = function () {
  3409. this._observers = new Array();
  3410. };
  3411. /**
  3412. * Clone the current observable
  3413. */
  3414. Observable.prototype.clone = function () {
  3415. var result = new Observable();
  3416. result._observers = this._observers.slice(0);
  3417. return result;
  3418. };
  3419. return Observable;
  3420. })();
  3421. BABYLON.Observable = Observable;
  3422. })(BABYLON || (BABYLON = {}));
  3423. var BABYLON;
  3424. (function (BABYLON) {
  3425. var Database = (function () {
  3426. function Database(urlToScene, callbackManifestChecked) {
  3427. // Handling various flavors of prefixed version of IndexedDB
  3428. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3429. this.callbackManifestChecked = callbackManifestChecked;
  3430. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3431. this.db = null;
  3432. this.enableSceneOffline = false;
  3433. this.enableTexturesOffline = false;
  3434. this.manifestVersionFound = 0;
  3435. this.mustUpdateRessources = false;
  3436. this.hasReachedQuota = false;
  3437. if (!Database.IDBStorageEnabled) {
  3438. this.callbackManifestChecked(true);
  3439. }
  3440. else {
  3441. this.checkManifestFile();
  3442. }
  3443. }
  3444. Database.prototype.checkManifestFile = function () {
  3445. var _this = this;
  3446. function noManifestFile() {
  3447. that.enableSceneOffline = false;
  3448. that.enableTexturesOffline = false;
  3449. that.callbackManifestChecked(false);
  3450. }
  3451. var that = this;
  3452. var timeStampUsed = false;
  3453. var manifestURL = this.currentSceneUrl + ".manifest";
  3454. var xhr = new XMLHttpRequest();
  3455. if (navigator.onLine) {
  3456. // Adding a timestamp to by-pass browsers' cache
  3457. timeStampUsed = true;
  3458. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3459. }
  3460. xhr.open("GET", manifestURL, true);
  3461. xhr.addEventListener("load", function () {
  3462. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3463. try {
  3464. var manifestFile = JSON.parse(xhr.response);
  3465. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3466. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3467. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3468. _this.manifestVersionFound = manifestFile.version;
  3469. }
  3470. if (_this.callbackManifestChecked) {
  3471. _this.callbackManifestChecked(true);
  3472. }
  3473. }
  3474. catch (ex) {
  3475. noManifestFile();
  3476. }
  3477. }
  3478. else {
  3479. noManifestFile();
  3480. }
  3481. }, false);
  3482. xhr.addEventListener("error", function (event) {
  3483. if (timeStampUsed) {
  3484. timeStampUsed = false;
  3485. // Let's retry without the timeStamp
  3486. // It could fail when coupled with HTML5 Offline API
  3487. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3488. xhr.open("GET", retryManifestURL, true);
  3489. xhr.send();
  3490. }
  3491. else {
  3492. noManifestFile();
  3493. }
  3494. }, false);
  3495. try {
  3496. xhr.send();
  3497. }
  3498. catch (ex) {
  3499. BABYLON.Tools.Error("Error on XHR send request.");
  3500. that.callbackManifestChecked(false);
  3501. }
  3502. };
  3503. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3504. var _this = this;
  3505. function handleError() {
  3506. that.isSupported = false;
  3507. if (errorCallback)
  3508. errorCallback();
  3509. }
  3510. var that = this;
  3511. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3512. // Your browser doesn't support IndexedDB
  3513. this.isSupported = false;
  3514. if (errorCallback)
  3515. errorCallback();
  3516. }
  3517. else {
  3518. // If the DB hasn't been opened or created yet
  3519. if (!this.db) {
  3520. this.hasReachedQuota = false;
  3521. this.isSupported = true;
  3522. var request = this.idbFactory.open("babylonjs", 1);
  3523. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3524. request.onerror = function (event) {
  3525. handleError();
  3526. };
  3527. // executes when a version change transaction cannot complete due to other active transactions
  3528. request.onblocked = function (event) {
  3529. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3530. handleError();
  3531. };
  3532. // DB has been opened successfully
  3533. request.onsuccess = function (event) {
  3534. _this.db = request.result;
  3535. successCallback();
  3536. };
  3537. // Initialization of the DB. Creating Scenes & Textures stores
  3538. request.onupgradeneeded = function (event) {
  3539. _this.db = (event.target).result;
  3540. try {
  3541. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3542. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3543. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3544. }
  3545. catch (ex) {
  3546. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3547. handleError();
  3548. }
  3549. };
  3550. }
  3551. else {
  3552. if (successCallback)
  3553. successCallback();
  3554. }
  3555. }
  3556. };
  3557. Database.prototype.loadImageFromDB = function (url, image) {
  3558. var _this = this;
  3559. var completeURL = Database.ReturnFullUrlLocation(url);
  3560. var saveAndLoadImage = function () {
  3561. if (!_this.hasReachedQuota && _this.db !== null) {
  3562. // the texture is not yet in the DB, let's try to save it
  3563. _this._saveImageIntoDBAsync(completeURL, image);
  3564. }
  3565. else {
  3566. image.src = url;
  3567. }
  3568. };
  3569. if (!this.mustUpdateRessources) {
  3570. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3571. }
  3572. else {
  3573. saveAndLoadImage();
  3574. }
  3575. };
  3576. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3577. if (this.isSupported && this.db !== null) {
  3578. var texture;
  3579. var transaction = this.db.transaction(["textures"]);
  3580. transaction.onabort = function (event) {
  3581. image.src = url;
  3582. };
  3583. transaction.oncomplete = function (event) {
  3584. var blobTextureURL;
  3585. if (texture) {
  3586. var URL = window.URL || window.webkitURL;
  3587. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3588. image.onerror = function () {
  3589. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3590. image.src = url;
  3591. };
  3592. image.src = blobTextureURL;
  3593. }
  3594. else {
  3595. notInDBCallback();
  3596. }
  3597. };
  3598. var getRequest = transaction.objectStore("textures").get(url);
  3599. getRequest.onsuccess = function (event) {
  3600. texture = (event.target).result;
  3601. };
  3602. getRequest.onerror = function (event) {
  3603. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3604. image.src = url;
  3605. };
  3606. }
  3607. else {
  3608. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3609. image.src = url;
  3610. }
  3611. };
  3612. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3613. var _this = this;
  3614. if (this.isSupported) {
  3615. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3616. var generateBlobUrl = function () {
  3617. var blobTextureURL;
  3618. if (blob) {
  3619. var URL = window.URL || window.webkitURL;
  3620. try {
  3621. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3622. }
  3623. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3624. catch (ex) {
  3625. blobTextureURL = URL.createObjectURL(blob);
  3626. }
  3627. }
  3628. image.src = blobTextureURL;
  3629. };
  3630. if (Database.IsUASupportingBlobStorage) {
  3631. var xhr = new XMLHttpRequest(), blob;
  3632. xhr.open("GET", url, true);
  3633. xhr.responseType = "blob";
  3634. xhr.addEventListener("load", function () {
  3635. if (xhr.status === 200) {
  3636. // Blob as response (XHR2)
  3637. blob = xhr.response;
  3638. var transaction = _this.db.transaction(["textures"], "readwrite");
  3639. // the transaction could abort because of a QuotaExceededError error
  3640. transaction.onabort = function (event) {
  3641. try {
  3642. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3643. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3644. this.hasReachedQuota = true;
  3645. }
  3646. }
  3647. catch (ex) { }
  3648. generateBlobUrl();
  3649. };
  3650. transaction.oncomplete = function (event) {
  3651. generateBlobUrl();
  3652. };
  3653. var newTexture = { textureUrl: url, data: blob };
  3654. try {
  3655. // Put the blob into the dabase
  3656. var addRequest = transaction.objectStore("textures").put(newTexture);
  3657. addRequest.onsuccess = function (event) {
  3658. };
  3659. addRequest.onerror = function (event) {
  3660. generateBlobUrl();
  3661. };
  3662. }
  3663. catch (ex) {
  3664. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3665. if (ex.code === 25) {
  3666. Database.IsUASupportingBlobStorage = false;
  3667. }
  3668. image.src = url;
  3669. }
  3670. }
  3671. else {
  3672. image.src = url;
  3673. }
  3674. }, false);
  3675. xhr.addEventListener("error", function (event) {
  3676. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3677. image.src = url;
  3678. }, false);
  3679. xhr.send();
  3680. }
  3681. else {
  3682. image.src = url;
  3683. }
  3684. }
  3685. else {
  3686. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3687. image.src = url;
  3688. }
  3689. };
  3690. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3691. var _this = this;
  3692. var updateVersion = function (event) {
  3693. // the version is not yet in the DB or we need to update it
  3694. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3695. };
  3696. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3697. };
  3698. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3699. var _this = this;
  3700. if (this.isSupported) {
  3701. var version;
  3702. try {
  3703. var transaction = this.db.transaction(["versions"]);
  3704. transaction.oncomplete = function (event) {
  3705. if (version) {
  3706. // If the version in the JSON file is > than the version in DB
  3707. if (_this.manifestVersionFound > version.data) {
  3708. _this.mustUpdateRessources = true;
  3709. updateInDBCallback();
  3710. }
  3711. else {
  3712. callback(version.data);
  3713. }
  3714. }
  3715. else {
  3716. _this.mustUpdateRessources = true;
  3717. updateInDBCallback();
  3718. }
  3719. };
  3720. transaction.onabort = function (event) {
  3721. callback(-1);
  3722. };
  3723. var getRequest = transaction.objectStore("versions").get(url);
  3724. getRequest.onsuccess = function (event) {
  3725. version = (event.target).result;
  3726. };
  3727. getRequest.onerror = function (event) {
  3728. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3729. callback(-1);
  3730. };
  3731. }
  3732. catch (ex) {
  3733. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3734. callback(-1);
  3735. }
  3736. }
  3737. else {
  3738. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3739. callback(-1);
  3740. }
  3741. };
  3742. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3743. var _this = this;
  3744. if (this.isSupported && !this.hasReachedQuota) {
  3745. try {
  3746. // Open a transaction to the database
  3747. var transaction = this.db.transaction(["versions"], "readwrite");
  3748. // the transaction could abort because of a QuotaExceededError error
  3749. transaction.onabort = function (event) {
  3750. try {
  3751. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3752. _this.hasReachedQuota = true;
  3753. }
  3754. }
  3755. catch (ex) { }
  3756. callback(-1);
  3757. };
  3758. transaction.oncomplete = function (event) {
  3759. callback(_this.manifestVersionFound);
  3760. };
  3761. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3762. // Put the scene into the database
  3763. var addRequest = transaction.objectStore("versions").put(newVersion);
  3764. addRequest.onsuccess = function (event) {
  3765. };
  3766. addRequest.onerror = function (event) {
  3767. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3768. };
  3769. }
  3770. catch (ex) {
  3771. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3772. callback(-1);
  3773. }
  3774. }
  3775. else {
  3776. callback(-1);
  3777. }
  3778. };
  3779. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3780. var _this = this;
  3781. var completeUrl = Database.ReturnFullUrlLocation(url);
  3782. var saveAndLoadFile = function (event) {
  3783. // the scene is not yet in the DB, let's try to save it
  3784. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3785. };
  3786. this._checkVersionFromDB(completeUrl, function (version) {
  3787. if (version !== -1) {
  3788. if (!_this.mustUpdateRessources) {
  3789. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3790. }
  3791. else {
  3792. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3793. }
  3794. }
  3795. else {
  3796. errorCallback();
  3797. }
  3798. });
  3799. };
  3800. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3801. if (this.isSupported) {
  3802. var targetStore;
  3803. if (url.indexOf(".babylon") !== -1) {
  3804. targetStore = "scenes";
  3805. }
  3806. else {
  3807. targetStore = "textures";
  3808. }
  3809. var file;
  3810. var transaction = this.db.transaction([targetStore]);
  3811. transaction.oncomplete = function (event) {
  3812. if (file) {
  3813. callback(file.data);
  3814. }
  3815. else {
  3816. notInDBCallback();
  3817. }
  3818. };
  3819. transaction.onabort = function (event) {
  3820. notInDBCallback();
  3821. };
  3822. var getRequest = transaction.objectStore(targetStore).get(url);
  3823. getRequest.onsuccess = function (event) {
  3824. file = (event.target).result;
  3825. };
  3826. getRequest.onerror = function (event) {
  3827. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3828. notInDBCallback();
  3829. };
  3830. }
  3831. else {
  3832. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3833. callback();
  3834. }
  3835. };
  3836. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3837. var _this = this;
  3838. if (this.isSupported) {
  3839. var targetStore;
  3840. if (url.indexOf(".babylon") !== -1) {
  3841. targetStore = "scenes";
  3842. }
  3843. else {
  3844. targetStore = "textures";
  3845. }
  3846. // Create XHR
  3847. var xhr = new XMLHttpRequest(), fileData;
  3848. xhr.open("GET", url, true);
  3849. if (useArrayBuffer) {
  3850. xhr.responseType = "arraybuffer";
  3851. }
  3852. xhr.onprogress = progressCallback;
  3853. xhr.addEventListener("load", function () {
  3854. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3855. // Blob as response (XHR2)
  3856. //fileData = xhr.responseText;
  3857. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3858. if (!_this.hasReachedQuota) {
  3859. // Open a transaction to the database
  3860. var transaction = _this.db.transaction([targetStore], "readwrite");
  3861. // the transaction could abort because of a QuotaExceededError error
  3862. transaction.onabort = function (event) {
  3863. try {
  3864. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3865. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3866. this.hasReachedQuota = true;
  3867. }
  3868. }
  3869. catch (ex) { }
  3870. callback(fileData);
  3871. };
  3872. transaction.oncomplete = function (event) {
  3873. callback(fileData);
  3874. };
  3875. var newFile;
  3876. if (targetStore === "scenes") {
  3877. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3878. }
  3879. else {
  3880. newFile = { textureUrl: url, data: fileData };
  3881. }
  3882. try {
  3883. // Put the scene into the database
  3884. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3885. addRequest.onsuccess = function (event) {
  3886. };
  3887. addRequest.onerror = function (event) {
  3888. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3889. };
  3890. }
  3891. catch (ex) {
  3892. callback(fileData);
  3893. }
  3894. }
  3895. else {
  3896. callback(fileData);
  3897. }
  3898. }
  3899. else {
  3900. callback();
  3901. }
  3902. }, false);
  3903. xhr.addEventListener("error", function (event) {
  3904. BABYLON.Tools.Error("error on XHR request.");
  3905. callback();
  3906. }, false);
  3907. xhr.send();
  3908. }
  3909. else {
  3910. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3911. callback();
  3912. }
  3913. };
  3914. Database.IsUASupportingBlobStorage = true;
  3915. Database.IDBStorageEnabled = true;
  3916. Database.parseURL = function (url) {
  3917. var a = document.createElement('a');
  3918. a.href = url;
  3919. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3920. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3921. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3922. return absLocation;
  3923. };
  3924. Database.ReturnFullUrlLocation = function (url) {
  3925. if (url.indexOf("http:/") === -1) {
  3926. return (Database.parseURL(window.location.href) + url);
  3927. }
  3928. else {
  3929. return url;
  3930. }
  3931. };
  3932. return Database;
  3933. })();
  3934. BABYLON.Database = Database;
  3935. })(BABYLON || (BABYLON = {}));
  3936. var BABYLON;
  3937. (function (BABYLON) {
  3938. var Internals;
  3939. (function (Internals) {
  3940. /*
  3941. * Based on jsTGALoader - Javascript loader for TGA file
  3942. * By Vincent Thibault
  3943. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3944. */
  3945. var TGATools = (function () {
  3946. function TGATools() {
  3947. }
  3948. TGATools.GetTGAHeader = function (data) {
  3949. var offset = 0;
  3950. var header = {
  3951. id_length: data[offset++],
  3952. colormap_type: data[offset++],
  3953. image_type: data[offset++],
  3954. colormap_index: data[offset++] | data[offset++] << 8,
  3955. colormap_length: data[offset++] | data[offset++] << 8,
  3956. colormap_size: data[offset++],
  3957. origin: [
  3958. data[offset++] | data[offset++] << 8,
  3959. data[offset++] | data[offset++] << 8
  3960. ],
  3961. width: data[offset++] | data[offset++] << 8,
  3962. height: data[offset++] | data[offset++] << 8,
  3963. pixel_size: data[offset++],
  3964. flags: data[offset++]
  3965. };
  3966. return header;
  3967. };
  3968. TGATools.UploadContent = function (gl, data) {
  3969. // Not enough data to contain header ?
  3970. if (data.length < 19) {
  3971. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3972. return;
  3973. }
  3974. // Read Header
  3975. var offset = 18;
  3976. var header = TGATools.GetTGAHeader(data);
  3977. // Assume it's a valid Targa file.
  3978. if (header.id_length + offset > data.length) {
  3979. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3980. return;
  3981. }
  3982. // Skip not needed data
  3983. offset += header.id_length;
  3984. var use_rle = false;
  3985. var use_pal = false;
  3986. var use_rgb = false;
  3987. var use_grey = false;
  3988. // Get some informations.
  3989. switch (header.image_type) {
  3990. case TGATools._TYPE_RLE_INDEXED:
  3991. use_rle = true;
  3992. case TGATools._TYPE_INDEXED:
  3993. use_pal = true;
  3994. break;
  3995. case TGATools._TYPE_RLE_RGB:
  3996. use_rle = true;
  3997. case TGATools._TYPE_RGB:
  3998. use_rgb = true;
  3999. break;
  4000. case TGATools._TYPE_RLE_GREY:
  4001. use_rle = true;
  4002. case TGATools._TYPE_GREY:
  4003. use_grey = true;
  4004. break;
  4005. }
  4006. var pixel_data;
  4007. var numAlphaBits = header.flags & 0xf;
  4008. var pixel_size = header.pixel_size >> 3;
  4009. var pixel_total = header.width * header.height * pixel_size;
  4010. // Read palettes
  4011. var palettes;
  4012. if (use_pal) {
  4013. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4014. }
  4015. // Read LRE
  4016. if (use_rle) {
  4017. pixel_data = new Uint8Array(pixel_total);
  4018. var c, count, i;
  4019. var localOffset = 0;
  4020. var pixels = new Uint8Array(pixel_size);
  4021. while (offset < pixel_total && localOffset < pixel_total) {
  4022. c = data[offset++];
  4023. count = (c & 0x7f) + 1;
  4024. // RLE pixels
  4025. if (c & 0x80) {
  4026. // Bind pixel tmp array
  4027. for (i = 0; i < pixel_size; ++i) {
  4028. pixels[i] = data[offset++];
  4029. }
  4030. // Copy pixel array
  4031. for (i = 0; i < count; ++i) {
  4032. pixel_data.set(pixels, localOffset + i * pixel_size);
  4033. }
  4034. localOffset += pixel_size * count;
  4035. }
  4036. else {
  4037. count *= pixel_size;
  4038. for (i = 0; i < count; ++i) {
  4039. pixel_data[localOffset + i] = data[offset++];
  4040. }
  4041. localOffset += count;
  4042. }
  4043. }
  4044. }
  4045. else {
  4046. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4047. }
  4048. // Load to texture
  4049. var x_start, y_start, x_step, y_step, y_end, x_end;
  4050. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4051. default:
  4052. case TGATools._ORIGIN_UL:
  4053. x_start = 0;
  4054. x_step = 1;
  4055. x_end = header.width;
  4056. y_start = 0;
  4057. y_step = 1;
  4058. y_end = header.height;
  4059. break;
  4060. case TGATools._ORIGIN_BL:
  4061. x_start = 0;
  4062. x_step = 1;
  4063. x_end = header.width;
  4064. y_start = header.height - 1;
  4065. y_step = -1;
  4066. y_end = -1;
  4067. break;
  4068. case TGATools._ORIGIN_UR:
  4069. x_start = header.width - 1;
  4070. x_step = -1;
  4071. x_end = -1;
  4072. y_start = 0;
  4073. y_step = 1;
  4074. y_end = header.height;
  4075. break;
  4076. case TGATools._ORIGIN_BR:
  4077. x_start = header.width - 1;
  4078. x_step = -1;
  4079. x_end = -1;
  4080. y_start = header.height - 1;
  4081. y_step = -1;
  4082. y_end = -1;
  4083. break;
  4084. }
  4085. // Load the specify method
  4086. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4087. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4088. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4089. };
  4090. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4091. var image = pixel_data, colormap = palettes;
  4092. var width = header.width, height = header.height;
  4093. var color, i = 0, x, y;
  4094. var imageData = new Uint8Array(width * height * 4);
  4095. for (y = y_start; y !== y_end; y += y_step) {
  4096. for (x = x_start; x !== x_end; x += x_step, i++) {
  4097. color = image[i];
  4098. imageData[(x + width * y) * 4 + 3] = 255;
  4099. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4100. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4101. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4102. }
  4103. }
  4104. return imageData;
  4105. };
  4106. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4107. var image = pixel_data;
  4108. var width = header.width, height = header.height;
  4109. var color, i = 0, x, y;
  4110. var imageData = new Uint8Array(width * height * 4);
  4111. for (y = y_start; y !== y_end; y += y_step) {
  4112. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4113. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4114. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4115. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4116. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4117. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4118. }
  4119. }
  4120. return imageData;
  4121. };
  4122. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4123. var image = pixel_data;
  4124. var width = header.width, height = header.height;
  4125. var i = 0, x, y;
  4126. var imageData = new Uint8Array(width * height * 4);
  4127. for (y = y_start; y !== y_end; y += y_step) {
  4128. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4129. imageData[(x + width * y) * 4 + 3] = 255;
  4130. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4131. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4132. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4133. }
  4134. }
  4135. return imageData;
  4136. };
  4137. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4138. var image = pixel_data;
  4139. var width = header.width, height = header.height;
  4140. var i = 0, x, y;
  4141. var imageData = new Uint8Array(width * height * 4);
  4142. for (y = y_start; y !== y_end; y += y_step) {
  4143. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4144. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4145. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4146. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4147. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4148. }
  4149. }
  4150. return imageData;
  4151. };
  4152. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4153. var image = pixel_data;
  4154. var width = header.width, height = header.height;
  4155. var color, i = 0, x, y;
  4156. var imageData = new Uint8Array(width * height * 4);
  4157. for (y = y_start; y !== y_end; y += y_step) {
  4158. for (x = x_start; x !== x_end; x += x_step, i++) {
  4159. color = image[i];
  4160. imageData[(x + width * y) * 4 + 0] = color;
  4161. imageData[(x + width * y) * 4 + 1] = color;
  4162. imageData[(x + width * y) * 4 + 2] = color;
  4163. imageData[(x + width * y) * 4 + 3] = 255;
  4164. }
  4165. }
  4166. return imageData;
  4167. };
  4168. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4169. var image = pixel_data;
  4170. var width = header.width, height = header.height;
  4171. var i = 0, x, y;
  4172. var imageData = new Uint8Array(width * height * 4);
  4173. for (y = y_start; y !== y_end; y += y_step) {
  4174. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4175. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4176. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4177. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4178. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4179. }
  4180. }
  4181. return imageData;
  4182. };
  4183. TGATools._TYPE_NO_DATA = 0;
  4184. TGATools._TYPE_INDEXED = 1;
  4185. TGATools._TYPE_RGB = 2;
  4186. TGATools._TYPE_GREY = 3;
  4187. TGATools._TYPE_RLE_INDEXED = 9;
  4188. TGATools._TYPE_RLE_RGB = 10;
  4189. TGATools._TYPE_RLE_GREY = 11;
  4190. TGATools._ORIGIN_MASK = 0x30;
  4191. TGATools._ORIGIN_SHIFT = 0x04;
  4192. TGATools._ORIGIN_BL = 0x00;
  4193. TGATools._ORIGIN_BR = 0x01;
  4194. TGATools._ORIGIN_UL = 0x02;
  4195. TGATools._ORIGIN_UR = 0x03;
  4196. return TGATools;
  4197. })();
  4198. Internals.TGATools = TGATools;
  4199. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4200. })(BABYLON || (BABYLON = {}));
  4201. var BABYLON;
  4202. (function (BABYLON) {
  4203. var SmartArray = (function () {
  4204. function SmartArray(capacity) {
  4205. this.length = 0;
  4206. this._duplicateId = 0;
  4207. this.data = new Array(capacity);
  4208. this._id = SmartArray._GlobalId++;
  4209. }
  4210. SmartArray.prototype.push = function (value) {
  4211. this.data[this.length++] = value;
  4212. if (this.length > this.data.length) {
  4213. this.data.length *= 2;
  4214. }
  4215. if (!value.__smartArrayFlags) {
  4216. value.__smartArrayFlags = {};
  4217. }
  4218. value.__smartArrayFlags[this._id] = this._duplicateId;
  4219. };
  4220. SmartArray.prototype.pushNoDuplicate = function (value) {
  4221. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4222. return;
  4223. }
  4224. this.push(value);
  4225. };
  4226. SmartArray.prototype.sort = function (compareFn) {
  4227. this.data.sort(compareFn);
  4228. };
  4229. SmartArray.prototype.reset = function () {
  4230. this.length = 0;
  4231. this._duplicateId++;
  4232. };
  4233. SmartArray.prototype.concat = function (array) {
  4234. if (array.length === 0) {
  4235. return;
  4236. }
  4237. if (this.length + array.length > this.data.length) {
  4238. this.data.length = (this.length + array.length) * 2;
  4239. }
  4240. for (var index = 0; index < array.length; index++) {
  4241. this.data[this.length++] = (array.data || array)[index];
  4242. }
  4243. };
  4244. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4245. if (array.length === 0) {
  4246. return;
  4247. }
  4248. if (this.length + array.length > this.data.length) {
  4249. this.data.length = (this.length + array.length) * 2;
  4250. }
  4251. for (var index = 0; index < array.length; index++) {
  4252. var item = (array.data || array)[index];
  4253. this.pushNoDuplicate(item);
  4254. }
  4255. };
  4256. SmartArray.prototype.indexOf = function (value) {
  4257. var position = this.data.indexOf(value);
  4258. if (position >= this.length) {
  4259. return -1;
  4260. }
  4261. return position;
  4262. };
  4263. // Statics
  4264. SmartArray._GlobalId = 0;
  4265. return SmartArray;
  4266. })();
  4267. BABYLON.SmartArray = SmartArray;
  4268. })(BABYLON || (BABYLON = {}));
  4269. var BABYLON;
  4270. (function (BABYLON) {
  4271. /**
  4272. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4273. * The underlying implementation relies on an associative array to ensure the best performances.
  4274. * The value can be anything including 'null' but except 'undefined'
  4275. */
  4276. var StringDictionary = (function () {
  4277. function StringDictionary() {
  4278. this._count = 0;
  4279. this._data = {};
  4280. }
  4281. /**
  4282. * Get a value based from its key
  4283. * @param key the given key to get the matching value from
  4284. * @return the value if found, otherwise undefined is returned
  4285. */
  4286. StringDictionary.prototype.get = function (key) {
  4287. var val = this._data[key];
  4288. if (val !== undefined) {
  4289. return val;
  4290. }
  4291. return undefined;
  4292. };
  4293. /**
  4294. * Get a value from its key or add it if it doesn't exist.
  4295. * This method will ensure you that a given key/data will be present in the dictionary.
  4296. * @param key the given key to get the matching value from
  4297. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4298. * The factory will only be invoked if there's no data for the given key.
  4299. * @return the value corresponding to the key.
  4300. */
  4301. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4302. var val = this.get(key);
  4303. if (val !== undefined) {
  4304. return val;
  4305. }
  4306. val = factory(key);
  4307. if (val) {
  4308. this.add(key, val);
  4309. }
  4310. return val;
  4311. };
  4312. /**
  4313. * Get a value from its key if present in the dictionary otherwise add it
  4314. * @param key the key to get the value from
  4315. * @param val if there's no such key/value pair in the dictionary add it with this value
  4316. * @return the value corresponding to the key
  4317. */
  4318. StringDictionary.prototype.getOrAdd = function (key, val) {
  4319. var curVal = this.get(key);
  4320. if (curVal !== undefined) {
  4321. return curVal;
  4322. }
  4323. this.add(key, val);
  4324. return val;
  4325. };
  4326. /**
  4327. * Check if there's a given key in the dictionary
  4328. * @param key the key to check for
  4329. * @return true if the key is present, false otherwise
  4330. */
  4331. StringDictionary.prototype.contains = function (key) {
  4332. return this._data[key] !== undefined;
  4333. };
  4334. /**
  4335. * Add a new key and its corresponding value
  4336. * @param key the key to add
  4337. * @param value the value corresponding to the key
  4338. * @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
  4339. */
  4340. StringDictionary.prototype.add = function (key, value) {
  4341. if (this._data[key] !== undefined) {
  4342. return false;
  4343. }
  4344. this._data[key] = value;
  4345. ++this._count;
  4346. return true;
  4347. };
  4348. StringDictionary.prototype.set = function (key, value) {
  4349. if (this._data[key] === undefined) {
  4350. return false;
  4351. }
  4352. this._data[key] = value;
  4353. return true;
  4354. };
  4355. /**
  4356. * Remove a key/value from the dictionary.
  4357. * @param key the key to remove
  4358. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4359. */
  4360. StringDictionary.prototype.remove = function (key) {
  4361. if (this.contains(key)) {
  4362. delete this._data[key];
  4363. --this._count;
  4364. return true;
  4365. }
  4366. return false;
  4367. };
  4368. /**
  4369. * Clear the whole content of the dictionary
  4370. */
  4371. StringDictionary.prototype.clear = function () {
  4372. this._data = {};
  4373. this._count = 0;
  4374. };
  4375. Object.defineProperty(StringDictionary.prototype, "count", {
  4376. get: function () {
  4377. return this._count;
  4378. },
  4379. enumerable: true,
  4380. configurable: true
  4381. });
  4382. /**
  4383. * Execute a callback on each key/val of the dictionary.
  4384. * Note that you can remove any element in this dictionary in the callback implementation
  4385. * @param callback the callback to execute on a given key/value pair
  4386. */
  4387. StringDictionary.prototype.forEach = function (callback) {
  4388. for (var cur in this._data) {
  4389. var val = this._data[cur];
  4390. callback(cur, val);
  4391. }
  4392. };
  4393. /**
  4394. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4395. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4396. * Note that you can remove any element in this dictionary in the callback implementation
  4397. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4398. */
  4399. StringDictionary.prototype.first = function (callback) {
  4400. for (var cur in this._data) {
  4401. var val = this._data[cur];
  4402. var res = callback(cur, val);
  4403. if (res) {
  4404. return res;
  4405. }
  4406. }
  4407. return null;
  4408. };
  4409. return StringDictionary;
  4410. })();
  4411. BABYLON.StringDictionary = StringDictionary;
  4412. })(BABYLON || (BABYLON = {}));
  4413. var BABYLON;
  4414. (function (BABYLON) {
  4415. // Screenshots
  4416. var screenshotCanvas;
  4417. var cloneValue = function (source, destinationObject) {
  4418. if (!source)
  4419. return null;
  4420. if (source instanceof BABYLON.Mesh) {
  4421. return null;
  4422. }
  4423. if (source instanceof BABYLON.SubMesh) {
  4424. return source.clone(destinationObject);
  4425. }
  4426. else if (source.clone) {
  4427. return source.clone();
  4428. }
  4429. return null;
  4430. };
  4431. var Tools = (function () {
  4432. function Tools() {
  4433. }
  4434. Tools.Instantiate = function (className) {
  4435. var arr = className.split(".");
  4436. var fn = (window || this);
  4437. for (var i = 0, len = arr.length; i < len; i++) {
  4438. fn = fn[arr[i]];
  4439. }
  4440. if (typeof fn !== "function") {
  4441. return null;
  4442. }
  4443. return fn;
  4444. };
  4445. Tools.SetImmediate = function (action) {
  4446. if (window.setImmediate) {
  4447. window.setImmediate(action);
  4448. }
  4449. else {
  4450. setTimeout(action, 1);
  4451. }
  4452. };
  4453. Tools.IsExponentOfTwo = function (value) {
  4454. var count = 1;
  4455. do {
  4456. count *= 2;
  4457. } while (count < value);
  4458. return count === value;
  4459. };
  4460. Tools.GetExponentOfTwo = function (value, max) {
  4461. var count = 1;
  4462. do {
  4463. count *= 2;
  4464. } while (count < value);
  4465. if (count > max)
  4466. count = max;
  4467. return count;
  4468. };
  4469. Tools.GetFilename = function (path) {
  4470. var index = path.lastIndexOf("/");
  4471. if (index < 0)
  4472. return path;
  4473. return path.substring(index + 1);
  4474. };
  4475. Tools.GetDOMTextContent = function (element) {
  4476. var result = "";
  4477. var child = element.firstChild;
  4478. while (child) {
  4479. if (child.nodeType === 3) {
  4480. result += child.textContent;
  4481. }
  4482. child = child.nextSibling;
  4483. }
  4484. return result;
  4485. };
  4486. Tools.ToDegrees = function (angle) {
  4487. return angle * 180 / Math.PI;
  4488. };
  4489. Tools.ToRadians = function (angle) {
  4490. return angle * Math.PI / 180;
  4491. };
  4492. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4493. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4494. var output = "";
  4495. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4496. var i = 0;
  4497. var bytes = new Uint8Array(buffer);
  4498. while (i < bytes.length) {
  4499. chr1 = bytes[i++];
  4500. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4501. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4502. enc1 = chr1 >> 2;
  4503. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4504. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4505. enc4 = chr3 & 63;
  4506. if (isNaN(chr2)) {
  4507. enc3 = enc4 = 64;
  4508. }
  4509. else if (isNaN(chr3)) {
  4510. enc4 = 64;
  4511. }
  4512. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4513. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4514. }
  4515. return "data:image/png;base64," + output;
  4516. };
  4517. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4518. if (bias === void 0) { bias = null; }
  4519. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4520. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4521. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4522. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4523. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4524. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4525. }
  4526. if (bias) {
  4527. minimum.x -= minimum.x * bias.x + bias.y;
  4528. minimum.y -= minimum.y * bias.x + bias.y;
  4529. minimum.z -= minimum.z * bias.x + bias.y;
  4530. maximum.x += maximum.x * bias.x + bias.y;
  4531. maximum.y += maximum.y * bias.x + bias.y;
  4532. maximum.z += maximum.z * bias.x + bias.y;
  4533. }
  4534. return {
  4535. minimum: minimum,
  4536. maximum: maximum
  4537. };
  4538. };
  4539. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4540. if (bias === void 0) { bias = null; }
  4541. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4542. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4543. for (var index = start; index < start + count; index++) {
  4544. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4545. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4546. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4547. }
  4548. if (bias) {
  4549. minimum.x -= minimum.x * bias.x + bias.y;
  4550. minimum.y -= minimum.y * bias.x + bias.y;
  4551. minimum.z -= minimum.z * bias.x + bias.y;
  4552. maximum.x += maximum.x * bias.x + bias.y;
  4553. maximum.y += maximum.y * bias.x + bias.y;
  4554. maximum.z += maximum.z * bias.x + bias.y;
  4555. }
  4556. return {
  4557. minimum: minimum,
  4558. maximum: maximum
  4559. };
  4560. };
  4561. Tools.Vector2ArrayFeeder = function (array) {
  4562. return function (index) {
  4563. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4564. var length = isFloatArray ? array.length / 2 : array.length;
  4565. if (index >= length) {
  4566. return null;
  4567. }
  4568. if (isFloatArray) {
  4569. var fa = array;
  4570. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4571. }
  4572. var a = array;
  4573. return a[index];
  4574. };
  4575. };
  4576. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4577. if (bias === void 0) { bias = null; }
  4578. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4579. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4580. var i = 0;
  4581. var cur = feeder(i++);
  4582. while (cur) {
  4583. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4584. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4585. cur = feeder(i++);
  4586. }
  4587. if (bias) {
  4588. minimum.x -= minimum.x * bias.x + bias.y;
  4589. minimum.y -= minimum.y * bias.x + bias.y;
  4590. maximum.x += maximum.x * bias.x + bias.y;
  4591. maximum.y += maximum.y * bias.x + bias.y;
  4592. }
  4593. return {
  4594. minimum: minimum,
  4595. maximum: maximum
  4596. };
  4597. };
  4598. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4599. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4600. return undefined;
  4601. return Array.isArray(obj) ? obj : [obj];
  4602. };
  4603. // Misc.
  4604. Tools.GetPointerPrefix = function () {
  4605. var eventPrefix = "pointer";
  4606. // Check if pointer events are supported
  4607. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4608. eventPrefix = "mouse";
  4609. }
  4610. return eventPrefix;
  4611. };
  4612. Tools.QueueNewFrame = function (func) {
  4613. if (window.requestAnimationFrame)
  4614. window.requestAnimationFrame(func);
  4615. else if (window.msRequestAnimationFrame)
  4616. window.msRequestAnimationFrame(func);
  4617. else if (window.webkitRequestAnimationFrame)
  4618. window.webkitRequestAnimationFrame(func);
  4619. else if (window.mozRequestAnimationFrame)
  4620. window.mozRequestAnimationFrame(func);
  4621. else if (window.oRequestAnimationFrame)
  4622. window.oRequestAnimationFrame(func);
  4623. else {
  4624. window.setTimeout(func, 16);
  4625. }
  4626. };
  4627. Tools.RequestFullscreen = function (element, options) {
  4628. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4629. if (!requestFunction)
  4630. return;
  4631. requestFunction.call(element, options);
  4632. };
  4633. Tools.ExitFullscreen = function () {
  4634. if (document.exitFullscreen) {
  4635. document.exitFullscreen();
  4636. }
  4637. else if (document.mozCancelFullScreen) {
  4638. document.mozCancelFullScreen();
  4639. }
  4640. else if (document.webkitCancelFullScreen) {
  4641. document.webkitCancelFullScreen();
  4642. }
  4643. else if (document.msCancelFullScreen) {
  4644. document.msCancelFullScreen();
  4645. }
  4646. };
  4647. // External files
  4648. Tools.CleanUrl = function (url) {
  4649. url = url.replace(/#/mg, "%23");
  4650. return url;
  4651. };
  4652. Tools.LoadImage = function (url, onload, onerror, database) {
  4653. if (url instanceof ArrayBuffer) {
  4654. url = Tools.EncodeArrayBufferTobase64(url);
  4655. }
  4656. url = Tools.CleanUrl(url);
  4657. var img = new Image();
  4658. if (url.substr(0, 5) !== "data:") {
  4659. if (Tools.CorsBehavior) {
  4660. switch (typeof (Tools.CorsBehavior)) {
  4661. case "function":
  4662. var result = Tools.CorsBehavior(url);
  4663. if (result) {
  4664. img.crossOrigin = result;
  4665. }
  4666. break;
  4667. case "string":
  4668. default:
  4669. img.crossOrigin = Tools.CorsBehavior;
  4670. break;
  4671. }
  4672. }
  4673. }
  4674. img.onload = function () {
  4675. onload(img);
  4676. };
  4677. img.onerror = function (err) {
  4678. Tools.Error("Error while trying to load texture: " + url);
  4679. if (Tools.UseFallbackTexture) {
  4680. 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";
  4681. onload(img);
  4682. }
  4683. else {
  4684. onerror();
  4685. }
  4686. };
  4687. var noIndexedDB = function () {
  4688. img.src = url;
  4689. };
  4690. var loadFromIndexedDB = function () {
  4691. database.loadImageFromDB(url, img);
  4692. };
  4693. //ANY database to do!
  4694. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4695. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4696. }
  4697. else {
  4698. if (url.indexOf("file:") === -1) {
  4699. noIndexedDB();
  4700. }
  4701. else {
  4702. try {
  4703. var textureName = url.substring(5).toLowerCase();
  4704. var blobURL;
  4705. try {
  4706. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4707. }
  4708. catch (ex) {
  4709. // Chrome doesn't support oneTimeOnly parameter
  4710. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4711. }
  4712. img.src = blobURL;
  4713. }
  4714. catch (e) {
  4715. img.src = null;
  4716. }
  4717. }
  4718. }
  4719. return img;
  4720. };
  4721. //ANY
  4722. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4723. url = Tools.CleanUrl(url);
  4724. var noIndexedDB = function () {
  4725. var request = new XMLHttpRequest();
  4726. var loadUrl = Tools.BaseUrl + url;
  4727. request.open('GET', loadUrl, true);
  4728. if (useArrayBuffer) {
  4729. request.responseType = "arraybuffer";
  4730. }
  4731. request.onprogress = progressCallBack;
  4732. request.onreadystatechange = function () {
  4733. if (request.readyState === 4) {
  4734. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4735. callback(!useArrayBuffer ? request.responseText : request.response);
  4736. }
  4737. else {
  4738. if (onError) {
  4739. onError();
  4740. }
  4741. else {
  4742. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4743. }
  4744. }
  4745. }
  4746. };
  4747. request.send(null);
  4748. };
  4749. var loadFromIndexedDB = function () {
  4750. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4751. };
  4752. if (url.indexOf("file:") !== -1) {
  4753. var fileName = url.substring(5).toLowerCase();
  4754. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4755. }
  4756. else {
  4757. // Caching all files
  4758. if (database && database.enableSceneOffline) {
  4759. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4760. }
  4761. else {
  4762. noIndexedDB();
  4763. }
  4764. }
  4765. };
  4766. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4767. var reader = new FileReader();
  4768. reader.onload = function (e) {
  4769. //target doesn't have result from ts 1.3
  4770. callback(e.target['result']);
  4771. };
  4772. reader.onprogress = progressCallback;
  4773. reader.readAsDataURL(fileToLoad);
  4774. };
  4775. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4776. var reader = new FileReader();
  4777. reader.onerror = function (e) {
  4778. Tools.Log("Error while reading file: " + fileToLoad.name);
  4779. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4780. };
  4781. reader.onload = function (e) {
  4782. //target doesn't have result from ts 1.3
  4783. callback(e.target['result']);
  4784. };
  4785. reader.onprogress = progressCallBack;
  4786. if (!useArrayBuffer) {
  4787. // Asynchronous read
  4788. reader.readAsText(fileToLoad);
  4789. }
  4790. else {
  4791. reader.readAsArrayBuffer(fileToLoad);
  4792. }
  4793. };
  4794. //returns a downloadable url to a file content.
  4795. Tools.FileAsURL = function (content) {
  4796. var fileBlob = new Blob([content]);
  4797. var url = window.URL || window.webkitURL;
  4798. var link = url.createObjectURL(fileBlob);
  4799. return link;
  4800. };
  4801. // Misc.
  4802. Tools.Format = function (value, decimals) {
  4803. if (decimals === void 0) { decimals = 2; }
  4804. return value.toFixed(decimals);
  4805. };
  4806. Tools.CheckExtends = function (v, min, max) {
  4807. if (v.x < min.x)
  4808. min.x = v.x;
  4809. if (v.y < min.y)
  4810. min.y = v.y;
  4811. if (v.z < min.z)
  4812. min.z = v.z;
  4813. if (v.x > max.x)
  4814. max.x = v.x;
  4815. if (v.y > max.y)
  4816. max.y = v.y;
  4817. if (v.z > max.z)
  4818. max.z = v.z;
  4819. };
  4820. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4821. for (var prop in source) {
  4822. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4823. continue;
  4824. }
  4825. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4826. continue;
  4827. }
  4828. var sourceValue = source[prop];
  4829. var typeOfSourceValue = typeof sourceValue;
  4830. if (typeOfSourceValue === "function") {
  4831. continue;
  4832. }
  4833. if (typeOfSourceValue === "object") {
  4834. if (sourceValue instanceof Array) {
  4835. destination[prop] = [];
  4836. if (sourceValue.length > 0) {
  4837. if (typeof sourceValue[0] == "object") {
  4838. for (var index = 0; index < sourceValue.length; index++) {
  4839. var clonedValue = cloneValue(sourceValue[index], destination);
  4840. if (destination[prop].indexOf(clonedValue) === -1) {
  4841. destination[prop].push(clonedValue);
  4842. }
  4843. }
  4844. }
  4845. else {
  4846. destination[prop] = sourceValue.slice(0);
  4847. }
  4848. }
  4849. }
  4850. else {
  4851. destination[prop] = cloneValue(sourceValue, destination);
  4852. }
  4853. }
  4854. else {
  4855. destination[prop] = sourceValue;
  4856. }
  4857. }
  4858. };
  4859. Tools.IsEmpty = function (obj) {
  4860. for (var i in obj) {
  4861. return false;
  4862. }
  4863. return true;
  4864. };
  4865. Tools.RegisterTopRootEvents = function (events) {
  4866. for (var index = 0; index < events.length; index++) {
  4867. var event = events[index];
  4868. window.addEventListener(event.name, event.handler, false);
  4869. try {
  4870. if (window.parent) {
  4871. window.parent.addEventListener(event.name, event.handler, false);
  4872. }
  4873. }
  4874. catch (e) {
  4875. }
  4876. }
  4877. };
  4878. Tools.UnregisterTopRootEvents = function (events) {
  4879. for (var index = 0; index < events.length; index++) {
  4880. var event = events[index];
  4881. window.removeEventListener(event.name, event.handler);
  4882. try {
  4883. if (window.parent) {
  4884. window.parent.removeEventListener(event.name, event.handler);
  4885. }
  4886. }
  4887. catch (e) {
  4888. }
  4889. }
  4890. };
  4891. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4892. // Read the contents of the framebuffer
  4893. var numberOfChannelsByLine = width * 4;
  4894. var halfHeight = height / 2;
  4895. //Reading datas from WebGL
  4896. var data = engine.readPixels(0, 0, width, height);
  4897. //To flip image on Y axis.
  4898. for (var i = 0; i < halfHeight; i++) {
  4899. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4900. var currentCell = j + i * numberOfChannelsByLine;
  4901. var targetLine = height - i - 1;
  4902. var targetCell = j + targetLine * numberOfChannelsByLine;
  4903. var temp = data[currentCell];
  4904. data[currentCell] = data[targetCell];
  4905. data[targetCell] = temp;
  4906. }
  4907. }
  4908. // Create a 2D canvas to store the result
  4909. if (!screenshotCanvas) {
  4910. screenshotCanvas = document.createElement('canvas');
  4911. }
  4912. screenshotCanvas.width = width;
  4913. screenshotCanvas.height = height;
  4914. var context = screenshotCanvas.getContext('2d');
  4915. // Copy the pixels to a 2D canvas
  4916. var imageData = context.createImageData(width, height);
  4917. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4918. var castData = imageData.data;
  4919. castData.set(data);
  4920. context.putImageData(imageData, 0, 0);
  4921. var base64Image = screenshotCanvas.toDataURL();
  4922. if (successCallback) {
  4923. successCallback(base64Image);
  4924. }
  4925. else {
  4926. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4927. if (("download" in document.createElement("a"))) {
  4928. var a = window.document.createElement("a");
  4929. a.href = base64Image;
  4930. var date = new Date();
  4931. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4932. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4933. window.document.body.appendChild(a);
  4934. a.addEventListener("click", function () {
  4935. a.parentElement.removeChild(a);
  4936. });
  4937. a.click();
  4938. }
  4939. else {
  4940. var newWindow = window.open("");
  4941. var img = newWindow.document.createElement("img");
  4942. img.src = base64Image;
  4943. newWindow.document.body.appendChild(img);
  4944. }
  4945. }
  4946. };
  4947. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4948. var width;
  4949. var height;
  4950. //If a precision value is specified
  4951. if (size.precision) {
  4952. width = Math.round(engine.getRenderWidth() * size.precision);
  4953. height = Math.round(width / engine.getAspectRatio(camera));
  4954. size = { width: width, height: height };
  4955. }
  4956. else if (size.width && size.height) {
  4957. width = size.width;
  4958. height = size.height;
  4959. }
  4960. else if (size.width && !size.height) {
  4961. width = size.width;
  4962. height = Math.round(width / engine.getAspectRatio(camera));
  4963. size = { width: width, height: height };
  4964. }
  4965. else if (size.height && !size.width) {
  4966. height = size.height;
  4967. width = Math.round(height * engine.getAspectRatio(camera));
  4968. size = { width: width, height: height };
  4969. }
  4970. else if (!isNaN(size)) {
  4971. height = size;
  4972. width = size;
  4973. }
  4974. else {
  4975. Tools.Error("Invalid 'size' parameter !");
  4976. return;
  4977. }
  4978. var scene = camera.getScene();
  4979. var previousCamera = null;
  4980. if (scene.activeCamera !== camera) {
  4981. previousCamera = scene.activeCamera;
  4982. scene.activeCamera = camera;
  4983. }
  4984. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4985. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4986. texture.renderList = scene.meshes;
  4987. texture.onAfterRenderObservable.add(function () {
  4988. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4989. });
  4990. scene.incrementRenderId();
  4991. texture.render(true);
  4992. texture.dispose();
  4993. if (previousCamera) {
  4994. scene.activeCamera = previousCamera;
  4995. }
  4996. camera.getProjectionMatrix(true); // Force cache refresh;
  4997. };
  4998. // XHR response validator for local file scenario
  4999. Tools.ValidateXHRData = function (xhr, dataType) {
  5000. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5001. if (dataType === void 0) { dataType = 7; }
  5002. try {
  5003. if (dataType & 1) {
  5004. if (xhr.responseText && xhr.responseText.length > 0) {
  5005. return true;
  5006. }
  5007. else if (dataType === 1) {
  5008. return false;
  5009. }
  5010. }
  5011. if (dataType & 2) {
  5012. // Check header width and height since there is no "TGA" magic number
  5013. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5014. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5015. return true;
  5016. }
  5017. else if (dataType === 2) {
  5018. return false;
  5019. }
  5020. }
  5021. if (dataType & 4) {
  5022. // Check for the "DDS" magic number
  5023. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5024. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5025. return true;
  5026. }
  5027. else {
  5028. return false;
  5029. }
  5030. }
  5031. }
  5032. catch (e) {
  5033. }
  5034. return false;
  5035. };
  5036. Object.defineProperty(Tools, "NoneLogLevel", {
  5037. get: function () {
  5038. return Tools._NoneLogLevel;
  5039. },
  5040. enumerable: true,
  5041. configurable: true
  5042. });
  5043. Object.defineProperty(Tools, "MessageLogLevel", {
  5044. get: function () {
  5045. return Tools._MessageLogLevel;
  5046. },
  5047. enumerable: true,
  5048. configurable: true
  5049. });
  5050. Object.defineProperty(Tools, "WarningLogLevel", {
  5051. get: function () {
  5052. return Tools._WarningLogLevel;
  5053. },
  5054. enumerable: true,
  5055. configurable: true
  5056. });
  5057. Object.defineProperty(Tools, "ErrorLogLevel", {
  5058. get: function () {
  5059. return Tools._ErrorLogLevel;
  5060. },
  5061. enumerable: true,
  5062. configurable: true
  5063. });
  5064. Object.defineProperty(Tools, "AllLogLevel", {
  5065. get: function () {
  5066. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5067. },
  5068. enumerable: true,
  5069. configurable: true
  5070. });
  5071. Tools._AddLogEntry = function (entry) {
  5072. Tools._LogCache = entry + Tools._LogCache;
  5073. if (Tools.OnNewCacheEntry) {
  5074. Tools.OnNewCacheEntry(entry);
  5075. }
  5076. };
  5077. Tools._FormatMessage = function (message) {
  5078. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5079. var date = new Date();
  5080. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5081. };
  5082. Tools._LogDisabled = function (message) {
  5083. // nothing to do
  5084. };
  5085. Tools._LogEnabled = function (message) {
  5086. var formattedMessage = Tools._FormatMessage(message);
  5087. console.log("BJS - " + formattedMessage);
  5088. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5089. Tools._AddLogEntry(entry);
  5090. };
  5091. Tools._WarnDisabled = function (message) {
  5092. // nothing to do
  5093. };
  5094. Tools._WarnEnabled = function (message) {
  5095. var formattedMessage = Tools._FormatMessage(message);
  5096. console.warn("BJS - " + formattedMessage);
  5097. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5098. Tools._AddLogEntry(entry);
  5099. };
  5100. Tools._ErrorDisabled = function (message) {
  5101. // nothing to do
  5102. };
  5103. Tools._ErrorEnabled = function (message) {
  5104. Tools.errorsCount++;
  5105. var formattedMessage = Tools._FormatMessage(message);
  5106. console.error("BJS - " + formattedMessage);
  5107. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5108. Tools._AddLogEntry(entry);
  5109. };
  5110. Object.defineProperty(Tools, "LogCache", {
  5111. get: function () {
  5112. return Tools._LogCache;
  5113. },
  5114. enumerable: true,
  5115. configurable: true
  5116. });
  5117. Tools.ClearLogCache = function () {
  5118. Tools._LogCache = "";
  5119. Tools.errorsCount = 0;
  5120. };
  5121. Object.defineProperty(Tools, "LogLevels", {
  5122. set: function (level) {
  5123. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5124. Tools.Log = Tools._LogEnabled;
  5125. }
  5126. else {
  5127. Tools.Log = Tools._LogDisabled;
  5128. }
  5129. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5130. Tools.Warn = Tools._WarnEnabled;
  5131. }
  5132. else {
  5133. Tools.Warn = Tools._WarnDisabled;
  5134. }
  5135. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5136. Tools.Error = Tools._ErrorEnabled;
  5137. }
  5138. else {
  5139. Tools.Error = Tools._ErrorDisabled;
  5140. }
  5141. },
  5142. enumerable: true,
  5143. configurable: true
  5144. });
  5145. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5146. get: function () {
  5147. return Tools._PerformanceNoneLogLevel;
  5148. },
  5149. enumerable: true,
  5150. configurable: true
  5151. });
  5152. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5153. get: function () {
  5154. return Tools._PerformanceUserMarkLogLevel;
  5155. },
  5156. enumerable: true,
  5157. configurable: true
  5158. });
  5159. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5160. get: function () {
  5161. return Tools._PerformanceConsoleLogLevel;
  5162. },
  5163. enumerable: true,
  5164. configurable: true
  5165. });
  5166. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5167. set: function (level) {
  5168. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5169. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5170. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5171. return;
  5172. }
  5173. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5174. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5175. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5176. return;
  5177. }
  5178. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5179. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5180. },
  5181. enumerable: true,
  5182. configurable: true
  5183. });
  5184. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5185. };
  5186. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5187. };
  5188. Tools._StartUserMark = function (counterName, condition) {
  5189. if (condition === void 0) { condition = true; }
  5190. if (!condition || !Tools._performance.mark) {
  5191. return;
  5192. }
  5193. Tools._performance.mark(counterName + "-Begin");
  5194. };
  5195. Tools._EndUserMark = function (counterName, condition) {
  5196. if (condition === void 0) { condition = true; }
  5197. if (!condition || !Tools._performance.mark) {
  5198. return;
  5199. }
  5200. Tools._performance.mark(counterName + "-End");
  5201. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5202. };
  5203. Tools._StartPerformanceConsole = function (counterName, condition) {
  5204. if (condition === void 0) { condition = true; }
  5205. if (!condition) {
  5206. return;
  5207. }
  5208. Tools._StartUserMark(counterName, condition);
  5209. if (console.time) {
  5210. console.time(counterName);
  5211. }
  5212. };
  5213. Tools._EndPerformanceConsole = function (counterName, condition) {
  5214. if (condition === void 0) { condition = true; }
  5215. if (!condition) {
  5216. return;
  5217. }
  5218. Tools._EndUserMark(counterName, condition);
  5219. if (console.time) {
  5220. console.timeEnd(counterName);
  5221. }
  5222. };
  5223. Object.defineProperty(Tools, "Now", {
  5224. get: function () {
  5225. if (window.performance && window.performance.now) {
  5226. return window.performance.now();
  5227. }
  5228. return new Date().getTime();
  5229. },
  5230. enumerable: true,
  5231. configurable: true
  5232. });
  5233. /**
  5234. * This method will return the name of the class used to create the instance of the given object.
  5235. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5236. * @param object the object to get the class name from
  5237. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5238. */
  5239. Tools.getClassName = function (object, isType) {
  5240. if (isType === void 0) { isType = false; }
  5241. var name = null;
  5242. if (!isType && object.getClassName) {
  5243. name = object.getClassName();
  5244. }
  5245. else {
  5246. if (object instanceof Object) {
  5247. var classObj = isType ? object : Object.getPrototypeOf(object);
  5248. name = classObj.constructor["__bjsclassName__"];
  5249. }
  5250. if (!name) {
  5251. name = typeof object;
  5252. }
  5253. }
  5254. return name;
  5255. };
  5256. Tools.first = function (array, predicate) {
  5257. for (var _i = 0; _i < array.length; _i++) {
  5258. var el = array[_i];
  5259. if (predicate(el)) {
  5260. return el;
  5261. }
  5262. }
  5263. };
  5264. /**
  5265. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  5266. * @param array
  5267. */
  5268. Tools.arrayOrStringFeeder = function (array) {
  5269. return function (index) {
  5270. if (index >= array.length) {
  5271. return null;
  5272. }
  5273. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5274. if (val && val.getHashCode) {
  5275. val = val.getHashCode();
  5276. }
  5277. if (typeof val === "string") {
  5278. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5279. }
  5280. return val;
  5281. };
  5282. };
  5283. /**
  5284. * Compute the hashCode of a stream of number
  5285. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5286. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5287. * @return the hash code computed
  5288. */
  5289. Tools.hashCodeFromStream = function (feeder) {
  5290. // Based from here: http://stackoverflow.com/a/7616484/802124
  5291. var hash = 0;
  5292. var index = 0;
  5293. var chr = feeder(index++);
  5294. while (chr != null) {
  5295. hash = ((hash << 5) - hash) + chr;
  5296. hash |= 0; // Convert to 32bit integer
  5297. chr = feeder(index++);
  5298. }
  5299. return hash;
  5300. };
  5301. Tools.BaseUrl = "";
  5302. Tools.CorsBehavior = "anonymous";
  5303. Tools.UseFallbackTexture = true;
  5304. // Logs
  5305. Tools._NoneLogLevel = 0;
  5306. Tools._MessageLogLevel = 1;
  5307. Tools._WarningLogLevel = 2;
  5308. Tools._ErrorLogLevel = 4;
  5309. Tools._LogCache = "";
  5310. Tools.errorsCount = 0;
  5311. Tools.Log = Tools._LogEnabled;
  5312. Tools.Warn = Tools._WarnEnabled;
  5313. Tools.Error = Tools._ErrorEnabled;
  5314. // Performances
  5315. Tools._PerformanceNoneLogLevel = 0;
  5316. Tools._PerformanceUserMarkLogLevel = 1;
  5317. Tools._PerformanceConsoleLogLevel = 2;
  5318. Tools._performance = window.performance;
  5319. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5320. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5321. return Tools;
  5322. })();
  5323. BABYLON.Tools = Tools;
  5324. /**
  5325. * Use this className as a decorator on a given class definition to add it a name.
  5326. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5327. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5328. * @param name
  5329. */
  5330. function className(name) {
  5331. return function (target) {
  5332. target["__bjsclassName__"] = name;
  5333. };
  5334. }
  5335. BABYLON.className = className;
  5336. /**
  5337. * An implementation of a loop for asynchronous functions.
  5338. */
  5339. var AsyncLoop = (function () {
  5340. /**
  5341. * Constroctor.
  5342. * @param iterations the number of iterations.
  5343. * @param _fn the function to run each iteration
  5344. * @param _successCallback the callback that will be called upon succesful execution
  5345. * @param offset starting offset.
  5346. */
  5347. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5348. if (offset === void 0) { offset = 0; }
  5349. this.iterations = iterations;
  5350. this._fn = _fn;
  5351. this._successCallback = _successCallback;
  5352. this.index = offset - 1;
  5353. this._done = false;
  5354. }
  5355. /**
  5356. * Execute the next iteration. Must be called after the last iteration was finished.
  5357. */
  5358. AsyncLoop.prototype.executeNext = function () {
  5359. if (!this._done) {
  5360. if (this.index + 1 < this.iterations) {
  5361. ++this.index;
  5362. this._fn(this);
  5363. }
  5364. else {
  5365. this.breakLoop();
  5366. }
  5367. }
  5368. };
  5369. /**
  5370. * Break the loop and run the success callback.
  5371. */
  5372. AsyncLoop.prototype.breakLoop = function () {
  5373. this._done = true;
  5374. this._successCallback();
  5375. };
  5376. /**
  5377. * Helper function
  5378. */
  5379. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5380. if (offset === void 0) { offset = 0; }
  5381. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5382. loop.executeNext();
  5383. return loop;
  5384. };
  5385. /**
  5386. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5387. * @param iterations total number of iterations
  5388. * @param syncedIterations number of synchronous iterations in each async iteration.
  5389. * @param fn the function to call each iteration.
  5390. * @param callback a success call back that will be called when iterating stops.
  5391. * @param breakFunction a break condition (optional)
  5392. * @param timeout timeout settings for the setTimeout function. default - 0.
  5393. * @constructor
  5394. */
  5395. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5396. if (timeout === void 0) { timeout = 0; }
  5397. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5398. if (breakFunction && breakFunction())
  5399. loop.breakLoop();
  5400. else {
  5401. setTimeout(function () {
  5402. for (var i = 0; i < syncedIterations; ++i) {
  5403. var iteration = (loop.index * syncedIterations) + i;
  5404. if (iteration >= iterations)
  5405. break;
  5406. fn(iteration);
  5407. if (breakFunction && breakFunction()) {
  5408. loop.breakLoop();
  5409. break;
  5410. }
  5411. }
  5412. loop.executeNext();
  5413. }, timeout);
  5414. }
  5415. }, callback);
  5416. };
  5417. return AsyncLoop;
  5418. })();
  5419. BABYLON.AsyncLoop = AsyncLoop;
  5420. })(BABYLON || (BABYLON = {}));
  5421. var BABYLON;
  5422. (function (BABYLON) {
  5423. var Internals;
  5424. (function (Internals) {
  5425. var _AlphaState = (function () {
  5426. function _AlphaState() {
  5427. this._isAlphaBlendDirty = false;
  5428. this._isBlendFunctionParametersDirty = false;
  5429. this._alphaBlend = false;
  5430. this._blendFunctionParameters = new Array(4);
  5431. }
  5432. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5433. get: function () {
  5434. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5435. },
  5436. enumerable: true,
  5437. configurable: true
  5438. });
  5439. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5440. get: function () {
  5441. return this._alphaBlend;
  5442. },
  5443. set: function (value) {
  5444. if (this._alphaBlend === value) {
  5445. return;
  5446. }
  5447. this._alphaBlend = value;
  5448. this._isAlphaBlendDirty = true;
  5449. },
  5450. enumerable: true,
  5451. configurable: true
  5452. });
  5453. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5454. if (this._blendFunctionParameters[0] === value0 &&
  5455. this._blendFunctionParameters[1] === value1 &&
  5456. this._blendFunctionParameters[2] === value2 &&
  5457. this._blendFunctionParameters[3] === value3) {
  5458. return;
  5459. }
  5460. this._blendFunctionParameters[0] = value0;
  5461. this._blendFunctionParameters[1] = value1;
  5462. this._blendFunctionParameters[2] = value2;
  5463. this._blendFunctionParameters[3] = value3;
  5464. this._isBlendFunctionParametersDirty = true;
  5465. };
  5466. _AlphaState.prototype.reset = function () {
  5467. this._alphaBlend = false;
  5468. this._blendFunctionParameters[0] = null;
  5469. this._blendFunctionParameters[1] = null;
  5470. this._blendFunctionParameters[2] = null;
  5471. this._blendFunctionParameters[3] = null;
  5472. this._isAlphaBlendDirty = true;
  5473. this._isBlendFunctionParametersDirty = false;
  5474. };
  5475. _AlphaState.prototype.apply = function (gl) {
  5476. if (!this.isDirty) {
  5477. return;
  5478. }
  5479. // Alpha blend
  5480. if (this._isAlphaBlendDirty) {
  5481. if (this._alphaBlend) {
  5482. gl.enable(gl.BLEND);
  5483. }
  5484. else {
  5485. gl.disable(gl.BLEND);
  5486. }
  5487. this._isAlphaBlendDirty = false;
  5488. }
  5489. // Alpha function
  5490. if (this._isBlendFunctionParametersDirty) {
  5491. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5492. this._isBlendFunctionParametersDirty = false;
  5493. }
  5494. };
  5495. return _AlphaState;
  5496. })();
  5497. Internals._AlphaState = _AlphaState;
  5498. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5499. })(BABYLON || (BABYLON = {}));
  5500. var BABYLON;
  5501. (function (BABYLON) {
  5502. var Internals;
  5503. (function (Internals) {
  5504. var _DepthCullingState = (function () {
  5505. function _DepthCullingState() {
  5506. this._isDepthTestDirty = false;
  5507. this._isDepthMaskDirty = false;
  5508. this._isDepthFuncDirty = false;
  5509. this._isCullFaceDirty = false;
  5510. this._isCullDirty = false;
  5511. this._isZOffsetDirty = false;
  5512. }
  5513. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5514. get: function () {
  5515. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5516. },
  5517. enumerable: true,
  5518. configurable: true
  5519. });
  5520. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5521. get: function () {
  5522. return this._zOffset;
  5523. },
  5524. set: function (value) {
  5525. if (this._zOffset === value) {
  5526. return;
  5527. }
  5528. this._zOffset = value;
  5529. this._isZOffsetDirty = true;
  5530. },
  5531. enumerable: true,
  5532. configurable: true
  5533. });
  5534. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5535. get: function () {
  5536. return this._cullFace;
  5537. },
  5538. set: function (value) {
  5539. if (this._cullFace === value) {
  5540. return;
  5541. }
  5542. this._cullFace = value;
  5543. this._isCullFaceDirty = true;
  5544. },
  5545. enumerable: true,
  5546. configurable: true
  5547. });
  5548. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5549. get: function () {
  5550. return this._cull;
  5551. },
  5552. set: function (value) {
  5553. if (this._cull === value) {
  5554. return;
  5555. }
  5556. this._cull = value;
  5557. this._isCullDirty = true;
  5558. },
  5559. enumerable: true,
  5560. configurable: true
  5561. });
  5562. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5563. get: function () {
  5564. return this._depthFunc;
  5565. },
  5566. set: function (value) {
  5567. if (this._depthFunc === value) {
  5568. return;
  5569. }
  5570. this._depthFunc = value;
  5571. this._isDepthFuncDirty = true;
  5572. },
  5573. enumerable: true,
  5574. configurable: true
  5575. });
  5576. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5577. get: function () {
  5578. return this._depthMask;
  5579. },
  5580. set: function (value) {
  5581. if (this._depthMask === value) {
  5582. return;
  5583. }
  5584. this._depthMask = value;
  5585. this._isDepthMaskDirty = true;
  5586. },
  5587. enumerable: true,
  5588. configurable: true
  5589. });
  5590. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5591. get: function () {
  5592. return this._depthTest;
  5593. },
  5594. set: function (value) {
  5595. if (this._depthTest === value) {
  5596. return;
  5597. }
  5598. this._depthTest = value;
  5599. this._isDepthTestDirty = true;
  5600. },
  5601. enumerable: true,
  5602. configurable: true
  5603. });
  5604. _DepthCullingState.prototype.reset = function () {
  5605. this._depthMask = true;
  5606. this._depthTest = true;
  5607. this._depthFunc = null;
  5608. this._cullFace = null;
  5609. this._cull = null;
  5610. this._zOffset = 0;
  5611. this._isDepthTestDirty = true;
  5612. this._isDepthMaskDirty = true;
  5613. this._isDepthFuncDirty = false;
  5614. this._isCullFaceDirty = false;
  5615. this._isCullDirty = false;
  5616. this._isZOffsetDirty = false;
  5617. };
  5618. _DepthCullingState.prototype.apply = function (gl) {
  5619. if (!this.isDirty) {
  5620. return;
  5621. }
  5622. // Cull
  5623. if (this._isCullDirty) {
  5624. if (this.cull) {
  5625. gl.enable(gl.CULL_FACE);
  5626. }
  5627. else {
  5628. gl.disable(gl.CULL_FACE);
  5629. }
  5630. this._isCullDirty = false;
  5631. }
  5632. // Cull face
  5633. if (this._isCullFaceDirty) {
  5634. gl.cullFace(this.cullFace);
  5635. this._isCullFaceDirty = false;
  5636. }
  5637. // Depth mask
  5638. if (this._isDepthMaskDirty) {
  5639. gl.depthMask(this.depthMask);
  5640. this._isDepthMaskDirty = false;
  5641. }
  5642. // Depth test
  5643. if (this._isDepthTestDirty) {
  5644. if (this.depthTest) {
  5645. gl.enable(gl.DEPTH_TEST);
  5646. }
  5647. else {
  5648. gl.disable(gl.DEPTH_TEST);
  5649. }
  5650. this._isDepthTestDirty = false;
  5651. }
  5652. // Depth func
  5653. if (this._isDepthFuncDirty) {
  5654. gl.depthFunc(this.depthFunc);
  5655. this._isDepthFuncDirty = false;
  5656. }
  5657. // zOffset
  5658. if (this._isZOffsetDirty) {
  5659. if (this.zOffset) {
  5660. gl.enable(gl.POLYGON_OFFSET_FILL);
  5661. gl.polygonOffset(this.zOffset, 0);
  5662. }
  5663. else {
  5664. gl.disable(gl.POLYGON_OFFSET_FILL);
  5665. }
  5666. this._isZOffsetDirty = false;
  5667. }
  5668. };
  5669. return _DepthCullingState;
  5670. })();
  5671. Internals._DepthCullingState = _DepthCullingState;
  5672. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5673. })(BABYLON || (BABYLON = {}));
  5674. var BABYLON;
  5675. (function (BABYLON) {
  5676. var compileShader = function (gl, source, type, defines) {
  5677. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5678. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5679. gl.compileShader(shader);
  5680. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5681. throw new Error(gl.getShaderInfoLog(shader));
  5682. }
  5683. return shader;
  5684. };
  5685. var getWebGLTextureType = function (gl, type) {
  5686. var textureType = gl.UNSIGNED_BYTE;
  5687. if (type === Engine.TEXTURETYPE_FLOAT)
  5688. textureType = gl.FLOAT;
  5689. return textureType;
  5690. };
  5691. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5692. var magFilter = gl.NEAREST;
  5693. var minFilter = gl.NEAREST;
  5694. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5695. magFilter = gl.LINEAR;
  5696. if (generateMipMaps) {
  5697. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5698. }
  5699. else {
  5700. minFilter = gl.LINEAR;
  5701. }
  5702. }
  5703. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5704. magFilter = gl.LINEAR;
  5705. if (generateMipMaps) {
  5706. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5707. }
  5708. else {
  5709. minFilter = gl.LINEAR;
  5710. }
  5711. }
  5712. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5713. magFilter = gl.NEAREST;
  5714. if (generateMipMaps) {
  5715. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5716. }
  5717. else {
  5718. minFilter = gl.NEAREST;
  5719. }
  5720. }
  5721. return {
  5722. min: minFilter,
  5723. mag: magFilter
  5724. };
  5725. };
  5726. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5727. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5728. var engine = scene.getEngine();
  5729. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5730. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5731. gl.bindTexture(gl.TEXTURE_2D, texture);
  5732. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5733. texture._baseWidth = width;
  5734. texture._baseHeight = height;
  5735. texture._width = potWidth;
  5736. texture._height = potHeight;
  5737. texture.isReady = true;
  5738. processFunction(potWidth, potHeight);
  5739. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5740. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5741. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5742. if (!noMipmap && !isCompressed) {
  5743. gl.generateMipmap(gl.TEXTURE_2D);
  5744. }
  5745. gl.bindTexture(gl.TEXTURE_2D, null);
  5746. engine.resetTextureCache();
  5747. scene._removePendingData(texture);
  5748. if (onLoad) {
  5749. onLoad();
  5750. }
  5751. };
  5752. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5753. var img;
  5754. var onload = function () {
  5755. loadedImages[index] = img;
  5756. loadedImages._internalCount++;
  5757. scene._removePendingData(img);
  5758. if (loadedImages._internalCount === 6) {
  5759. onfinish(loadedImages);
  5760. }
  5761. };
  5762. var onerror = function () {
  5763. scene._removePendingData(img);
  5764. };
  5765. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5766. scene._addPendingData(img);
  5767. };
  5768. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5769. var loadedImages = [];
  5770. loadedImages._internalCount = 0;
  5771. for (var index = 0; index < 6; index++) {
  5772. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5773. }
  5774. };
  5775. var InstancingAttributeInfo = (function () {
  5776. function InstancingAttributeInfo() {
  5777. }
  5778. return InstancingAttributeInfo;
  5779. })();
  5780. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5781. var EngineCapabilities = (function () {
  5782. function EngineCapabilities() {
  5783. }
  5784. return EngineCapabilities;
  5785. })();
  5786. BABYLON.EngineCapabilities = EngineCapabilities;
  5787. /**
  5788. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5789. */
  5790. var Engine = (function () {
  5791. /**
  5792. * @constructor
  5793. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5794. * @param {boolean} [antialias] - enable antialias
  5795. * @param options - further options to be sent to the getContext function
  5796. */
  5797. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5798. var _this = this;
  5799. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5800. // Public members
  5801. this.isFullscreen = false;
  5802. this.isPointerLock = false;
  5803. this.cullBackFaces = true;
  5804. this.renderEvenInBackground = true;
  5805. // To enable/disable IDB support and avoid XHR on .manifest
  5806. this.enableOfflineSupport = true;
  5807. this.scenes = new Array();
  5808. this._windowIsBackground = false;
  5809. this._webGLVersion = "1.0";
  5810. this._drawCalls = 0;
  5811. this._renderingQueueLaunched = false;
  5812. this._activeRenderLoops = [];
  5813. // FPS
  5814. this.fpsRange = 60;
  5815. this.previousFramesDuration = [];
  5816. this.fps = 60;
  5817. this.deltaTime = 0;
  5818. // States
  5819. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5820. this._alphaState = new BABYLON.Internals._AlphaState();
  5821. this._alphaMode = Engine.ALPHA_DISABLE;
  5822. // Cache
  5823. this._loadedTexturesCache = new Array();
  5824. this._maxTextureChannels = 16;
  5825. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5826. this._compiledEffects = {};
  5827. this._uintIndicesCurrentlySet = false;
  5828. this._renderingCanvas = canvas;
  5829. this._externalData = new BABYLON.StringDictionary();
  5830. options = options || {};
  5831. options.antialias = antialias;
  5832. if (options.preserveDrawingBuffer === undefined) {
  5833. options.preserveDrawingBuffer = false;
  5834. }
  5835. // GL
  5836. //try {
  5837. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5838. // if (this._gl) {
  5839. // this._webGLVersion = "2.0";
  5840. // }
  5841. //} catch (e) {
  5842. // // Do nothing
  5843. //}
  5844. if (!this._gl) {
  5845. try {
  5846. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5847. }
  5848. catch (e) {
  5849. throw new Error("WebGL not supported");
  5850. }
  5851. }
  5852. if (!this._gl) {
  5853. throw new Error("WebGL not supported");
  5854. }
  5855. this._onBlur = function () {
  5856. _this._windowIsBackground = true;
  5857. };
  5858. this._onFocus = function () {
  5859. _this._windowIsBackground = false;
  5860. };
  5861. window.addEventListener("blur", this._onBlur);
  5862. window.addEventListener("focus", this._onFocus);
  5863. // Viewport
  5864. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5865. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5866. this.resize();
  5867. // Caps
  5868. this._caps = new EngineCapabilities();
  5869. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5870. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5871. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5872. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5873. // Infos
  5874. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5875. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5876. if (rendererInfo != null) {
  5877. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5878. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5879. }
  5880. if (!this._glVendor) {
  5881. this._glVendor = "Unknown vendor";
  5882. }
  5883. if (!this._glRenderer) {
  5884. this._glRenderer = "Unknown renderer";
  5885. }
  5886. // Extensions
  5887. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5888. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5889. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5890. 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');
  5891. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5892. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5893. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5894. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5895. this._caps.highPrecisionShaderSupported = true;
  5896. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5897. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5898. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5899. if (this._gl.getShaderPrecisionFormat) {
  5900. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5901. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5902. }
  5903. // Depth buffer
  5904. this.setDepthBuffer(true);
  5905. this.setDepthFunctionToLessOrEqual();
  5906. this.setDepthWrite(true);
  5907. // Fullscreen
  5908. this._onFullscreenChange = function () {
  5909. if (document.fullscreen !== undefined) {
  5910. _this.isFullscreen = document.fullscreen;
  5911. }
  5912. else if (document.mozFullScreen !== undefined) {
  5913. _this.isFullscreen = document.mozFullScreen;
  5914. }
  5915. else if (document.webkitIsFullScreen !== undefined) {
  5916. _this.isFullscreen = document.webkitIsFullScreen;
  5917. }
  5918. else if (document.msIsFullScreen !== undefined) {
  5919. _this.isFullscreen = document.msIsFullScreen;
  5920. }
  5921. // Pointer lock
  5922. if (_this.isFullscreen && _this._pointerLockRequested) {
  5923. canvas.requestPointerLock = canvas.requestPointerLock ||
  5924. canvas.msRequestPointerLock ||
  5925. canvas.mozRequestPointerLock ||
  5926. canvas.webkitRequestPointerLock;
  5927. if (canvas.requestPointerLock) {
  5928. canvas.requestPointerLock();
  5929. }
  5930. }
  5931. };
  5932. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5933. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5934. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5935. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5936. // Pointer lock
  5937. this._onPointerLockChange = function () {
  5938. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5939. document.webkitPointerLockElement === canvas ||
  5940. document.msPointerLockElement === canvas ||
  5941. document.pointerLockElement === canvas);
  5942. };
  5943. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5944. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5945. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5946. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5947. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5948. Engine.audioEngine = new BABYLON.AudioEngine();
  5949. }
  5950. //default loading screen
  5951. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5952. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5953. }
  5954. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5955. get: function () {
  5956. return Engine._ALPHA_DISABLE;
  5957. },
  5958. enumerable: true,
  5959. configurable: true
  5960. });
  5961. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5962. get: function () {
  5963. return Engine._ALPHA_ONEONE;
  5964. },
  5965. enumerable: true,
  5966. configurable: true
  5967. });
  5968. Object.defineProperty(Engine, "ALPHA_ADD", {
  5969. get: function () {
  5970. return Engine._ALPHA_ADD;
  5971. },
  5972. enumerable: true,
  5973. configurable: true
  5974. });
  5975. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5976. get: function () {
  5977. return Engine._ALPHA_COMBINE;
  5978. },
  5979. enumerable: true,
  5980. configurable: true
  5981. });
  5982. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5983. get: function () {
  5984. return Engine._ALPHA_SUBTRACT;
  5985. },
  5986. enumerable: true,
  5987. configurable: true
  5988. });
  5989. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5990. get: function () {
  5991. return Engine._ALPHA_MULTIPLY;
  5992. },
  5993. enumerable: true,
  5994. configurable: true
  5995. });
  5996. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5997. get: function () {
  5998. return Engine._ALPHA_MAXIMIZED;
  5999. },
  6000. enumerable: true,
  6001. configurable: true
  6002. });
  6003. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6004. get: function () {
  6005. return Engine._DELAYLOADSTATE_NONE;
  6006. },
  6007. enumerable: true,
  6008. configurable: true
  6009. });
  6010. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6011. get: function () {
  6012. return Engine._DELAYLOADSTATE_LOADED;
  6013. },
  6014. enumerable: true,
  6015. configurable: true
  6016. });
  6017. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6018. get: function () {
  6019. return Engine._DELAYLOADSTATE_LOADING;
  6020. },
  6021. enumerable: true,
  6022. configurable: true
  6023. });
  6024. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6025. get: function () {
  6026. return Engine._DELAYLOADSTATE_NOTLOADED;
  6027. },
  6028. enumerable: true,
  6029. configurable: true
  6030. });
  6031. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6032. get: function () {
  6033. return Engine._TEXTUREFORMAT_ALPHA;
  6034. },
  6035. enumerable: true,
  6036. configurable: true
  6037. });
  6038. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6039. get: function () {
  6040. return Engine._TEXTUREFORMAT_LUMINANCE;
  6041. },
  6042. enumerable: true,
  6043. configurable: true
  6044. });
  6045. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6046. get: function () {
  6047. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6048. },
  6049. enumerable: true,
  6050. configurable: true
  6051. });
  6052. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6053. get: function () {
  6054. return Engine._TEXTUREFORMAT_RGB;
  6055. },
  6056. enumerable: true,
  6057. configurable: true
  6058. });
  6059. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6060. get: function () {
  6061. return Engine._TEXTUREFORMAT_RGBA;
  6062. },
  6063. enumerable: true,
  6064. configurable: true
  6065. });
  6066. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6067. get: function () {
  6068. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6069. },
  6070. enumerable: true,
  6071. configurable: true
  6072. });
  6073. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6074. get: function () {
  6075. return Engine._TEXTURETYPE_FLOAT;
  6076. },
  6077. enumerable: true,
  6078. configurable: true
  6079. });
  6080. Object.defineProperty(Engine, "Version", {
  6081. get: function () {
  6082. return "2.4.0-beta";
  6083. },
  6084. enumerable: true,
  6085. configurable: true
  6086. });
  6087. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6088. get: function () {
  6089. return this._webGLVersion;
  6090. },
  6091. enumerable: true,
  6092. configurable: true
  6093. });
  6094. Engine.prototype._prepareWorkingCanvas = function () {
  6095. if (this._workingCanvas) {
  6096. return;
  6097. }
  6098. this._workingCanvas = document.createElement("canvas");
  6099. this._workingContext = this._workingCanvas.getContext("2d");
  6100. };
  6101. Engine.prototype.resetTextureCache = function () {
  6102. for (var index = 0; index < this._maxTextureChannels; index++) {
  6103. this._activeTexturesCache[index] = null;
  6104. }
  6105. };
  6106. Engine.prototype.getGlInfo = function () {
  6107. return {
  6108. vendor: this._glVendor,
  6109. renderer: this._glRenderer,
  6110. version: this._glVersion
  6111. };
  6112. };
  6113. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6114. if (useScreen === void 0) { useScreen = false; }
  6115. var viewport = camera.viewport;
  6116. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6117. };
  6118. Engine.prototype.getRenderWidth = function (useScreen) {
  6119. if (useScreen === void 0) { useScreen = false; }
  6120. if (!useScreen && this._currentRenderTarget) {
  6121. return this._currentRenderTarget._width;
  6122. }
  6123. return this._renderingCanvas.width;
  6124. };
  6125. Engine.prototype.getRenderHeight = function (useScreen) {
  6126. if (useScreen === void 0) { useScreen = false; }
  6127. if (!useScreen && this._currentRenderTarget) {
  6128. return this._currentRenderTarget._height;
  6129. }
  6130. return this._renderingCanvas.height;
  6131. };
  6132. Engine.prototype.getRenderingCanvas = function () {
  6133. return this._renderingCanvas;
  6134. };
  6135. Engine.prototype.getRenderingCanvasClientRect = function () {
  6136. return this._renderingCanvas.getBoundingClientRect();
  6137. };
  6138. Engine.prototype.setHardwareScalingLevel = function (level) {
  6139. this._hardwareScalingLevel = level;
  6140. this.resize();
  6141. };
  6142. Engine.prototype.getHardwareScalingLevel = function () {
  6143. return this._hardwareScalingLevel;
  6144. };
  6145. Engine.prototype.getLoadedTexturesCache = function () {
  6146. return this._loadedTexturesCache;
  6147. };
  6148. Engine.prototype.getCaps = function () {
  6149. return this._caps;
  6150. };
  6151. Object.defineProperty(Engine.prototype, "drawCalls", {
  6152. get: function () {
  6153. return this._drawCalls;
  6154. },
  6155. enumerable: true,
  6156. configurable: true
  6157. });
  6158. // Methods
  6159. Engine.prototype.resetDrawCalls = function () {
  6160. this._drawCalls = 0;
  6161. };
  6162. Engine.prototype.getDepthFunction = function () {
  6163. return this._depthCullingState.depthFunc;
  6164. };
  6165. Engine.prototype.setDepthFunction = function (depthFunc) {
  6166. this._depthCullingState.depthFunc = depthFunc;
  6167. };
  6168. Engine.prototype.setDepthFunctionToGreater = function () {
  6169. this._depthCullingState.depthFunc = this._gl.GREATER;
  6170. };
  6171. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6172. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6173. };
  6174. Engine.prototype.setDepthFunctionToLess = function () {
  6175. this._depthCullingState.depthFunc = this._gl.LESS;
  6176. };
  6177. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6178. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6179. };
  6180. /**
  6181. * stop executing a render loop function and remove it from the execution array
  6182. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6183. */
  6184. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6185. if (!renderFunction) {
  6186. this._activeRenderLoops = [];
  6187. return;
  6188. }
  6189. var index = this._activeRenderLoops.indexOf(renderFunction);
  6190. if (index >= 0) {
  6191. this._activeRenderLoops.splice(index, 1);
  6192. }
  6193. };
  6194. Engine.prototype._renderLoop = function () {
  6195. var shouldRender = true;
  6196. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6197. shouldRender = false;
  6198. }
  6199. if (shouldRender) {
  6200. // Start new frame
  6201. this.beginFrame();
  6202. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6203. var renderFunction = this._activeRenderLoops[index];
  6204. renderFunction();
  6205. }
  6206. // Present
  6207. this.endFrame();
  6208. }
  6209. if (this._activeRenderLoops.length > 0) {
  6210. // Register new frame
  6211. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6212. }
  6213. else {
  6214. this._renderingQueueLaunched = false;
  6215. }
  6216. };
  6217. /**
  6218. * Register and execute a render loop. The engine can have more than one render function.
  6219. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6220. * @example
  6221. * engine.runRenderLoop(function () {
  6222. * scene.render()
  6223. * })
  6224. */
  6225. Engine.prototype.runRenderLoop = function (renderFunction) {
  6226. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6227. return;
  6228. }
  6229. this._activeRenderLoops.push(renderFunction);
  6230. if (!this._renderingQueueLaunched) {
  6231. this._renderingQueueLaunched = true;
  6232. this._bindedRenderFunction = this._renderLoop.bind(this);
  6233. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6234. }
  6235. };
  6236. /**
  6237. * Toggle full screen mode.
  6238. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6239. * @param {any} options - an options object to be sent to the requestFullscreen function
  6240. */
  6241. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6242. if (this.isFullscreen) {
  6243. BABYLON.Tools.ExitFullscreen();
  6244. }
  6245. else {
  6246. this._pointerLockRequested = requestPointerLock;
  6247. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6248. }
  6249. };
  6250. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6251. this.applyStates();
  6252. if (backBuffer) {
  6253. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6254. }
  6255. if (depthStencil && this._depthCullingState.depthMask) {
  6256. this._gl.clearDepth(1.0);
  6257. }
  6258. var mode = 0;
  6259. if (backBuffer) {
  6260. mode |= this._gl.COLOR_BUFFER_BIT;
  6261. }
  6262. if (depthStencil && this._depthCullingState.depthMask) {
  6263. mode |= this._gl.DEPTH_BUFFER_BIT;
  6264. }
  6265. this._gl.clear(mode);
  6266. };
  6267. /**
  6268. * Set the WebGL's viewport
  6269. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6270. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6271. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6272. */
  6273. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6274. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6275. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6276. var x = viewport.x || 0;
  6277. var y = viewport.y || 0;
  6278. this._cachedViewport = viewport;
  6279. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6280. };
  6281. /**
  6282. * Directly set the WebGL Viewport
  6283. * The x, y, width & height are directly passed to the WebGL call
  6284. * @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.
  6285. */
  6286. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6287. var currentViewport = this._cachedViewport;
  6288. this._cachedViewport = null;
  6289. this._gl.viewport(x, y, width, height);
  6290. return currentViewport;
  6291. };
  6292. Engine.prototype.beginFrame = function () {
  6293. this._measureFps();
  6294. };
  6295. Engine.prototype.endFrame = function () {
  6296. //this.flushFramebuffer();
  6297. };
  6298. /**
  6299. * resize the view according to the canvas' size.
  6300. * @example
  6301. * window.addEventListener("resize", function () {
  6302. * engine.resize();
  6303. * });
  6304. */
  6305. Engine.prototype.resize = function () {
  6306. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6307. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6308. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6309. for (var index = 0; index < this.scenes.length; index++) {
  6310. var scene = this.scenes[index];
  6311. if (scene.debugLayer.isVisible()) {
  6312. scene.debugLayer._syncPositions();
  6313. }
  6314. }
  6315. };
  6316. /**
  6317. * force a specific size of the canvas
  6318. * @param {number} width - the new canvas' width
  6319. * @param {number} height - the new canvas' height
  6320. */
  6321. Engine.prototype.setSize = function (width, height) {
  6322. this._renderingCanvas.width = width;
  6323. this._renderingCanvas.height = height;
  6324. for (var index = 0; index < this.scenes.length; index++) {
  6325. var scene = this.scenes[index];
  6326. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6327. var cam = scene.cameras[camIndex];
  6328. cam._currentRenderId = 0;
  6329. }
  6330. }
  6331. };
  6332. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6333. this._currentRenderTarget = texture;
  6334. var gl = this._gl;
  6335. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  6336. if (texture.isCube) {
  6337. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6338. }
  6339. else {
  6340. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6341. }
  6342. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6343. this.wipeCaches();
  6344. };
  6345. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6346. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6347. this._currentRenderTarget = null;
  6348. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6349. var gl = this._gl;
  6350. gl.bindTexture(gl.TEXTURE_2D, texture);
  6351. gl.generateMipmap(gl.TEXTURE_2D);
  6352. gl.bindTexture(gl.TEXTURE_2D, null);
  6353. }
  6354. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6355. };
  6356. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6357. if (texture.generateMipMaps) {
  6358. var gl = this._gl;
  6359. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6360. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6361. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6362. }
  6363. };
  6364. Engine.prototype.flushFramebuffer = function () {
  6365. this._gl.flush();
  6366. };
  6367. Engine.prototype.restoreDefaultFramebuffer = function () {
  6368. this._currentRenderTarget = null;
  6369. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6370. this.setViewport(this._cachedViewport);
  6371. this.wipeCaches();
  6372. };
  6373. // VBOs
  6374. Engine.prototype._resetVertexBufferBinding = function () {
  6375. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  6376. this._cachedVertexBuffers = null;
  6377. };
  6378. Engine.prototype.createVertexBuffer = function (vertices) {
  6379. var vbo = this._gl.createBuffer();
  6380. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6381. if (vertices instanceof Float32Array) {
  6382. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6383. }
  6384. else {
  6385. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6386. }
  6387. this._resetVertexBufferBinding();
  6388. vbo.references = 1;
  6389. return vbo;
  6390. };
  6391. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6392. var vbo = this._gl.createBuffer();
  6393. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6394. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6395. this._resetVertexBufferBinding();
  6396. vbo.references = 1;
  6397. return vbo;
  6398. };
  6399. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6400. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6401. if (offset === undefined) {
  6402. offset = 0;
  6403. }
  6404. if (vertices instanceof Float32Array) {
  6405. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6406. }
  6407. else {
  6408. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6409. }
  6410. this._resetVertexBufferBinding();
  6411. };
  6412. Engine.prototype._resetIndexBufferBinding = function () {
  6413. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6414. this._cachedIndexBuffer = null;
  6415. };
  6416. Engine.prototype.createIndexBuffer = function (indices) {
  6417. var vbo = this._gl.createBuffer();
  6418. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6419. // Check for 32 bits indices
  6420. var arrayBuffer;
  6421. var need32Bits = false;
  6422. if (this._caps.uintIndices) {
  6423. for (var index = 0; index < indices.length; index++) {
  6424. if (indices[index] > 65535) {
  6425. need32Bits = true;
  6426. break;
  6427. }
  6428. }
  6429. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6430. }
  6431. else {
  6432. arrayBuffer = new Uint16Array(indices);
  6433. }
  6434. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6435. this._resetIndexBufferBinding();
  6436. vbo.references = 1;
  6437. vbo.is32Bits = need32Bits;
  6438. return vbo;
  6439. };
  6440. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6441. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6442. this._cachedVertexBuffers = vertexBuffer;
  6443. this._cachedEffectForVertexBuffers = effect;
  6444. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6445. var offset = 0;
  6446. for (var index = 0; index < vertexDeclaration.length; index++) {
  6447. var order = effect.getAttributeLocation(index);
  6448. if (order >= 0) {
  6449. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6450. }
  6451. offset += vertexDeclaration[index] * 4;
  6452. }
  6453. }
  6454. if (this._cachedIndexBuffer !== indexBuffer) {
  6455. this._cachedIndexBuffer = indexBuffer;
  6456. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6457. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6458. }
  6459. };
  6460. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6461. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6462. this._cachedVertexBuffers = vertexBuffers;
  6463. this._cachedEffectForVertexBuffers = effect;
  6464. var attributes = effect.getAttributesNames();
  6465. for (var index = 0; index < attributes.length; index++) {
  6466. var order = effect.getAttributeLocation(index);
  6467. if (order >= 0) {
  6468. var vertexBuffer = vertexBuffers[attributes[index]];
  6469. if (!vertexBuffer) {
  6470. continue;
  6471. }
  6472. var stride = vertexBuffer.getStrideSize();
  6473. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6474. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6475. }
  6476. }
  6477. }
  6478. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6479. this._cachedIndexBuffer = indexBuffer;
  6480. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6481. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6482. }
  6483. };
  6484. Engine.prototype._releaseBuffer = function (buffer) {
  6485. buffer.references--;
  6486. if (buffer.references === 0) {
  6487. this._gl.deleteBuffer(buffer);
  6488. return true;
  6489. }
  6490. return false;
  6491. };
  6492. Engine.prototype.createInstancesBuffer = function (capacity) {
  6493. var buffer = this._gl.createBuffer();
  6494. buffer.capacity = capacity;
  6495. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6496. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6497. return buffer;
  6498. };
  6499. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6500. this._gl.deleteBuffer(buffer);
  6501. };
  6502. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6503. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6504. if (data) {
  6505. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6506. }
  6507. if (offsetLocations[0].index !== undefined) {
  6508. var stride = 0;
  6509. for (var i = 0; i < offsetLocations.length; i++) {
  6510. var ai = offsetLocations[i];
  6511. stride += ai.attributeSize * 4;
  6512. }
  6513. for (var i = 0; i < offsetLocations.length; i++) {
  6514. var ai = offsetLocations[i];
  6515. this._gl.enableVertexAttribArray(ai.index);
  6516. this._gl.vertexAttribPointer(ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6517. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6518. }
  6519. }
  6520. else {
  6521. for (var index = 0; index < 4; index++) {
  6522. var offsetLocation = offsetLocations[index];
  6523. this._gl.enableVertexAttribArray(offsetLocation);
  6524. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6525. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6526. }
  6527. }
  6528. };
  6529. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6530. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6531. if (offsetLocations[0].index !== undefined) {
  6532. for (var i = 0; i < offsetLocations.length; i++) {
  6533. var ai = offsetLocations[i];
  6534. this._gl.disableVertexAttribArray(ai.index);
  6535. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 0);
  6536. }
  6537. }
  6538. else {
  6539. for (var index = 0; index < 4; index++) {
  6540. var offsetLocation = offsetLocations[index];
  6541. this._gl.disableVertexAttribArray(offsetLocation);
  6542. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6543. }
  6544. }
  6545. };
  6546. Engine.prototype.applyStates = function () {
  6547. this._depthCullingState.apply(this._gl);
  6548. this._alphaState.apply(this._gl);
  6549. };
  6550. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6551. // Apply states
  6552. this.applyStates();
  6553. this._drawCalls++;
  6554. // Render
  6555. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6556. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6557. if (instancesCount) {
  6558. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6559. return;
  6560. }
  6561. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6562. };
  6563. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6564. // Apply states
  6565. this.applyStates();
  6566. this._drawCalls++;
  6567. if (instancesCount) {
  6568. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6569. return;
  6570. }
  6571. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6572. };
  6573. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6574. // Apply states
  6575. this.applyStates();
  6576. this._drawCalls++;
  6577. if (instancesCount) {
  6578. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6579. return;
  6580. }
  6581. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6582. };
  6583. // Shaders
  6584. Engine.prototype._releaseEffect = function (effect) {
  6585. if (this._compiledEffects[effect._key]) {
  6586. delete this._compiledEffects[effect._key];
  6587. if (effect.getProgram()) {
  6588. this._gl.deleteProgram(effect.getProgram());
  6589. }
  6590. }
  6591. };
  6592. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6593. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6594. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6595. var name = vertex + "+" + fragment + "@" + defines;
  6596. if (this._compiledEffects[name]) {
  6597. return this._compiledEffects[name];
  6598. }
  6599. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6600. effect._key = name;
  6601. this._compiledEffects[name] = effect;
  6602. return effect;
  6603. };
  6604. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6605. if (uniformsNames === void 0) { uniformsNames = []; }
  6606. if (samplers === void 0) { samplers = []; }
  6607. if (defines === void 0) { defines = ""; }
  6608. return this.createEffect({
  6609. vertex: "particles",
  6610. fragmentElement: fragmentName
  6611. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6612. };
  6613. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6614. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6615. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6616. var shaderProgram = this._gl.createProgram();
  6617. this._gl.attachShader(shaderProgram, vertexShader);
  6618. this._gl.attachShader(shaderProgram, fragmentShader);
  6619. this._gl.linkProgram(shaderProgram);
  6620. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6621. if (!linked) {
  6622. var error = this._gl.getProgramInfoLog(shaderProgram);
  6623. if (error) {
  6624. throw new Error(error);
  6625. }
  6626. }
  6627. this._gl.deleteShader(vertexShader);
  6628. this._gl.deleteShader(fragmentShader);
  6629. return shaderProgram;
  6630. };
  6631. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6632. var results = [];
  6633. for (var index = 0; index < uniformsNames.length; index++) {
  6634. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6635. }
  6636. return results;
  6637. };
  6638. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6639. var results = [];
  6640. for (var index = 0; index < attributesNames.length; index++) {
  6641. try {
  6642. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6643. }
  6644. catch (e) {
  6645. results.push(-1);
  6646. }
  6647. }
  6648. return results;
  6649. };
  6650. Engine.prototype.enableEffect = function (effect) {
  6651. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6652. if (effect && effect.onBind) {
  6653. effect.onBind(effect);
  6654. }
  6655. return;
  6656. }
  6657. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6658. // Use program
  6659. this._gl.useProgram(effect.getProgram());
  6660. for (var i in this._vertexAttribArrays) {
  6661. //make sure this is a number)
  6662. var iAsNumber = +i;
  6663. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6664. continue;
  6665. }
  6666. this._vertexAttribArrays[iAsNumber] = false;
  6667. this._gl.disableVertexAttribArray(iAsNumber);
  6668. }
  6669. var attributesCount = effect.getAttributesCount();
  6670. for (var index = 0; index < attributesCount; index++) {
  6671. // Attributes
  6672. var order = effect.getAttributeLocation(index);
  6673. if (order >= 0) {
  6674. this._vertexAttribArrays[order] = true;
  6675. this._gl.enableVertexAttribArray(order);
  6676. }
  6677. }
  6678. this._currentEffect = effect;
  6679. if (effect.onBind) {
  6680. effect.onBind(effect);
  6681. }
  6682. };
  6683. Engine.prototype.setArray = function (uniform, array) {
  6684. if (!uniform)
  6685. return;
  6686. this._gl.uniform1fv(uniform, array);
  6687. };
  6688. Engine.prototype.setArray2 = function (uniform, array) {
  6689. if (!uniform || array.length % 2 !== 0)
  6690. return;
  6691. this._gl.uniform2fv(uniform, array);
  6692. };
  6693. Engine.prototype.setArray3 = function (uniform, array) {
  6694. if (!uniform || array.length % 3 !== 0)
  6695. return;
  6696. this._gl.uniform3fv(uniform, array);
  6697. };
  6698. Engine.prototype.setArray4 = function (uniform, array) {
  6699. if (!uniform || array.length % 4 !== 0)
  6700. return;
  6701. this._gl.uniform4fv(uniform, array);
  6702. };
  6703. Engine.prototype.setMatrices = function (uniform, matrices) {
  6704. if (!uniform)
  6705. return;
  6706. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6707. };
  6708. Engine.prototype.setMatrix = function (uniform, matrix) {
  6709. if (!uniform)
  6710. return;
  6711. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6712. };
  6713. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6714. if (!uniform)
  6715. return;
  6716. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6717. };
  6718. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6719. if (!uniform)
  6720. return;
  6721. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6722. };
  6723. Engine.prototype.setFloat = function (uniform, value) {
  6724. if (!uniform)
  6725. return;
  6726. this._gl.uniform1f(uniform, value);
  6727. };
  6728. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6729. if (!uniform)
  6730. return;
  6731. this._gl.uniform2f(uniform, x, y);
  6732. };
  6733. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6734. if (!uniform)
  6735. return;
  6736. this._gl.uniform3f(uniform, x, y, z);
  6737. };
  6738. Engine.prototype.setBool = function (uniform, bool) {
  6739. if (!uniform)
  6740. return;
  6741. this._gl.uniform1i(uniform, bool);
  6742. };
  6743. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6744. if (!uniform)
  6745. return;
  6746. this._gl.uniform4f(uniform, x, y, z, w);
  6747. };
  6748. Engine.prototype.setColor3 = function (uniform, color3) {
  6749. if (!uniform)
  6750. return;
  6751. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6752. };
  6753. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6754. if (!uniform)
  6755. return;
  6756. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6757. };
  6758. // States
  6759. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6760. if (zOffset === void 0) { zOffset = 0; }
  6761. if (reverseSide === void 0) { reverseSide = false; }
  6762. // Culling
  6763. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6764. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6765. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6766. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6767. if (culling) {
  6768. this._depthCullingState.cullFace = cullFace;
  6769. this._depthCullingState.cull = true;
  6770. }
  6771. else {
  6772. this._depthCullingState.cull = false;
  6773. }
  6774. }
  6775. // Z offset
  6776. this._depthCullingState.zOffset = zOffset;
  6777. };
  6778. Engine.prototype.setDepthBuffer = function (enable) {
  6779. this._depthCullingState.depthTest = enable;
  6780. };
  6781. Engine.prototype.getDepthWrite = function () {
  6782. return this._depthCullingState.depthMask;
  6783. };
  6784. Engine.prototype.setDepthWrite = function (enable) {
  6785. this._depthCullingState.depthMask = enable;
  6786. };
  6787. Engine.prototype.setColorWrite = function (enable) {
  6788. this._gl.colorMask(enable, enable, enable, enable);
  6789. };
  6790. Engine.prototype.setAlphaMode = function (mode) {
  6791. if (this._alphaMode === mode) {
  6792. return;
  6793. }
  6794. switch (mode) {
  6795. case Engine.ALPHA_DISABLE:
  6796. this.setDepthWrite(true);
  6797. this._alphaState.alphaBlend = false;
  6798. break;
  6799. case Engine.ALPHA_COMBINE:
  6800. this.setDepthWrite(false);
  6801. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6802. this._alphaState.alphaBlend = true;
  6803. break;
  6804. case Engine.ALPHA_ONEONE:
  6805. this.setDepthWrite(false);
  6806. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6807. this._alphaState.alphaBlend = true;
  6808. break;
  6809. case Engine.ALPHA_ADD:
  6810. this.setDepthWrite(false);
  6811. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6812. this._alphaState.alphaBlend = true;
  6813. break;
  6814. case Engine.ALPHA_SUBTRACT:
  6815. this.setDepthWrite(false);
  6816. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6817. this._alphaState.alphaBlend = true;
  6818. break;
  6819. case Engine.ALPHA_MULTIPLY:
  6820. this.setDepthWrite(false);
  6821. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6822. this._alphaState.alphaBlend = true;
  6823. break;
  6824. case Engine.ALPHA_MAXIMIZED:
  6825. this.setDepthWrite(false);
  6826. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6827. this._alphaState.alphaBlend = true;
  6828. break;
  6829. }
  6830. this._alphaMode = mode;
  6831. };
  6832. Engine.prototype.getAlphaMode = function () {
  6833. return this._alphaMode;
  6834. };
  6835. Engine.prototype.setAlphaTesting = function (enable) {
  6836. this._alphaTest = enable;
  6837. };
  6838. Engine.prototype.getAlphaTesting = function () {
  6839. return this._alphaTest;
  6840. };
  6841. // Textures
  6842. Engine.prototype.wipeCaches = function () {
  6843. this.resetTextureCache();
  6844. this._currentEffect = null;
  6845. this._depthCullingState.reset();
  6846. this.setDepthFunctionToLessOrEqual();
  6847. this._alphaState.reset();
  6848. this._cachedVertexBuffers = null;
  6849. this._cachedIndexBuffer = null;
  6850. this._cachedEffectForVertexBuffers = null;
  6851. };
  6852. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6853. var gl = this._gl;
  6854. gl.bindTexture(gl.TEXTURE_2D, texture);
  6855. var magFilter = gl.NEAREST;
  6856. var minFilter = gl.NEAREST;
  6857. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6858. magFilter = gl.LINEAR;
  6859. minFilter = gl.LINEAR;
  6860. }
  6861. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6862. magFilter = gl.LINEAR;
  6863. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6864. }
  6865. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6867. gl.bindTexture(gl.TEXTURE_2D, null);
  6868. texture.samplingMode = samplingMode;
  6869. };
  6870. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6871. var _this = this;
  6872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6873. if (onLoad === void 0) { onLoad = null; }
  6874. if (onError === void 0) { onError = null; }
  6875. if (buffer === void 0) { buffer = null; }
  6876. var texture = this._gl.createTexture();
  6877. var extension;
  6878. var fromData = false;
  6879. if (url.substr(0, 5) === "data:") {
  6880. fromData = true;
  6881. }
  6882. if (!fromData)
  6883. extension = url.substr(url.length - 4, 4).toLowerCase();
  6884. else {
  6885. var oldUrl = url;
  6886. fromData = oldUrl.split(':');
  6887. url = oldUrl;
  6888. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6889. }
  6890. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6891. var isTGA = (extension === ".tga");
  6892. scene._addPendingData(texture);
  6893. texture.url = url;
  6894. texture.noMipmap = noMipmap;
  6895. texture.references = 1;
  6896. texture.samplingMode = samplingMode;
  6897. this._loadedTexturesCache.push(texture);
  6898. var onerror = function () {
  6899. scene._removePendingData(texture);
  6900. if (onError) {
  6901. onError();
  6902. }
  6903. };
  6904. var callback;
  6905. if (isTGA) {
  6906. callback = function (arrayBuffer) {
  6907. var data = new Uint8Array(arrayBuffer);
  6908. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6909. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6910. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6911. }, onLoad, samplingMode);
  6912. };
  6913. if (!(fromData instanceof Array))
  6914. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6915. callback(arrayBuffer);
  6916. }, onerror, scene.database, true);
  6917. else
  6918. callback(buffer);
  6919. }
  6920. else if (isDDS) {
  6921. callback = function (data) {
  6922. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6923. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6924. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6925. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6926. }, onLoad, samplingMode);
  6927. };
  6928. if (!(fromData instanceof Array))
  6929. BABYLON.Tools.LoadFile(url, function (data) {
  6930. callback(data);
  6931. }, onerror, scene.database, true);
  6932. else
  6933. callback(buffer);
  6934. }
  6935. else {
  6936. var onload = function (img) {
  6937. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6938. var isPot = (img.width === potWidth && img.height === potHeight);
  6939. if (!isPot) {
  6940. _this._prepareWorkingCanvas();
  6941. _this._workingCanvas.width = potWidth;
  6942. _this._workingCanvas.height = potHeight;
  6943. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6944. _this._workingContext.imageSmoothingEnabled = false;
  6945. _this._workingContext.mozImageSmoothingEnabled = false;
  6946. _this._workingContext.oImageSmoothingEnabled = false;
  6947. _this._workingContext.webkitImageSmoothingEnabled = false;
  6948. _this._workingContext.msImageSmoothingEnabled = false;
  6949. }
  6950. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6951. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6952. _this._workingContext.imageSmoothingEnabled = true;
  6953. _this._workingContext.mozImageSmoothingEnabled = true;
  6954. _this._workingContext.oImageSmoothingEnabled = true;
  6955. _this._workingContext.webkitImageSmoothingEnabled = true;
  6956. _this._workingContext.msImageSmoothingEnabled = true;
  6957. }
  6958. }
  6959. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6960. }, onLoad, samplingMode);
  6961. };
  6962. if (!(fromData instanceof Array))
  6963. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6964. else
  6965. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6966. }
  6967. return texture;
  6968. };
  6969. Engine.prototype._getInternalFormat = function (format) {
  6970. var internalFormat = this._gl.RGBA;
  6971. switch (format) {
  6972. case Engine.TEXTUREFORMAT_ALPHA:
  6973. internalFormat = this._gl.ALPHA;
  6974. break;
  6975. case Engine.TEXTUREFORMAT_LUMINANCE:
  6976. internalFormat = this._gl.LUMINANCE;
  6977. break;
  6978. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6979. internalFormat = this._gl.LUMINANCE_ALPHA;
  6980. break;
  6981. case Engine.TEXTUREFORMAT_RGB:
  6982. internalFormat = this._gl.RGB;
  6983. break;
  6984. case Engine.TEXTUREFORMAT_RGBA:
  6985. internalFormat = this._gl.RGBA;
  6986. break;
  6987. }
  6988. return internalFormat;
  6989. };
  6990. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6991. if (compression === void 0) { compression = null; }
  6992. var internalFormat = this._getInternalFormat(format);
  6993. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6994. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6995. if (texture._width % 4 !== 0) {
  6996. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  6997. }
  6998. if (compression) {
  6999. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7000. }
  7001. else {
  7002. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7003. }
  7004. if (texture.generateMipMaps) {
  7005. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7006. }
  7007. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7008. this.resetTextureCache();
  7009. texture.isReady = true;
  7010. };
  7011. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7012. if (compression === void 0) { compression = null; }
  7013. var texture = this._gl.createTexture();
  7014. texture._baseWidth = width;
  7015. texture._baseHeight = height;
  7016. texture._width = width;
  7017. texture._height = height;
  7018. texture.references = 1;
  7019. this.updateRawTexture(texture, data, format, invertY, compression);
  7020. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7021. // Filters
  7022. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7023. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7024. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7025. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7026. texture.samplingMode = samplingMode;
  7027. this._loadedTexturesCache.push(texture);
  7028. return texture;
  7029. };
  7030. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  7031. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  7032. var texture = this._gl.createTexture();
  7033. texture._baseWidth = width;
  7034. texture._baseHeight = height;
  7035. if (forceExponantOfTwo) {
  7036. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7037. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7038. }
  7039. this.resetTextureCache();
  7040. texture._width = width;
  7041. texture._height = height;
  7042. texture.isReady = false;
  7043. texture.generateMipMaps = generateMipMaps;
  7044. texture.references = 1;
  7045. texture.samplingMode = samplingMode;
  7046. this.updateTextureSamplingMode(samplingMode, texture);
  7047. this._loadedTexturesCache.push(texture);
  7048. return texture;
  7049. };
  7050. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7051. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7052. if (texture.isCube) {
  7053. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  7054. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7055. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7056. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7057. }
  7058. else {
  7059. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7060. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7061. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7062. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7063. }
  7064. };
  7065. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7066. if (premulAlpha === void 0) { premulAlpha = false; }
  7067. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7068. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7069. if (premulAlpha) {
  7070. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7071. }
  7072. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7073. if (texture.generateMipMaps) {
  7074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7075. }
  7076. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7077. this.resetTextureCache();
  7078. texture.isReady = true;
  7079. };
  7080. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7081. if (texture._isDisabled) {
  7082. return;
  7083. }
  7084. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7085. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7086. try {
  7087. // Testing video texture support
  7088. if (this._videoTextureSupported === undefined) {
  7089. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7090. if (this._gl.getError() !== 0) {
  7091. this._videoTextureSupported = false;
  7092. }
  7093. else {
  7094. this._videoTextureSupported = true;
  7095. }
  7096. }
  7097. // Copy video through the current working canvas if video texture is not supported
  7098. if (!this._videoTextureSupported) {
  7099. if (!texture._workingCanvas) {
  7100. texture._workingCanvas = document.createElement("canvas");
  7101. texture._workingContext = texture._workingCanvas.getContext("2d");
  7102. texture._workingCanvas.width = texture._width;
  7103. texture._workingCanvas.height = texture._height;
  7104. }
  7105. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7106. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7107. }
  7108. else {
  7109. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7110. }
  7111. if (texture.generateMipMaps) {
  7112. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7113. }
  7114. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7115. this.resetTextureCache();
  7116. texture.isReady = true;
  7117. }
  7118. catch (ex) {
  7119. // Something unexpected
  7120. // Let's disable the texture
  7121. texture._isDisabled = true;
  7122. }
  7123. };
  7124. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7125. // old version had a "generateMipMaps" arg instead of options.
  7126. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7127. // in the same way, generateDepthBuffer is defaulted to true
  7128. var generateMipMaps = false;
  7129. var generateDepthBuffer = true;
  7130. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7131. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7132. if (options !== undefined) {
  7133. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7134. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7135. type = options.type === undefined ? type : options.type;
  7136. if (options.samplingMode !== undefined) {
  7137. samplingMode = options.samplingMode;
  7138. }
  7139. if (type === Engine.TEXTURETYPE_FLOAT) {
  7140. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7141. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7142. }
  7143. }
  7144. var gl = this._gl;
  7145. var texture = gl.createTexture();
  7146. gl.bindTexture(gl.TEXTURE_2D, texture);
  7147. var width = size.width || size;
  7148. var height = size.height || size;
  7149. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7150. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7151. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7152. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7153. }
  7154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7156. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7158. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7159. var depthBuffer;
  7160. // Create the depth buffer
  7161. if (generateDepthBuffer) {
  7162. depthBuffer = gl.createRenderbuffer();
  7163. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7164. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7165. }
  7166. // Create the framebuffer
  7167. var framebuffer = gl.createFramebuffer();
  7168. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  7169. if (generateDepthBuffer) {
  7170. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7171. }
  7172. if (generateMipMaps) {
  7173. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7174. }
  7175. // Unbind
  7176. gl.bindTexture(gl.TEXTURE_2D, null);
  7177. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7178. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7179. texture._framebuffer = framebuffer;
  7180. if (generateDepthBuffer) {
  7181. texture._depthBuffer = depthBuffer;
  7182. }
  7183. texture._baseWidth = width;
  7184. texture._baseHeight = height;
  7185. texture._width = width;
  7186. texture._height = height;
  7187. texture.isReady = true;
  7188. texture.generateMipMaps = generateMipMaps;
  7189. texture.references = 1;
  7190. texture.samplingMode = samplingMode;
  7191. this.resetTextureCache();
  7192. this._loadedTexturesCache.push(texture);
  7193. return texture;
  7194. };
  7195. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7196. var gl = this._gl;
  7197. var texture = gl.createTexture();
  7198. var generateMipMaps = true;
  7199. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7200. if (options !== undefined) {
  7201. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7202. if (options.samplingMode !== undefined) {
  7203. samplingMode = options.samplingMode;
  7204. }
  7205. }
  7206. texture.isCube = true;
  7207. texture.references = 1;
  7208. texture.generateMipMaps = generateMipMaps;
  7209. texture.references = 1;
  7210. texture.samplingMode = samplingMode;
  7211. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7212. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7213. for (var face = 0; face < 6; face++) {
  7214. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7215. }
  7216. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7217. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7218. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7220. // Create the depth buffer
  7221. var depthBuffer = gl.createRenderbuffer();
  7222. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7223. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7224. // Create the framebuffer
  7225. var framebuffer = gl.createFramebuffer();
  7226. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  7227. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7228. // Mipmaps
  7229. if (texture.generateMipMaps) {
  7230. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7231. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7232. }
  7233. // Unbind
  7234. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7235. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7236. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7237. texture._framebuffer = framebuffer;
  7238. texture._depthBuffer = depthBuffer;
  7239. this.resetTextureCache();
  7240. texture._width = size;
  7241. texture._height = size;
  7242. texture.isReady = true;
  7243. return texture;
  7244. };
  7245. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7246. var _this = this;
  7247. var gl = this._gl;
  7248. var texture = gl.createTexture();
  7249. texture.isCube = true;
  7250. texture.url = rootUrl;
  7251. texture.references = 1;
  7252. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7253. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7254. if (isDDS) {
  7255. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7256. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7257. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7258. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7259. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7260. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7261. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7262. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7263. }
  7264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7268. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7269. _this.resetTextureCache();
  7270. texture._width = info.width;
  7271. texture._height = info.height;
  7272. texture.isReady = true;
  7273. }, null, null, true);
  7274. }
  7275. else {
  7276. cascadeLoad(rootUrl, scene, function (imgs) {
  7277. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7278. var height = width;
  7279. _this._prepareWorkingCanvas();
  7280. _this._workingCanvas.width = width;
  7281. _this._workingCanvas.height = height;
  7282. var faces = [
  7283. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7284. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7285. ];
  7286. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7287. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7288. for (var index = 0; index < faces.length; index++) {
  7289. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7290. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7291. }
  7292. if (!noMipmap) {
  7293. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7294. }
  7295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7299. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7300. _this.resetTextureCache();
  7301. texture._width = width;
  7302. texture._height = height;
  7303. texture.isReady = true;
  7304. }, files);
  7305. }
  7306. return texture;
  7307. };
  7308. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7309. texture._width = width;
  7310. texture._height = height;
  7311. texture._size = width * height;
  7312. texture._baseWidth = width;
  7313. texture._baseHeight = height;
  7314. };
  7315. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7316. var _this = this;
  7317. var gl = this._gl;
  7318. var texture = gl.createTexture();
  7319. scene._addPendingData(texture);
  7320. texture.isCube = true;
  7321. texture.references = 1;
  7322. texture.url = url;
  7323. var internalFormat = this._getInternalFormat(format);
  7324. var textureType = gl.UNSIGNED_BYTE;
  7325. if (type === Engine.TEXTURETYPE_FLOAT) {
  7326. textureType = gl.FLOAT;
  7327. }
  7328. var width = size;
  7329. var height = width;
  7330. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7331. texture._width = width;
  7332. texture._height = height;
  7333. var onerror = function () {
  7334. scene._removePendingData(texture);
  7335. };
  7336. var internalCallback = function (data) {
  7337. var rgbeDataArrays = callback(data);
  7338. var facesIndex = [
  7339. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7340. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7341. ];
  7342. width = texture._width;
  7343. height = texture._height;
  7344. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7345. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7346. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7347. if (!noMipmap && isPot) {
  7348. if (mipmmapGenerator) {
  7349. var arrayTemp = [];
  7350. // Data are known to be in +X +Y +Z -X -Y -Z
  7351. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7352. arrayTemp.push(rgbeDataArrays[0]); // +X
  7353. arrayTemp.push(rgbeDataArrays[3]); // -X
  7354. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7355. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7356. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7357. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7358. var mipData = mipmmapGenerator(arrayTemp);
  7359. for (var level = 0; level < mipData.length; level++) {
  7360. var mipSize = width >> level;
  7361. // mipData is order in +X -X +Y -Y +Z -Z
  7362. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7363. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7364. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7365. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7366. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7367. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7368. }
  7369. }
  7370. else {
  7371. // Data are known to be in +X +Y +Z -X -Y -Z
  7372. for (var index = 0; index < facesIndex.length; index++) {
  7373. var faceData = rgbeDataArrays[index];
  7374. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7375. }
  7376. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7377. }
  7378. }
  7379. else {
  7380. noMipmap = true;
  7381. }
  7382. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7385. }
  7386. else {
  7387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7388. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7389. }
  7390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7391. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7392. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7393. texture.isReady = true;
  7394. _this.resetTextureCache();
  7395. scene._removePendingData(texture);
  7396. };
  7397. BABYLON.Tools.LoadFile(url, function (data) {
  7398. internalCallback(data);
  7399. }, onerror, scene.database, true);
  7400. return texture;
  7401. };
  7402. ;
  7403. Engine.prototype._releaseTexture = function (texture) {
  7404. var gl = this._gl;
  7405. if (texture._framebuffer) {
  7406. gl.deleteFramebuffer(texture._framebuffer);
  7407. }
  7408. if (texture._depthBuffer) {
  7409. gl.deleteRenderbuffer(texture._depthBuffer);
  7410. }
  7411. gl.deleteTexture(texture);
  7412. // Unbind channels
  7413. this.unbindAllTextures();
  7414. var index = this._loadedTexturesCache.indexOf(texture);
  7415. if (index !== -1) {
  7416. this._loadedTexturesCache.splice(index, 1);
  7417. }
  7418. };
  7419. Engine.prototype.bindSamplers = function (effect) {
  7420. this._gl.useProgram(effect.getProgram());
  7421. var samplers = effect.getSamplers();
  7422. for (var index = 0; index < samplers.length; index++) {
  7423. var uniform = effect.getUniform(samplers[index]);
  7424. this._gl.uniform1i(uniform, index);
  7425. }
  7426. this._currentEffect = null;
  7427. };
  7428. Engine.prototype._bindTexture = function (channel, texture) {
  7429. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7430. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7431. this._activeTexturesCache[channel] = null;
  7432. };
  7433. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7434. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7435. };
  7436. Engine.prototype.unbindAllTextures = function () {
  7437. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7438. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7439. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7440. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7441. this._activeTexturesCache[channel] = null;
  7442. }
  7443. };
  7444. Engine.prototype.setTexture = function (channel, texture) {
  7445. if (channel < 0) {
  7446. return;
  7447. }
  7448. // Not ready?
  7449. if (!texture || !texture.isReady()) {
  7450. if (this._activeTexturesCache[channel] != null) {
  7451. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7452. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7453. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7454. this._activeTexturesCache[channel] = null;
  7455. }
  7456. return;
  7457. }
  7458. // Video
  7459. var alreadyActivated = false;
  7460. if (texture instanceof BABYLON.VideoTexture) {
  7461. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7462. alreadyActivated = true;
  7463. texture.update();
  7464. }
  7465. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7466. texture.delayLoad();
  7467. return;
  7468. }
  7469. if (this._activeTexturesCache[channel] === texture) {
  7470. return;
  7471. }
  7472. this._activeTexturesCache[channel] = texture;
  7473. var internalTexture = texture.getInternalTexture();
  7474. if (!alreadyActivated) {
  7475. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7476. }
  7477. if (internalTexture.isCube) {
  7478. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7479. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7480. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7481. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7482. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7483. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7484. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7485. }
  7486. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7487. }
  7488. else {
  7489. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7490. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7491. internalTexture._cachedWrapU = texture.wrapU;
  7492. switch (texture.wrapU) {
  7493. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7494. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7495. break;
  7496. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7497. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7498. break;
  7499. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7500. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7501. break;
  7502. }
  7503. }
  7504. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7505. internalTexture._cachedWrapV = texture.wrapV;
  7506. switch (texture.wrapV) {
  7507. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7508. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7509. break;
  7510. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7511. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7512. break;
  7513. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7514. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7515. break;
  7516. }
  7517. }
  7518. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7519. }
  7520. };
  7521. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7522. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7523. var value = texture.anisotropicFilteringLevel;
  7524. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7525. value = 1;
  7526. }
  7527. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7528. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7529. texture._cachedAnisotropicFilteringLevel = value;
  7530. }
  7531. };
  7532. Engine.prototype.readPixels = function (x, y, width, height) {
  7533. var data = new Uint8Array(height * width * 4);
  7534. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7535. return data;
  7536. };
  7537. /**
  7538. * Add an externaly attached data from its key.
  7539. * This method call will fail and return false, if such key already exists.
  7540. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7541. * @param key the unique key that identifies the data
  7542. * @param data the data object to associate to the key for this Engine instance
  7543. * @return true if no such key were already present and the data was added successfully, false otherwise
  7544. */
  7545. Engine.prototype.addExternalData = function (key, data) {
  7546. return this._externalData.add(key, data);
  7547. };
  7548. /**
  7549. * Get an externaly attached data from its key
  7550. * @param key the unique key that identifies the data
  7551. * @return the associated data, if present (can be null), or undefined if not present
  7552. */
  7553. Engine.prototype.getExternalData = function (key) {
  7554. return this._externalData.get(key);
  7555. };
  7556. /**
  7557. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7558. * @param key the unique key that identifies the data
  7559. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7560. * @return the associated data, can be null if the factory returned null.
  7561. */
  7562. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7563. return this._externalData.getOrAddWithFactory(key, factory);
  7564. };
  7565. /**
  7566. * Remove an externaly attached data from the Engine instance
  7567. * @param key the unique key that identifies the data
  7568. * @return true if the data was successfully removed, false if it doesn't exist
  7569. */
  7570. Engine.prototype.removeExternalData = function (key) {
  7571. return this._externalData.remove(key);
  7572. };
  7573. Engine.prototype.releaseInternalTexture = function (texture) {
  7574. if (!texture) {
  7575. return;
  7576. }
  7577. texture.references--;
  7578. // Final reference ?
  7579. if (texture.references === 0) {
  7580. var texturesCache = this.getLoadedTexturesCache();
  7581. var index = texturesCache.indexOf(texture);
  7582. if (index > -1) {
  7583. texturesCache.splice(index, 1);
  7584. }
  7585. this._releaseTexture(texture);
  7586. }
  7587. };
  7588. // Dispose
  7589. Engine.prototype.dispose = function () {
  7590. this.hideLoadingUI();
  7591. this.stopRenderLoop();
  7592. // Release scenes
  7593. while (this.scenes.length) {
  7594. this.scenes[0].dispose();
  7595. }
  7596. // Release audio engine
  7597. Engine.audioEngine.dispose();
  7598. // Release effects
  7599. for (var name in this._compiledEffects) {
  7600. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7601. }
  7602. // Unbind
  7603. for (var i in this._vertexAttribArrays) {
  7604. //making sure this is a string
  7605. var iAsNumber = +i;
  7606. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7607. continue;
  7608. }
  7609. this._gl.disableVertexAttribArray(iAsNumber);
  7610. }
  7611. this._gl = null;
  7612. // Events
  7613. window.removeEventListener("blur", this._onBlur);
  7614. window.removeEventListener("focus", this._onFocus);
  7615. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7616. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7617. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7618. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7619. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7620. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7621. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7622. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7623. };
  7624. // Loading screen
  7625. Engine.prototype.displayLoadingUI = function () {
  7626. this._loadingScreen.displayLoadingUI();
  7627. };
  7628. Engine.prototype.hideLoadingUI = function () {
  7629. this._loadingScreen.hideLoadingUI();
  7630. };
  7631. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7632. get: function () {
  7633. return this._loadingScreen;
  7634. },
  7635. set: function (loadingScreen) {
  7636. this._loadingScreen = loadingScreen;
  7637. },
  7638. enumerable: true,
  7639. configurable: true
  7640. });
  7641. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7642. set: function (text) {
  7643. this._loadingScreen.loadingUIText = text;
  7644. },
  7645. enumerable: true,
  7646. configurable: true
  7647. });
  7648. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7649. set: function (color) {
  7650. this._loadingScreen.loadingUIBackgroundColor = color;
  7651. },
  7652. enumerable: true,
  7653. configurable: true
  7654. });
  7655. // FPS
  7656. Engine.prototype.getFps = function () {
  7657. return this.fps;
  7658. };
  7659. Engine.prototype.getDeltaTime = function () {
  7660. return this.deltaTime;
  7661. };
  7662. Engine.prototype._measureFps = function () {
  7663. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7664. var length = this.previousFramesDuration.length;
  7665. if (length >= 2) {
  7666. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7667. }
  7668. if (length >= this.fpsRange) {
  7669. if (length > this.fpsRange) {
  7670. this.previousFramesDuration.splice(0, 1);
  7671. length = this.previousFramesDuration.length;
  7672. }
  7673. var sum = 0;
  7674. for (var id = 0; id < length - 1; id++) {
  7675. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7676. }
  7677. this.fps = 1000.0 / (sum / (length - 1));
  7678. }
  7679. };
  7680. // Statics
  7681. Engine.isSupported = function () {
  7682. try {
  7683. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7684. if (navigator.isCocoonJS) {
  7685. return true;
  7686. }
  7687. var tempcanvas = document.createElement("canvas");
  7688. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7689. return gl != null && !!window.WebGLRenderingContext;
  7690. }
  7691. catch (e) {
  7692. return false;
  7693. }
  7694. };
  7695. // Const statics
  7696. Engine._ALPHA_DISABLE = 0;
  7697. Engine._ALPHA_ADD = 1;
  7698. Engine._ALPHA_COMBINE = 2;
  7699. Engine._ALPHA_SUBTRACT = 3;
  7700. Engine._ALPHA_MULTIPLY = 4;
  7701. Engine._ALPHA_MAXIMIZED = 5;
  7702. Engine._ALPHA_ONEONE = 6;
  7703. Engine._DELAYLOADSTATE_NONE = 0;
  7704. Engine._DELAYLOADSTATE_LOADED = 1;
  7705. Engine._DELAYLOADSTATE_LOADING = 2;
  7706. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7707. Engine._TEXTUREFORMAT_ALPHA = 0;
  7708. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7709. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7710. Engine._TEXTUREFORMAT_RGB = 4;
  7711. Engine._TEXTUREFORMAT_RGBA = 5;
  7712. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7713. Engine._TEXTURETYPE_FLOAT = 1;
  7714. // Updatable statics so stick with vars here
  7715. Engine.CollisionsEpsilon = 0.001;
  7716. Engine.CodeRepository = "src/";
  7717. Engine.ShadersRepository = "src/Shaders/";
  7718. return Engine;
  7719. })();
  7720. BABYLON.Engine = Engine;
  7721. })(BABYLON || (BABYLON = {}));
  7722. var BABYLON;
  7723. (function (BABYLON) {
  7724. /**
  7725. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7726. */
  7727. var Node = (function () {
  7728. /**
  7729. * @constructor
  7730. * @param {string} name - the name and id to be given to this node
  7731. * @param {BABYLON.Scene} the scene this node will be added to
  7732. */
  7733. function Node(name, scene) {
  7734. this.state = "";
  7735. this.animations = new Array();
  7736. this._ranges = {};
  7737. this._childrenFlag = -1;
  7738. this._isEnabled = true;
  7739. this._isReady = true;
  7740. this._currentRenderId = -1;
  7741. this._parentRenderId = -1;
  7742. this.name = name;
  7743. this.id = name;
  7744. this._scene = scene;
  7745. this._initCache();
  7746. }
  7747. Object.defineProperty(Node.prototype, "parent", {
  7748. get: function () {
  7749. return this._parentNode;
  7750. },
  7751. set: function (parent) {
  7752. if (this._parentNode === parent) {
  7753. return;
  7754. }
  7755. if (this._parentNode) {
  7756. var index = this._parentNode._children.indexOf(this);
  7757. if (index !== -1) {
  7758. this._parentNode._children.splice(index, 1);
  7759. }
  7760. }
  7761. this._parentNode = parent;
  7762. if (this._parentNode) {
  7763. if (!this._parentNode._children) {
  7764. this._parentNode._children = new Array();
  7765. }
  7766. this._parentNode._children.push(this);
  7767. }
  7768. },
  7769. enumerable: true,
  7770. configurable: true
  7771. });
  7772. Node.prototype.getScene = function () {
  7773. return this._scene;
  7774. };
  7775. Node.prototype.getEngine = function () {
  7776. return this._scene.getEngine();
  7777. };
  7778. // override it in derived class
  7779. Node.prototype.getWorldMatrix = function () {
  7780. return BABYLON.Matrix.Identity();
  7781. };
  7782. // override it in derived class if you add new variables to the cache
  7783. // and call the parent class method
  7784. Node.prototype._initCache = function () {
  7785. this._cache = {};
  7786. this._cache.parent = undefined;
  7787. };
  7788. Node.prototype.updateCache = function (force) {
  7789. if (!force && this.isSynchronized())
  7790. return;
  7791. this._cache.parent = this.parent;
  7792. this._updateCache();
  7793. };
  7794. // override it in derived class if you add new variables to the cache
  7795. // and call the parent class method if !ignoreParentClass
  7796. Node.prototype._updateCache = function (ignoreParentClass) {
  7797. };
  7798. // override it in derived class if you add new variables to the cache
  7799. Node.prototype._isSynchronized = function () {
  7800. return true;
  7801. };
  7802. Node.prototype._markSyncedWithParent = function () {
  7803. this._parentRenderId = this.parent._currentRenderId;
  7804. };
  7805. Node.prototype.isSynchronizedWithParent = function () {
  7806. if (!this.parent) {
  7807. return true;
  7808. }
  7809. if (this._parentRenderId !== this.parent._currentRenderId) {
  7810. return false;
  7811. }
  7812. return this.parent.isSynchronized();
  7813. };
  7814. Node.prototype.isSynchronized = function (updateCache) {
  7815. var check = this.hasNewParent();
  7816. check = check || !this.isSynchronizedWithParent();
  7817. check = check || !this._isSynchronized();
  7818. if (updateCache)
  7819. this.updateCache(true);
  7820. return !check;
  7821. };
  7822. Node.prototype.hasNewParent = function (update) {
  7823. if (this._cache.parent === this.parent)
  7824. return false;
  7825. if (update)
  7826. this._cache.parent = this.parent;
  7827. return true;
  7828. };
  7829. /**
  7830. * Is this node ready to be used/rendered
  7831. * @return {boolean} is it ready
  7832. */
  7833. Node.prototype.isReady = function () {
  7834. return this._isReady;
  7835. };
  7836. /**
  7837. * Is this node enabled.
  7838. * If the node has a parent and is enabled, the parent will be inspected as well.
  7839. * @return {boolean} whether this node (and its parent) is enabled.
  7840. * @see setEnabled
  7841. */
  7842. Node.prototype.isEnabled = function () {
  7843. if (!this._isEnabled) {
  7844. return false;
  7845. }
  7846. if (this.parent) {
  7847. return this.parent.isEnabled();
  7848. }
  7849. return true;
  7850. };
  7851. /**
  7852. * Set the enabled state of this node.
  7853. * @param {boolean} value - the new enabled state
  7854. * @see isEnabled
  7855. */
  7856. Node.prototype.setEnabled = function (value) {
  7857. this._isEnabled = value;
  7858. };
  7859. /**
  7860. * Is this node a descendant of the given node.
  7861. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7862. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7863. * @see parent
  7864. */
  7865. Node.prototype.isDescendantOf = function (ancestor) {
  7866. if (this.parent) {
  7867. if (this.parent === ancestor) {
  7868. return true;
  7869. }
  7870. return this.parent.isDescendantOf(ancestor);
  7871. }
  7872. return false;
  7873. };
  7874. /**
  7875. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7876. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7877. * @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.
  7878. * @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.
  7879. */
  7880. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7881. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7882. if (!this._children) {
  7883. return;
  7884. }
  7885. for (var index = 0; index < this._children.length; index++) {
  7886. var item = this._children[index];
  7887. if (!predicate || predicate(item)) {
  7888. results.push(item);
  7889. }
  7890. if (!directDescendantsOnly) {
  7891. item._getDescendants(results, false, predicate);
  7892. }
  7893. }
  7894. };
  7895. /**
  7896. * Will return all nodes that have this node as ascendant.
  7897. * @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.
  7898. * @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.
  7899. * @return {BABYLON.Node[]} all children nodes of all types.
  7900. */
  7901. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7902. var results = [];
  7903. this._getDescendants(results, directDescendantsOnly, predicate);
  7904. return results;
  7905. };
  7906. /**
  7907. * @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.
  7908. * @Deprecated, legacy support.
  7909. * use getDecendants instead.
  7910. */
  7911. Node.prototype.getChildren = function (predicate) {
  7912. return this.getDescendants(true, predicate);
  7913. };
  7914. /**
  7915. * Get all child-meshes of this node.
  7916. */
  7917. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7918. var results = [];
  7919. this._getDescendants(results, directDecendantsOnly, function (node) {
  7920. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7921. });
  7922. return results;
  7923. };
  7924. Node.prototype._setReady = function (state) {
  7925. if (state === this._isReady) {
  7926. return;
  7927. }
  7928. if (!state) {
  7929. this._isReady = false;
  7930. return;
  7931. }
  7932. this._isReady = true;
  7933. if (this.onReady) {
  7934. this.onReady(this);
  7935. }
  7936. };
  7937. Node.prototype.getAnimationByName = function (name) {
  7938. for (var i = 0; i < this.animations.length; i++) {
  7939. var animation = this.animations[i];
  7940. if (animation.name === name) {
  7941. return animation;
  7942. }
  7943. }
  7944. return null;
  7945. };
  7946. Node.prototype.createAnimationRange = function (name, from, to) {
  7947. // check name not already in use
  7948. if (!this._ranges[name]) {
  7949. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7950. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7951. if (this.animations[i]) {
  7952. this.animations[i].createRange(name, from, to);
  7953. }
  7954. }
  7955. }
  7956. };
  7957. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7958. if (deleteFrames === void 0) { deleteFrames = true; }
  7959. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7960. if (this.animations[i]) {
  7961. this.animations[i].deleteRange(name, deleteFrames);
  7962. }
  7963. }
  7964. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7965. };
  7966. Node.prototype.getAnimationRange = function (name) {
  7967. return this._ranges[name];
  7968. };
  7969. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7970. var range = this.getAnimationRange(name);
  7971. if (!range) {
  7972. return null;
  7973. }
  7974. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7975. };
  7976. Node.prototype.serializeAnimationRanges = function () {
  7977. var serializationRanges = [];
  7978. for (var name in this._ranges) {
  7979. var range = {};
  7980. range.name = name;
  7981. range.from = this._ranges[name].from;
  7982. range.to = this._ranges[name].to;
  7983. serializationRanges.push(range);
  7984. }
  7985. return serializationRanges;
  7986. };
  7987. Node.prototype.dispose = function () {
  7988. this.parent = null;
  7989. };
  7990. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7991. if (parsedNode.ranges) {
  7992. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7993. var data = parsedNode.ranges[index];
  7994. node.createAnimationRange(data.name, data.from, data.to);
  7995. }
  7996. }
  7997. };
  7998. __decorate([
  7999. BABYLON.serialize()
  8000. ], Node.prototype, "name", void 0);
  8001. __decorate([
  8002. BABYLON.serialize()
  8003. ], Node.prototype, "id", void 0);
  8004. __decorate([
  8005. BABYLON.serialize()
  8006. ], Node.prototype, "uniqueId", void 0);
  8007. __decorate([
  8008. BABYLON.serialize()
  8009. ], Node.prototype, "state", void 0);
  8010. return Node;
  8011. })();
  8012. BABYLON.Node = Node;
  8013. })(BABYLON || (BABYLON = {}));
  8014. var BABYLON;
  8015. (function (BABYLON) {
  8016. var FilesInput = (function () {
  8017. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8018. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8019. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8020. this._engine = p_engine;
  8021. this._canvas = p_canvas;
  8022. this._currentScene = p_scene;
  8023. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8024. this._progressCallback = p_progressCallback;
  8025. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8026. this._textureLoadingCallback = p_textureLoadingCallback;
  8027. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8028. }
  8029. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8030. var _this = this;
  8031. if (p_elementToMonitor) {
  8032. this._elementToMonitor = p_elementToMonitor;
  8033. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8034. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8035. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8036. }
  8037. };
  8038. FilesInput.prototype.renderFunction = function () {
  8039. if (this._additionnalRenderLoopLogicCallback) {
  8040. this._additionnalRenderLoopLogicCallback();
  8041. }
  8042. if (this._currentScene) {
  8043. if (this._textureLoadingCallback) {
  8044. var remaining = this._currentScene.getWaitingItemsCount();
  8045. if (remaining > 0) {
  8046. this._textureLoadingCallback(remaining);
  8047. }
  8048. }
  8049. this._currentScene.render();
  8050. }
  8051. };
  8052. FilesInput.prototype.drag = function (e) {
  8053. e.stopPropagation();
  8054. e.preventDefault();
  8055. };
  8056. FilesInput.prototype.drop = function (eventDrop) {
  8057. eventDrop.stopPropagation();
  8058. eventDrop.preventDefault();
  8059. this.loadFiles(eventDrop);
  8060. };
  8061. FilesInput.prototype.loadFiles = function (event) {
  8062. if (this._startingProcessingFilesCallback)
  8063. this._startingProcessingFilesCallback();
  8064. // Handling data transfer via drag'n'drop
  8065. if (event && event.dataTransfer && event.dataTransfer.files) {
  8066. this._filesToLoad = event.dataTransfer.files;
  8067. }
  8068. // Handling files from input files
  8069. if (event && event.target && event.target.files) {
  8070. this._filesToLoad = event.target.files;
  8071. }
  8072. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8073. for (var i = 0; i < this._filesToLoad.length; i++) {
  8074. switch (this._filesToLoad[i].type) {
  8075. case "image/jpeg":
  8076. case "image/png":
  8077. case "image/bmp":
  8078. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8079. break;
  8080. case "image/targa":
  8081. case "image/vnd.ms-dds":
  8082. case "audio/wav":
  8083. case "audio/x-wav":
  8084. case "audio/mp3":
  8085. case "audio/mpeg":
  8086. case "audio/mpeg3":
  8087. case "audio/x-mpeg-3":
  8088. case "audio/ogg":
  8089. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8090. break;
  8091. default:
  8092. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8093. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8094. }
  8095. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8096. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8097. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8098. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8099. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8100. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8101. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8102. this._sceneFileToLoad = this._filesToLoad[i];
  8103. }
  8104. break;
  8105. }
  8106. }
  8107. this.reload();
  8108. }
  8109. };
  8110. FilesInput.prototype.reload = function () {
  8111. var _this = this;
  8112. var that = this;
  8113. // If a ".babylon" file has been provided
  8114. if (this._sceneFileToLoad) {
  8115. if (this._currentScene) {
  8116. if (BABYLON.Tools.errorsCount > 0) {
  8117. BABYLON.Tools.ClearLogCache();
  8118. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8119. }
  8120. this._engine.stopRenderLoop();
  8121. this._currentScene.dispose();
  8122. }
  8123. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8124. that._currentScene = newScene;
  8125. // Wait for textures and shaders to be ready
  8126. that._currentScene.executeWhenReady(function () {
  8127. // Attach camera to canvas inputs
  8128. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8129. that._currentScene.createDefaultCameraOrLight();
  8130. }
  8131. that._currentScene.activeCamera.attachControl(that._canvas);
  8132. if (that._sceneLoadedCallback) {
  8133. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8134. }
  8135. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8136. });
  8137. }, function (progress) {
  8138. if (_this._progressCallback) {
  8139. _this._progressCallback(progress);
  8140. }
  8141. });
  8142. }
  8143. else {
  8144. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8145. }
  8146. };
  8147. FilesInput.FilesTextures = new Array();
  8148. FilesInput.FilesToLoad = new Array();
  8149. return FilesInput;
  8150. })();
  8151. BABYLON.FilesInput = FilesInput;
  8152. })(BABYLON || (BABYLON = {}));
  8153. var BABYLON;
  8154. (function (BABYLON) {
  8155. var IntersectionInfo = (function () {
  8156. function IntersectionInfo(bu, bv, distance) {
  8157. this.bu = bu;
  8158. this.bv = bv;
  8159. this.distance = distance;
  8160. this.faceId = 0;
  8161. this.subMeshId = 0;
  8162. }
  8163. return IntersectionInfo;
  8164. })();
  8165. BABYLON.IntersectionInfo = IntersectionInfo;
  8166. var PickingInfo = (function () {
  8167. function PickingInfo() {
  8168. this.hit = false;
  8169. this.distance = 0;
  8170. this.pickedPoint = null;
  8171. this.pickedMesh = null;
  8172. this.bu = 0;
  8173. this.bv = 0;
  8174. this.faceId = -1;
  8175. this.subMeshId = 0;
  8176. this.pickedSprite = null;
  8177. }
  8178. // Methods
  8179. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8180. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8181. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8182. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8183. return null;
  8184. }
  8185. var indices = this.pickedMesh.getIndices();
  8186. var result;
  8187. if (useVerticesNormals) {
  8188. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8189. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8190. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8191. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8192. normal0 = normal0.scale(this.bu);
  8193. normal1 = normal1.scale(this.bv);
  8194. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8195. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8196. }
  8197. else {
  8198. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8199. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8200. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8201. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8202. var p1p2 = vertex1.subtract(vertex2);
  8203. var p3p2 = vertex3.subtract(vertex2);
  8204. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8205. }
  8206. if (useWorldCoordinates) {
  8207. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8208. }
  8209. return BABYLON.Vector3.Normalize(result);
  8210. };
  8211. PickingInfo.prototype.getTextureCoordinates = function () {
  8212. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8213. return null;
  8214. }
  8215. var indices = this.pickedMesh.getIndices();
  8216. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8217. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8218. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8219. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8220. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8221. uv1 = uv1.scale(this.bu);
  8222. uv2 = uv2.scale(this.bv);
  8223. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8224. };
  8225. return PickingInfo;
  8226. })();
  8227. BABYLON.PickingInfo = PickingInfo;
  8228. })(BABYLON || (BABYLON = {}));
  8229. var BABYLON;
  8230. (function (BABYLON) {
  8231. var BoundingSphere = (function () {
  8232. function BoundingSphere(minimum, maximum) {
  8233. this.minimum = minimum;
  8234. this.maximum = maximum;
  8235. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8236. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8237. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8238. this.radius = distance * 0.5;
  8239. this.centerWorld = BABYLON.Vector3.Zero();
  8240. this._update(BABYLON.Matrix.Identity());
  8241. }
  8242. // Methods
  8243. BoundingSphere.prototype._update = function (world) {
  8244. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8245. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8246. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8247. };
  8248. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8249. for (var i = 0; i < 6; i++) {
  8250. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8251. return false;
  8252. }
  8253. return true;
  8254. };
  8255. BoundingSphere.prototype.intersectsPoint = function (point) {
  8256. var x = this.centerWorld.x - point.x;
  8257. var y = this.centerWorld.y - point.y;
  8258. var z = this.centerWorld.z - point.z;
  8259. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8260. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8261. return false;
  8262. return true;
  8263. };
  8264. // Statics
  8265. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8266. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8267. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8268. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8269. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8270. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8271. return false;
  8272. return true;
  8273. };
  8274. return BoundingSphere;
  8275. })();
  8276. BABYLON.BoundingSphere = BoundingSphere;
  8277. })(BABYLON || (BABYLON = {}));
  8278. var BABYLON;
  8279. (function (BABYLON) {
  8280. var BoundingBox = (function () {
  8281. function BoundingBox(minimum, maximum) {
  8282. this.minimum = minimum;
  8283. this.maximum = maximum;
  8284. this.vectors = new Array();
  8285. this.vectorsWorld = new Array();
  8286. // Bounding vectors
  8287. this.vectors.push(this.minimum.clone());
  8288. this.vectors.push(this.maximum.clone());
  8289. this.vectors.push(this.minimum.clone());
  8290. this.vectors[2].x = this.maximum.x;
  8291. this.vectors.push(this.minimum.clone());
  8292. this.vectors[3].y = this.maximum.y;
  8293. this.vectors.push(this.minimum.clone());
  8294. this.vectors[4].z = this.maximum.z;
  8295. this.vectors.push(this.maximum.clone());
  8296. this.vectors[5].z = this.minimum.z;
  8297. this.vectors.push(this.maximum.clone());
  8298. this.vectors[6].x = this.minimum.x;
  8299. this.vectors.push(this.maximum.clone());
  8300. this.vectors[7].y = this.minimum.y;
  8301. // OBB
  8302. this.center = this.maximum.add(this.minimum).scale(0.5);
  8303. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8304. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8305. // World
  8306. for (var index = 0; index < this.vectors.length; index++) {
  8307. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8308. }
  8309. this.minimumWorld = BABYLON.Vector3.Zero();
  8310. this.maximumWorld = BABYLON.Vector3.Zero();
  8311. this._update(BABYLON.Matrix.Identity());
  8312. }
  8313. // Methods
  8314. BoundingBox.prototype.getWorldMatrix = function () {
  8315. return this._worldMatrix;
  8316. };
  8317. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8318. this._worldMatrix.copyFrom(matrix);
  8319. return this;
  8320. };
  8321. BoundingBox.prototype._update = function (world) {
  8322. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8323. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8324. for (var index = 0; index < this.vectors.length; index++) {
  8325. var v = this.vectorsWorld[index];
  8326. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8327. if (v.x < this.minimumWorld.x)
  8328. this.minimumWorld.x = v.x;
  8329. if (v.y < this.minimumWorld.y)
  8330. this.minimumWorld.y = v.y;
  8331. if (v.z < this.minimumWorld.z)
  8332. this.minimumWorld.z = v.z;
  8333. if (v.x > this.maximumWorld.x)
  8334. this.maximumWorld.x = v.x;
  8335. if (v.y > this.maximumWorld.y)
  8336. this.maximumWorld.y = v.y;
  8337. if (v.z > this.maximumWorld.z)
  8338. this.maximumWorld.z = v.z;
  8339. }
  8340. // OBB
  8341. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8342. this.center.scaleInPlace(0.5);
  8343. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8344. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8345. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8346. this._worldMatrix = world;
  8347. };
  8348. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8349. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8350. };
  8351. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8352. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8353. };
  8354. BoundingBox.prototype.intersectsPoint = function (point) {
  8355. var delta = -BABYLON.Epsilon;
  8356. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8357. return false;
  8358. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8359. return false;
  8360. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8361. return false;
  8362. return true;
  8363. };
  8364. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8365. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8366. };
  8367. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8368. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8369. return false;
  8370. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8371. return false;
  8372. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8373. return false;
  8374. return true;
  8375. };
  8376. // Statics
  8377. BoundingBox.Intersects = function (box0, box1) {
  8378. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8379. return false;
  8380. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8381. return false;
  8382. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8383. return false;
  8384. return true;
  8385. };
  8386. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8387. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8388. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8389. return (num <= (sphereRadius * sphereRadius));
  8390. };
  8391. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8392. for (var p = 0; p < 6; p++) {
  8393. for (var i = 0; i < 8; i++) {
  8394. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8395. return false;
  8396. }
  8397. }
  8398. }
  8399. return true;
  8400. };
  8401. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8402. for (var p = 0; p < 6; p++) {
  8403. var inCount = 8;
  8404. for (var i = 0; i < 8; i++) {
  8405. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8406. --inCount;
  8407. }
  8408. else {
  8409. break;
  8410. }
  8411. }
  8412. if (inCount === 0)
  8413. return false;
  8414. }
  8415. return true;
  8416. };
  8417. return BoundingBox;
  8418. })();
  8419. BABYLON.BoundingBox = BoundingBox;
  8420. })(BABYLON || (BABYLON = {}));
  8421. var BABYLON;
  8422. (function (BABYLON) {
  8423. var computeBoxExtents = function (axis, box) {
  8424. var p = BABYLON.Vector3.Dot(box.center, axis);
  8425. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8426. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8427. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8428. var r = r0 + r1 + r2;
  8429. return {
  8430. min: p - r,
  8431. max: p + r
  8432. };
  8433. };
  8434. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8435. var axisOverlap = function (axis, box0, box1) {
  8436. var result0 = computeBoxExtents(axis, box0);
  8437. var result1 = computeBoxExtents(axis, box1);
  8438. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8439. };
  8440. var BoundingInfo = (function () {
  8441. function BoundingInfo(minimum, maximum) {
  8442. this.minimum = minimum;
  8443. this.maximum = maximum;
  8444. this._isLocked = false;
  8445. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8446. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8447. }
  8448. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8449. get: function () {
  8450. return this._isLocked;
  8451. },
  8452. set: function (value) {
  8453. this._isLocked = value;
  8454. },
  8455. enumerable: true,
  8456. configurable: true
  8457. });
  8458. // Methods
  8459. BoundingInfo.prototype.update = function (world) {
  8460. if (this._isLocked) {
  8461. return;
  8462. }
  8463. this.boundingBox._update(world);
  8464. this.boundingSphere._update(world);
  8465. };
  8466. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8467. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8468. return false;
  8469. return this.boundingBox.isInFrustum(frustumPlanes);
  8470. };
  8471. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8472. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8473. };
  8474. BoundingInfo.prototype._checkCollision = function (collider) {
  8475. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8476. };
  8477. BoundingInfo.prototype.intersectsPoint = function (point) {
  8478. if (!this.boundingSphere.centerWorld) {
  8479. return false;
  8480. }
  8481. if (!this.boundingSphere.intersectsPoint(point)) {
  8482. return false;
  8483. }
  8484. if (!this.boundingBox.intersectsPoint(point)) {
  8485. return false;
  8486. }
  8487. return true;
  8488. };
  8489. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8490. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8491. return false;
  8492. }
  8493. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8494. return false;
  8495. }
  8496. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8497. return false;
  8498. }
  8499. if (!precise) {
  8500. return true;
  8501. }
  8502. var box0 = this.boundingBox;
  8503. var box1 = boundingInfo.boundingBox;
  8504. if (!axisOverlap(box0.directions[0], box0, box1))
  8505. return false;
  8506. if (!axisOverlap(box0.directions[1], box0, box1))
  8507. return false;
  8508. if (!axisOverlap(box0.directions[2], box0, box1))
  8509. return false;
  8510. if (!axisOverlap(box1.directions[0], box0, box1))
  8511. return false;
  8512. if (!axisOverlap(box1.directions[1], box0, box1))
  8513. return false;
  8514. if (!axisOverlap(box1.directions[2], box0, box1))
  8515. return false;
  8516. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8517. return false;
  8518. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8519. return false;
  8520. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8521. return false;
  8522. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8523. return false;
  8524. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8525. return false;
  8526. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8527. return false;
  8528. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8529. return false;
  8530. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8531. return false;
  8532. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8533. return false;
  8534. return true;
  8535. };
  8536. return BoundingInfo;
  8537. })();
  8538. BABYLON.BoundingInfo = BoundingInfo;
  8539. })(BABYLON || (BABYLON = {}));
  8540. var BABYLON;
  8541. (function (BABYLON) {
  8542. var Ray = (function () {
  8543. function Ray(origin, direction, length) {
  8544. if (length === void 0) { length = Number.MAX_VALUE; }
  8545. this.origin = origin;
  8546. this.direction = direction;
  8547. this.length = length;
  8548. }
  8549. // Methods
  8550. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8551. var d = 0.0;
  8552. var maxValue = Number.MAX_VALUE;
  8553. var inv;
  8554. var min;
  8555. var max;
  8556. var temp;
  8557. if (Math.abs(this.direction.x) < 0.0000001) {
  8558. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8559. return false;
  8560. }
  8561. }
  8562. else {
  8563. inv = 1.0 / this.direction.x;
  8564. min = (minimum.x - this.origin.x) * inv;
  8565. max = (maximum.x - this.origin.x) * inv;
  8566. if (max === -Infinity) {
  8567. max = Infinity;
  8568. }
  8569. if (min > max) {
  8570. temp = min;
  8571. min = max;
  8572. max = temp;
  8573. }
  8574. d = Math.max(min, d);
  8575. maxValue = Math.min(max, maxValue);
  8576. if (d > maxValue) {
  8577. return false;
  8578. }
  8579. }
  8580. if (Math.abs(this.direction.y) < 0.0000001) {
  8581. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8582. return false;
  8583. }
  8584. }
  8585. else {
  8586. inv = 1.0 / this.direction.y;
  8587. min = (minimum.y - this.origin.y) * inv;
  8588. max = (maximum.y - this.origin.y) * inv;
  8589. if (max === -Infinity) {
  8590. max = Infinity;
  8591. }
  8592. if (min > max) {
  8593. temp = min;
  8594. min = max;
  8595. max = temp;
  8596. }
  8597. d = Math.max(min, d);
  8598. maxValue = Math.min(max, maxValue);
  8599. if (d > maxValue) {
  8600. return false;
  8601. }
  8602. }
  8603. if (Math.abs(this.direction.z) < 0.0000001) {
  8604. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8605. return false;
  8606. }
  8607. }
  8608. else {
  8609. inv = 1.0 / this.direction.z;
  8610. min = (minimum.z - this.origin.z) * inv;
  8611. max = (maximum.z - this.origin.z) * inv;
  8612. if (max === -Infinity) {
  8613. max = Infinity;
  8614. }
  8615. if (min > max) {
  8616. temp = min;
  8617. min = max;
  8618. max = temp;
  8619. }
  8620. d = Math.max(min, d);
  8621. maxValue = Math.min(max, maxValue);
  8622. if (d > maxValue) {
  8623. return false;
  8624. }
  8625. }
  8626. return true;
  8627. };
  8628. Ray.prototype.intersectsBox = function (box) {
  8629. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8630. };
  8631. Ray.prototype.intersectsSphere = function (sphere) {
  8632. var x = sphere.center.x - this.origin.x;
  8633. var y = sphere.center.y - this.origin.y;
  8634. var z = sphere.center.z - this.origin.z;
  8635. var pyth = (x * x) + (y * y) + (z * z);
  8636. var rr = sphere.radius * sphere.radius;
  8637. if (pyth <= rr) {
  8638. return true;
  8639. }
  8640. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8641. if (dot < 0.0) {
  8642. return false;
  8643. }
  8644. var temp = pyth - (dot * dot);
  8645. return temp <= rr;
  8646. };
  8647. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8648. if (!this._edge1) {
  8649. this._edge1 = BABYLON.Vector3.Zero();
  8650. this._edge2 = BABYLON.Vector3.Zero();
  8651. this._pvec = BABYLON.Vector3.Zero();
  8652. this._tvec = BABYLON.Vector3.Zero();
  8653. this._qvec = BABYLON.Vector3.Zero();
  8654. }
  8655. vertex1.subtractToRef(vertex0, this._edge1);
  8656. vertex2.subtractToRef(vertex0, this._edge2);
  8657. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8658. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8659. if (det === 0) {
  8660. return null;
  8661. }
  8662. var invdet = 1 / det;
  8663. this.origin.subtractToRef(vertex0, this._tvec);
  8664. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8665. if (bu < 0 || bu > 1.0) {
  8666. return null;
  8667. }
  8668. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8669. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8670. if (bv < 0 || bu + bv > 1.0) {
  8671. return null;
  8672. }
  8673. //check if the distance is longer than the predefined length.
  8674. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8675. if (distance > this.length) {
  8676. return null;
  8677. }
  8678. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8679. };
  8680. Ray.prototype.intersectsPlane = function (plane) {
  8681. var distance;
  8682. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8683. if (Math.abs(result1) < 9.99999997475243E-07) {
  8684. return null;
  8685. }
  8686. else {
  8687. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8688. distance = (-plane.d - result2) / result1;
  8689. if (distance < 0.0) {
  8690. if (distance < -9.99999997475243E-07) {
  8691. return null;
  8692. }
  8693. else {
  8694. return 0;
  8695. }
  8696. }
  8697. return distance;
  8698. }
  8699. };
  8700. /**
  8701. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8702. * @param sega the first point of the segment to test the intersection against
  8703. * @param segb the second point of the segment to test the intersection against
  8704. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8705. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8706. */
  8707. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8708. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8709. var u = segb.subtract(sega);
  8710. var v = rsegb.subtract(this.origin);
  8711. var w = sega.subtract(this.origin);
  8712. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8713. var b = BABYLON.Vector3.Dot(u, v);
  8714. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8715. var d = BABYLON.Vector3.Dot(u, w);
  8716. var e = BABYLON.Vector3.Dot(v, w);
  8717. var D = a * c - b * b; // always >= 0
  8718. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8719. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8720. // compute the line parameters of the two closest points
  8721. if (D < Ray.smallnum) {
  8722. sN = 0.0; // force using point P0 on segment S1
  8723. sD = 1.0; // to prevent possible division by 0.0 later
  8724. tN = e;
  8725. tD = c;
  8726. }
  8727. else {
  8728. sN = (b * e - c * d);
  8729. tN = (a * e - b * d);
  8730. if (sN < 0.0) {
  8731. sN = 0.0;
  8732. tN = e;
  8733. tD = c;
  8734. }
  8735. else if (sN > sD) {
  8736. sN = sD;
  8737. tN = e + b;
  8738. tD = c;
  8739. }
  8740. }
  8741. if (tN < 0.0) {
  8742. tN = 0.0;
  8743. // recompute sc for this edge
  8744. if (-d < 0.0) {
  8745. sN = 0.0;
  8746. }
  8747. else if (-d > a)
  8748. sN = sD;
  8749. else {
  8750. sN = -d;
  8751. sD = a;
  8752. }
  8753. }
  8754. else if (tN > tD) {
  8755. tN = tD;
  8756. // recompute sc for this edge
  8757. if ((-d + b) < 0.0) {
  8758. sN = 0;
  8759. }
  8760. else if ((-d + b) > a) {
  8761. sN = sD;
  8762. }
  8763. else {
  8764. sN = (-d + b);
  8765. sD = a;
  8766. }
  8767. }
  8768. // finally do the division to get sc and tc
  8769. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8770. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8771. // get the difference of the two closest points
  8772. var qtc = v.multiplyByFloats(tc, tc, tc);
  8773. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8774. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8775. if (isIntersected) {
  8776. return qtc.length();
  8777. }
  8778. return -1;
  8779. };
  8780. // Statics
  8781. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8782. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8783. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8784. var direction = end.subtract(start);
  8785. direction.normalize();
  8786. return new Ray(start, direction);
  8787. };
  8788. /**
  8789. * 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
  8790. * transformed to the given world matrix.
  8791. * @param origin The origin point
  8792. * @param end The end point
  8793. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8794. */
  8795. Ray.CreateNewFromTo = function (origin, end, world) {
  8796. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8797. var direction = end.subtract(origin);
  8798. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8799. direction.normalize();
  8800. return Ray.Transform(new Ray(origin, direction, length), world);
  8801. };
  8802. Ray.Transform = function (ray, matrix) {
  8803. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8804. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8805. newDirection.normalize();
  8806. return new Ray(newOrigin, newDirection, ray.length);
  8807. };
  8808. Ray.smallnum = 0.00000001;
  8809. Ray.rayl = 10e8;
  8810. return Ray;
  8811. })();
  8812. BABYLON.Ray = Ray;
  8813. })(BABYLON || (BABYLON = {}));
  8814. var BABYLON;
  8815. (function (BABYLON) {
  8816. var AbstractMesh = (function (_super) {
  8817. __extends(AbstractMesh, _super);
  8818. // Constructor
  8819. function AbstractMesh(name, scene) {
  8820. var _this = this;
  8821. _super.call(this, name, scene);
  8822. // Events
  8823. /**
  8824. * An event triggered when the mesh is disposed.
  8825. * @type {BABYLON.Observable}
  8826. */
  8827. this.onDisposeObservable = new BABYLON.Observable();
  8828. /**
  8829. * An event triggered when this mesh collides with another one
  8830. * @type {BABYLON.Observable}
  8831. */
  8832. this.onCollideObservable = new BABYLON.Observable();
  8833. /**
  8834. * An event triggered when the collision's position changes
  8835. * @type {BABYLON.Observable}
  8836. */
  8837. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8838. /**
  8839. * An event triggered after the world matrix is updated
  8840. * @type {BABYLON.Observable}
  8841. */
  8842. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8843. // Properties
  8844. this.definedFacingForward = true; // orientation for POV movement & rotation
  8845. this.position = new BABYLON.Vector3(0, 0, 0);
  8846. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8847. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8848. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8849. this.visibility = 1.0;
  8850. this.alphaIndex = Number.MAX_VALUE;
  8851. this.infiniteDistance = false;
  8852. this.isVisible = true;
  8853. this.isPickable = true;
  8854. this.showBoundingBox = false;
  8855. this.showSubMeshesBoundingBox = false;
  8856. this.isBlocker = false;
  8857. this.renderingGroupId = 0;
  8858. this.receiveShadows = false;
  8859. this.renderOutline = false;
  8860. this.outlineColor = BABYLON.Color3.Red();
  8861. this.outlineWidth = 0.02;
  8862. this.renderOverlay = false;
  8863. this.overlayColor = BABYLON.Color3.Red();
  8864. this.overlayAlpha = 0.5;
  8865. this.hasVertexAlpha = false;
  8866. this.useVertexColors = true;
  8867. this.applyFog = true;
  8868. this.computeBonesUsingShaders = true;
  8869. this.scalingDeterminant = 1;
  8870. this.numBoneInfluencers = 4;
  8871. this.useOctreeForRenderingSelection = true;
  8872. this.useOctreeForPicking = true;
  8873. this.useOctreeForCollisions = true;
  8874. this.layerMask = 0x0FFFFFFF;
  8875. this.alwaysSelectAsActiveMesh = false;
  8876. // Collisions
  8877. this._checkCollisions = false;
  8878. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8879. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8880. this._collider = new BABYLON.Collider();
  8881. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8882. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8883. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8884. // Edges
  8885. this.edgesWidth = 1;
  8886. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8887. // Cache
  8888. this._localWorld = BABYLON.Matrix.Zero();
  8889. this._worldMatrix = BABYLON.Matrix.Zero();
  8890. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8891. this._absolutePosition = BABYLON.Vector3.Zero();
  8892. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8893. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8894. this._isDirty = false;
  8895. this._pivotMatrix = BABYLON.Matrix.Identity();
  8896. this._isDisposed = false;
  8897. this._renderId = 0;
  8898. this._intersectionsInProgress = new Array();
  8899. this._isWorldMatrixFrozen = false;
  8900. this._unIndexed = false;
  8901. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8902. if (collidedMesh === void 0) { collidedMesh = null; }
  8903. //TODO move this to the collision coordinator!
  8904. if (_this.getScene().workerCollisions)
  8905. newPosition.multiplyInPlace(_this._collider.radius);
  8906. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8907. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8908. _this.position.addInPlace(_this._diffPositionForCollisions);
  8909. }
  8910. if (collidedMesh) {
  8911. _this.onCollideObservable.notifyObservers(collidedMesh);
  8912. }
  8913. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8914. };
  8915. scene.addMesh(this);
  8916. }
  8917. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8918. get: function () {
  8919. return AbstractMesh._BILLBOARDMODE_NONE;
  8920. },
  8921. enumerable: true,
  8922. configurable: true
  8923. });
  8924. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8925. get: function () {
  8926. return AbstractMesh._BILLBOARDMODE_X;
  8927. },
  8928. enumerable: true,
  8929. configurable: true
  8930. });
  8931. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8932. get: function () {
  8933. return AbstractMesh._BILLBOARDMODE_Y;
  8934. },
  8935. enumerable: true,
  8936. configurable: true
  8937. });
  8938. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8939. get: function () {
  8940. return AbstractMesh._BILLBOARDMODE_Z;
  8941. },
  8942. enumerable: true,
  8943. configurable: true
  8944. });
  8945. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8946. get: function () {
  8947. return AbstractMesh._BILLBOARDMODE_ALL;
  8948. },
  8949. enumerable: true,
  8950. configurable: true
  8951. });
  8952. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  8953. set: function (callback) {
  8954. if (this._onDisposeObserver) {
  8955. this.onDisposeObservable.remove(this._onDisposeObserver);
  8956. }
  8957. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  8958. },
  8959. enumerable: true,
  8960. configurable: true
  8961. });
  8962. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8963. set: function (callback) {
  8964. if (this._onCollideObserver) {
  8965. this.onCollideObservable.remove(this._onCollideObserver);
  8966. }
  8967. this._onCollideObserver = this.onCollideObservable.add(callback);
  8968. },
  8969. enumerable: true,
  8970. configurable: true
  8971. });
  8972. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8973. set: function (callback) {
  8974. if (this._onCollisionPositionChangeObserver) {
  8975. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8976. }
  8977. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8978. },
  8979. enumerable: true,
  8980. configurable: true
  8981. });
  8982. Object.defineProperty(AbstractMesh.prototype, "actionManager", {
  8983. /**
  8984. * This scene's action manager
  8985. * @type {BABYLON.ActionManager}
  8986. */
  8987. get: function () {
  8988. if (!this._actionManager) {
  8989. this.actionManager = new BABYLON.ActionManager(this.getScene());
  8990. }
  8991. return this._actionManager;
  8992. },
  8993. /**
  8994. * This scene's action manager
  8995. * @type {BABYLON.ActionManager}
  8996. */
  8997. set: function (value) {
  8998. this._actionManager = value;
  8999. },
  9000. enumerable: true,
  9001. configurable: true
  9002. });
  9003. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9004. get: function () {
  9005. return this._skeleton;
  9006. },
  9007. set: function (value) {
  9008. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9009. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9010. }
  9011. if (value && value.needInitialSkinMatrix) {
  9012. value._registerMeshWithPoseMatrix(this);
  9013. }
  9014. this._skeleton = value;
  9015. if (!this._skeleton) {
  9016. this._bonesTransformMatrices = null;
  9017. }
  9018. },
  9019. enumerable: true,
  9020. configurable: true
  9021. });
  9022. /**
  9023. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9024. */
  9025. AbstractMesh.prototype.toString = function (fullDetails) {
  9026. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9027. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9028. if (this._skeleton) {
  9029. ret += ", skeleton: " + this._skeleton.name;
  9030. }
  9031. if (fullDetails) {
  9032. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9033. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9034. }
  9035. return ret;
  9036. };
  9037. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9038. /**
  9039. * Getting the rotation object.
  9040. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9041. */
  9042. get: function () {
  9043. return this._rotation;
  9044. },
  9045. set: function (newRotation) {
  9046. this._rotation = newRotation;
  9047. },
  9048. enumerable: true,
  9049. configurable: true
  9050. });
  9051. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9052. get: function () {
  9053. return this._scaling;
  9054. },
  9055. set: function (newScaling) {
  9056. this._scaling = newScaling;
  9057. if (this.physicsImpostor) {
  9058. this.physicsImpostor.forceUpdate();
  9059. }
  9060. },
  9061. enumerable: true,
  9062. configurable: true
  9063. });
  9064. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9065. get: function () {
  9066. return this._rotationQuaternion;
  9067. },
  9068. set: function (quaternion) {
  9069. this._rotationQuaternion = quaternion;
  9070. //reset the rotation vector.
  9071. if (quaternion && this.rotation.length()) {
  9072. this.rotation.copyFromFloats(0, 0, 0);
  9073. }
  9074. },
  9075. enumerable: true,
  9076. configurable: true
  9077. });
  9078. // Methods
  9079. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9080. this._poseMatrix.copyFrom(matrix);
  9081. };
  9082. AbstractMesh.prototype.getPoseMatrix = function () {
  9083. return this._poseMatrix;
  9084. };
  9085. AbstractMesh.prototype.disableEdgesRendering = function () {
  9086. if (this._edgesRenderer !== undefined) {
  9087. this._edgesRenderer.dispose();
  9088. this._edgesRenderer = undefined;
  9089. }
  9090. };
  9091. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9092. if (epsilon === void 0) { epsilon = 0.95; }
  9093. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9094. this.disableEdgesRendering();
  9095. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9096. };
  9097. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9098. get: function () {
  9099. return false;
  9100. },
  9101. enumerable: true,
  9102. configurable: true
  9103. });
  9104. AbstractMesh.prototype.getLOD = function (camera) {
  9105. return this;
  9106. };
  9107. AbstractMesh.prototype.getTotalVertices = function () {
  9108. return 0;
  9109. };
  9110. AbstractMesh.prototype.getIndices = function () {
  9111. return null;
  9112. };
  9113. AbstractMesh.prototype.getVerticesData = function (kind) {
  9114. return null;
  9115. };
  9116. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9117. return false;
  9118. };
  9119. AbstractMesh.prototype.getBoundingInfo = function () {
  9120. if (this._masterMesh) {
  9121. return this._masterMesh.getBoundingInfo();
  9122. }
  9123. if (!this._boundingInfo) {
  9124. this._updateBoundingInfo();
  9125. }
  9126. return this._boundingInfo;
  9127. };
  9128. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9129. get: function () {
  9130. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9131. },
  9132. enumerable: true,
  9133. configurable: true
  9134. });
  9135. AbstractMesh.prototype._preActivate = function () {
  9136. };
  9137. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9138. };
  9139. AbstractMesh.prototype._activate = function (renderId) {
  9140. this._renderId = renderId;
  9141. };
  9142. AbstractMesh.prototype.getWorldMatrix = function () {
  9143. if (this._masterMesh) {
  9144. return this._masterMesh.getWorldMatrix();
  9145. }
  9146. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9147. this.computeWorldMatrix();
  9148. }
  9149. return this._worldMatrix;
  9150. };
  9151. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9152. get: function () {
  9153. return this._worldMatrix;
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9159. get: function () {
  9160. return this._absolutePosition;
  9161. },
  9162. enumerable: true,
  9163. configurable: true
  9164. });
  9165. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9166. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9167. this.computeWorldMatrix(true);
  9168. this._isWorldMatrixFrozen = true;
  9169. };
  9170. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9171. this._isWorldMatrixFrozen = false;
  9172. this.computeWorldMatrix(true);
  9173. };
  9174. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9175. get: function () {
  9176. return this._isWorldMatrixFrozen;
  9177. },
  9178. enumerable: true,
  9179. configurable: true
  9180. });
  9181. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9182. axis.normalize();
  9183. if (!this.rotationQuaternion) {
  9184. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9185. this.rotation = BABYLON.Vector3.Zero();
  9186. }
  9187. var rotationQuaternion;
  9188. if (!space || space === BABYLON.Space.LOCAL) {
  9189. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9190. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9191. }
  9192. else {
  9193. if (this.parent) {
  9194. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9195. invertParentWorldMatrix.invert();
  9196. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9197. }
  9198. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9199. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9200. }
  9201. };
  9202. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9203. var displacementVector = axis.scale(distance);
  9204. if (!space || space === BABYLON.Space.LOCAL) {
  9205. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9206. this.setPositionWithLocalVector(tempV3);
  9207. }
  9208. else {
  9209. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9210. }
  9211. };
  9212. AbstractMesh.prototype.getAbsolutePosition = function () {
  9213. this.computeWorldMatrix();
  9214. return this._absolutePosition;
  9215. };
  9216. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9217. if (!absolutePosition) {
  9218. return;
  9219. }
  9220. var absolutePositionX;
  9221. var absolutePositionY;
  9222. var absolutePositionZ;
  9223. if (absolutePosition.x === undefined) {
  9224. if (arguments.length < 3) {
  9225. return;
  9226. }
  9227. absolutePositionX = arguments[0];
  9228. absolutePositionY = arguments[1];
  9229. absolutePositionZ = arguments[2];
  9230. }
  9231. else {
  9232. absolutePositionX = absolutePosition.x;
  9233. absolutePositionY = absolutePosition.y;
  9234. absolutePositionZ = absolutePosition.z;
  9235. }
  9236. if (this.parent) {
  9237. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9238. invertParentWorldMatrix.invert();
  9239. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9240. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9241. }
  9242. else {
  9243. this.position.x = absolutePositionX;
  9244. this.position.y = absolutePositionY;
  9245. this.position.z = absolutePositionZ;
  9246. }
  9247. };
  9248. // ================================== Point of View Movement =================================
  9249. /**
  9250. * Perform relative position change from the point of view of behind the front of the mesh.
  9251. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9252. * Supports definition of mesh facing forward or backward.
  9253. * @param {number} amountRight
  9254. * @param {number} amountUp
  9255. * @param {number} amountForward
  9256. */
  9257. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9258. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9259. };
  9260. /**
  9261. * Calculate relative position change from the point of view of behind the front of the mesh.
  9262. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9263. * Supports definition of mesh facing forward or backward.
  9264. * @param {number} amountRight
  9265. * @param {number} amountUp
  9266. * @param {number} amountForward
  9267. */
  9268. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9269. var rotMatrix = new BABYLON.Matrix();
  9270. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9271. rotQuaternion.toRotationMatrix(rotMatrix);
  9272. var translationDelta = BABYLON.Vector3.Zero();
  9273. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9274. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9275. return translationDelta;
  9276. };
  9277. // ================================== Point of View Rotation =================================
  9278. /**
  9279. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9280. * Supports definition of mesh facing forward or backward.
  9281. * @param {number} flipBack
  9282. * @param {number} twirlClockwise
  9283. * @param {number} tiltRight
  9284. */
  9285. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9286. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9287. };
  9288. /**
  9289. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9290. * Supports definition of mesh facing forward or backward.
  9291. * @param {number} flipBack
  9292. * @param {number} twirlClockwise
  9293. * @param {number} tiltRight
  9294. */
  9295. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9296. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9297. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9298. };
  9299. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9300. this._pivotMatrix = matrix;
  9301. this._cache.pivotMatrixUpdated = true;
  9302. };
  9303. AbstractMesh.prototype.getPivotMatrix = function () {
  9304. return this._pivotMatrix;
  9305. };
  9306. AbstractMesh.prototype._isSynchronized = function () {
  9307. if (this._isDirty) {
  9308. return false;
  9309. }
  9310. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9311. return false;
  9312. if (this._cache.pivotMatrixUpdated) {
  9313. return false;
  9314. }
  9315. if (this.infiniteDistance) {
  9316. return false;
  9317. }
  9318. if (!this._cache.position.equals(this.position))
  9319. return false;
  9320. if (this.rotationQuaternion) {
  9321. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9322. return false;
  9323. }
  9324. else {
  9325. if (!this._cache.rotation.equals(this.rotation))
  9326. return false;
  9327. }
  9328. if (!this._cache.scaling.equals(this.scaling))
  9329. return false;
  9330. return true;
  9331. };
  9332. AbstractMesh.prototype._initCache = function () {
  9333. _super.prototype._initCache.call(this);
  9334. this._cache.localMatrixUpdated = false;
  9335. this._cache.position = BABYLON.Vector3.Zero();
  9336. this._cache.scaling = BABYLON.Vector3.Zero();
  9337. this._cache.rotation = BABYLON.Vector3.Zero();
  9338. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9339. this._cache.billboardMode = -1;
  9340. };
  9341. AbstractMesh.prototype.markAsDirty = function (property) {
  9342. if (property === "rotation") {
  9343. this.rotationQuaternion = null;
  9344. }
  9345. this._currentRenderId = Number.MAX_VALUE;
  9346. this._isDirty = true;
  9347. };
  9348. AbstractMesh.prototype._updateBoundingInfo = function () {
  9349. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9350. this._boundingInfo.update(this.worldMatrixFromCache);
  9351. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9352. };
  9353. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9354. if (!this.subMeshes) {
  9355. return;
  9356. }
  9357. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9358. var subMesh = this.subMeshes[subIndex];
  9359. if (!subMesh.IsGlobal) {
  9360. subMesh.updateBoundingInfo(matrix);
  9361. }
  9362. }
  9363. };
  9364. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9365. if (this._isWorldMatrixFrozen) {
  9366. return this._worldMatrix;
  9367. }
  9368. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9369. this._currentRenderId = this.getScene().getRenderId();
  9370. return this._worldMatrix;
  9371. }
  9372. this._cache.position.copyFrom(this.position);
  9373. this._cache.scaling.copyFrom(this.scaling);
  9374. this._cache.pivotMatrixUpdated = false;
  9375. this._cache.billboardMode = this.billboardMode;
  9376. this._currentRenderId = this.getScene().getRenderId();
  9377. this._isDirty = false;
  9378. // Scaling
  9379. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9380. // Rotation
  9381. //rotate, if quaternion is set and rotation was used
  9382. if (this.rotationQuaternion) {
  9383. var len = this.rotation.length();
  9384. if (len) {
  9385. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9386. this.rotation.copyFromFloats(0, 0, 0);
  9387. }
  9388. }
  9389. if (this.rotationQuaternion) {
  9390. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9391. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9392. }
  9393. else {
  9394. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9395. this._cache.rotation.copyFrom(this.rotation);
  9396. }
  9397. // Translation
  9398. if (this.infiniteDistance && !this.parent) {
  9399. var camera = this.getScene().activeCamera;
  9400. if (camera) {
  9401. var cameraWorldMatrix = camera.getWorldMatrix();
  9402. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9403. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9404. }
  9405. }
  9406. else {
  9407. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9408. }
  9409. // Composing transformations
  9410. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9411. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9412. // Billboarding
  9413. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9414. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9415. var localPosition = BABYLON.Tmp.Vector3[0];
  9416. if (this.parent && this.parent.getWorldMatrix) {
  9417. this._markSyncedWithParent();
  9418. var parentMatrix;
  9419. if (this._meshToBoneReferal) {
  9420. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9421. parentMatrix = BABYLON.Tmp.Matrix[6];
  9422. }
  9423. else {
  9424. parentMatrix = this.parent.getWorldMatrix();
  9425. }
  9426. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9427. localPosition = BABYLON.Tmp.Vector3[1];
  9428. }
  9429. var zero = this.getScene().activeCamera.globalPosition.clone();
  9430. if (this.parent && this.parent.position) {
  9431. localPosition.addInPlace(this.parent.position);
  9432. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9433. }
  9434. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9435. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9436. zero.x = localPosition.x + BABYLON.Epsilon;
  9437. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9438. zero.y = localPosition.y + BABYLON.Epsilon;
  9439. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9440. zero.z = localPosition.z + BABYLON.Epsilon;
  9441. }
  9442. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9443. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9444. BABYLON.Tmp.Matrix[3].invert();
  9445. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9446. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9447. }
  9448. // Local world
  9449. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9450. // Parent
  9451. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9452. this._markSyncedWithParent();
  9453. if (this._meshToBoneReferal) {
  9454. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9455. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9456. }
  9457. else {
  9458. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9459. }
  9460. }
  9461. else {
  9462. this._worldMatrix.copyFrom(this._localWorld);
  9463. }
  9464. // Bounding info
  9465. this._updateBoundingInfo();
  9466. // Absolute position
  9467. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9468. // Callbacks
  9469. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9470. if (!this._poseMatrix) {
  9471. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9472. }
  9473. return this._worldMatrix;
  9474. };
  9475. /**
  9476. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9477. * @param func: callback function to add
  9478. */
  9479. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9480. this.onAfterWorldMatrixUpdateObservable.add(func);
  9481. };
  9482. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9483. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9484. };
  9485. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9486. this.computeWorldMatrix();
  9487. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9488. };
  9489. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9490. this.computeWorldMatrix();
  9491. var invLocalWorldMatrix = this._localWorld.clone();
  9492. invLocalWorldMatrix.invert();
  9493. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9494. };
  9495. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9496. this.computeWorldMatrix(true);
  9497. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9498. };
  9499. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9500. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9501. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9502. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9503. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9504. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9505. /// <returns>Mesh oriented towards targetMesh</returns>
  9506. yawCor = yawCor || 0; // default to zero if undefined
  9507. pitchCor = pitchCor || 0;
  9508. rollCor = rollCor || 0;
  9509. var dv = targetPoint.subtract(this.position);
  9510. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9511. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9512. var pitch = Math.atan2(dv.y, len);
  9513. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9514. };
  9515. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9516. this._meshToBoneReferal = affectedMesh;
  9517. this.parent = bone;
  9518. if (bone.getWorldMatrix().determinant() < 0) {
  9519. this.scalingDeterminant *= -1;
  9520. }
  9521. };
  9522. AbstractMesh.prototype.detachFromBone = function () {
  9523. if (this.parent.getWorldMatrix().determinant() < 0) {
  9524. this.scalingDeterminant *= -1;
  9525. }
  9526. this._meshToBoneReferal = null;
  9527. this.parent = null;
  9528. };
  9529. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9530. return this._boundingInfo.isInFrustum(frustumPlanes);
  9531. };
  9532. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9533. if (!camera) {
  9534. camera = this.getScene().activeCamera;
  9535. }
  9536. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9537. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9538. return false;
  9539. }
  9540. return true;
  9541. };
  9542. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9543. if (!this._boundingInfo || !mesh._boundingInfo) {
  9544. return false;
  9545. }
  9546. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9547. };
  9548. AbstractMesh.prototype.intersectsPoint = function (point) {
  9549. if (!this._boundingInfo) {
  9550. return false;
  9551. }
  9552. return this._boundingInfo.intersectsPoint(point);
  9553. };
  9554. // Physics
  9555. /**
  9556. * @Deprecated. Use new PhysicsImpostor instead.
  9557. * */
  9558. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9559. //legacy support
  9560. if (impostor.impostor) {
  9561. options = impostor;
  9562. impostor = impostor.impostor;
  9563. }
  9564. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9565. return this.physicsImpostor.physicsBody;
  9566. };
  9567. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9568. return this.physicsImpostor;
  9569. };
  9570. /**
  9571. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9572. */
  9573. AbstractMesh.prototype.getPhysicsMass = function () {
  9574. return this.physicsImpostor.getParam("mass");
  9575. };
  9576. /**
  9577. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9578. */
  9579. AbstractMesh.prototype.getPhysicsFriction = function () {
  9580. return this.physicsImpostor.getParam("friction");
  9581. };
  9582. /**
  9583. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9584. */
  9585. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9586. return this.physicsImpostor.getParam("resitution");
  9587. };
  9588. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9589. if (!camera) {
  9590. camera = this.getScene().activeCamera;
  9591. }
  9592. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9593. };
  9594. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9595. if (!camera) {
  9596. camera = this.getScene().activeCamera;
  9597. }
  9598. return this.absolutePosition.subtract(camera.position).length();
  9599. };
  9600. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9601. if (!this.physicsImpostor) {
  9602. return;
  9603. }
  9604. this.physicsImpostor.applyImpulse(force, contactPoint);
  9605. };
  9606. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9607. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9608. return;
  9609. }
  9610. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9611. mainPivot: pivot1,
  9612. connectedPivot: pivot2,
  9613. nativeParams: options
  9614. });
  9615. };
  9616. /**
  9617. * @Deprecated
  9618. */
  9619. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9620. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9621. this.updatePhysicsBody();
  9622. };
  9623. /**
  9624. * @Deprecated
  9625. * Calling this function is not needed anymore.
  9626. * The physics engine takes care of transofmration automatically.
  9627. */
  9628. AbstractMesh.prototype.updatePhysicsBody = function () {
  9629. //Unneeded
  9630. };
  9631. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9632. // Collisions
  9633. get: function () {
  9634. return this._checkCollisions;
  9635. },
  9636. set: function (collisionEnabled) {
  9637. this._checkCollisions = collisionEnabled;
  9638. if (this.getScene().workerCollisions) {
  9639. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9640. }
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9646. var globalPosition = this.getAbsolutePosition();
  9647. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9648. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9649. this._collider.radius = this.ellipsoid;
  9650. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9651. };
  9652. // Submeshes octree
  9653. /**
  9654. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9655. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9656. */
  9657. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9658. if (maxCapacity === void 0) { maxCapacity = 64; }
  9659. if (maxDepth === void 0) { maxDepth = 2; }
  9660. if (!this._submeshesOctree) {
  9661. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9662. }
  9663. this.computeWorldMatrix(true);
  9664. // Update octree
  9665. var bbox = this.getBoundingInfo().boundingBox;
  9666. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9667. return this._submeshesOctree;
  9668. };
  9669. // Collisions
  9670. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9671. this._generatePointsArray();
  9672. // Transformation
  9673. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9674. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9675. subMesh._lastColliderWorldVertices = [];
  9676. subMesh._trianglePlanes = [];
  9677. var start = subMesh.verticesStart;
  9678. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9679. for (var i = start; i < end; i++) {
  9680. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9681. }
  9682. }
  9683. // Collide
  9684. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9685. if (collider.collisionFound) {
  9686. collider.collidedMesh = this;
  9687. }
  9688. };
  9689. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9690. var subMeshes;
  9691. var len;
  9692. // Octrees
  9693. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9694. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9695. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9696. len = intersections.length;
  9697. subMeshes = intersections.data;
  9698. }
  9699. else {
  9700. subMeshes = this.subMeshes;
  9701. len = subMeshes.length;
  9702. }
  9703. for (var index = 0; index < len; index++) {
  9704. var subMesh = subMeshes[index];
  9705. // Bounding test
  9706. if (len > 1 && !subMesh._checkCollision(collider))
  9707. continue;
  9708. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9709. }
  9710. };
  9711. AbstractMesh.prototype._checkCollision = function (collider) {
  9712. // Bounding box test
  9713. if (!this._boundingInfo._checkCollision(collider))
  9714. return;
  9715. // Transformation matrix
  9716. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9717. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9718. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9719. };
  9720. // Picking
  9721. AbstractMesh.prototype._generatePointsArray = function () {
  9722. return false;
  9723. };
  9724. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9725. var pickingInfo = new BABYLON.PickingInfo();
  9726. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9727. return pickingInfo;
  9728. }
  9729. if (!this._generatePointsArray()) {
  9730. return pickingInfo;
  9731. }
  9732. var intersectInfo = null;
  9733. // Octrees
  9734. var subMeshes;
  9735. var len;
  9736. if (this._submeshesOctree && this.useOctreeForPicking) {
  9737. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9738. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9739. len = intersections.length;
  9740. subMeshes = intersections.data;
  9741. }
  9742. else {
  9743. subMeshes = this.subMeshes;
  9744. len = subMeshes.length;
  9745. }
  9746. for (var index = 0; index < len; index++) {
  9747. var subMesh = subMeshes[index];
  9748. // Bounding test
  9749. if (len > 1 && !subMesh.canIntersects(ray))
  9750. continue;
  9751. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9752. if (currentIntersectInfo) {
  9753. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9754. intersectInfo = currentIntersectInfo;
  9755. intersectInfo.subMeshId = index;
  9756. if (fastCheck) {
  9757. break;
  9758. }
  9759. }
  9760. }
  9761. }
  9762. if (intersectInfo) {
  9763. // Get picked point
  9764. var world = this.getWorldMatrix();
  9765. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9766. var direction = ray.direction.clone();
  9767. direction = direction.scale(intersectInfo.distance);
  9768. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9769. var pickedPoint = worldOrigin.add(worldDirection);
  9770. // Return result
  9771. pickingInfo.hit = true;
  9772. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9773. pickingInfo.pickedPoint = pickedPoint;
  9774. pickingInfo.pickedMesh = this;
  9775. pickingInfo.bu = intersectInfo.bu;
  9776. pickingInfo.bv = intersectInfo.bv;
  9777. pickingInfo.faceId = intersectInfo.faceId;
  9778. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9779. return pickingInfo;
  9780. }
  9781. return pickingInfo;
  9782. };
  9783. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9784. return null;
  9785. };
  9786. AbstractMesh.prototype.releaseSubMeshes = function () {
  9787. if (this.subMeshes) {
  9788. while (this.subMeshes.length) {
  9789. this.subMeshes[0].dispose();
  9790. }
  9791. }
  9792. else {
  9793. this.subMeshes = new Array();
  9794. }
  9795. };
  9796. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9797. var _this = this;
  9798. var index;
  9799. // Action manager
  9800. if (this.actionManager) {
  9801. this.actionManager.dispose();
  9802. this.actionManager = null;
  9803. }
  9804. // Skeleton
  9805. this.skeleton = null;
  9806. // Animations
  9807. this.getScene().stopAnimation(this);
  9808. // Physics
  9809. if (this.physicsImpostor) {
  9810. this.physicsImpostor.dispose();
  9811. }
  9812. // Intersections in progress
  9813. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9814. var other = this._intersectionsInProgress[index];
  9815. var pos = other._intersectionsInProgress.indexOf(this);
  9816. other._intersectionsInProgress.splice(pos, 1);
  9817. }
  9818. this._intersectionsInProgress = [];
  9819. // Lights
  9820. var lights = this.getScene().lights;
  9821. lights.forEach(function (light) {
  9822. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9823. if (meshIndex !== -1) {
  9824. light.includedOnlyMeshes.splice(meshIndex, 1);
  9825. }
  9826. meshIndex = light.excludedMeshes.indexOf(_this);
  9827. if (meshIndex !== -1) {
  9828. light.excludedMeshes.splice(meshIndex, 1);
  9829. }
  9830. });
  9831. // Edges
  9832. if (this._edgesRenderer) {
  9833. this._edgesRenderer.dispose();
  9834. this._edgesRenderer = null;
  9835. }
  9836. // SubMeshes
  9837. this.releaseSubMeshes();
  9838. // Remove from scene
  9839. this.getScene().removeMesh(this);
  9840. if (!doNotRecurse) {
  9841. // Particles
  9842. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9843. if (this.getScene().particleSystems[index].emitter === this) {
  9844. this.getScene().particleSystems[index].dispose();
  9845. index--;
  9846. }
  9847. }
  9848. // Children
  9849. var objects = this.getDescendants(true);
  9850. for (index = 0; index < objects.length; index++) {
  9851. objects[index].dispose();
  9852. }
  9853. }
  9854. else {
  9855. var childMeshes = this.getChildMeshes(true);
  9856. for (index = 0; index < childMeshes.length; index++) {
  9857. var child = childMeshes[index];
  9858. child.parent = null;
  9859. child.computeWorldMatrix(true);
  9860. }
  9861. }
  9862. _super.prototype.dispose.call(this);
  9863. this.onAfterWorldMatrixUpdateObservable.clear();
  9864. this.onCollideObservable.clear();
  9865. this.onCollisionPositionChangeObservable.clear();
  9866. this._isDisposed = true;
  9867. // Callback
  9868. this.onDisposeObservable.notifyObservers(this);
  9869. this.onDisposeObservable.clear();
  9870. };
  9871. // Statics
  9872. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9873. AbstractMesh._BILLBOARDMODE_X = 1;
  9874. AbstractMesh._BILLBOARDMODE_Y = 2;
  9875. AbstractMesh._BILLBOARDMODE_Z = 4;
  9876. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9877. return AbstractMesh;
  9878. })(BABYLON.Node);
  9879. BABYLON.AbstractMesh = AbstractMesh;
  9880. })(BABYLON || (BABYLON = {}));
  9881. var BABYLON;
  9882. (function (BABYLON) {
  9883. var Light = (function (_super) {
  9884. __extends(Light, _super);
  9885. function Light(name, scene) {
  9886. _super.call(this, name, scene);
  9887. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9888. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9889. this.intensity = 1.0;
  9890. this.range = Number.MAX_VALUE;
  9891. this.includeOnlyWithLayerMask = 0;
  9892. this.includedOnlyMeshes = new Array();
  9893. this.excludedMeshes = new Array();
  9894. this.excludeWithLayerMask = 0;
  9895. // PBR Properties.
  9896. this.radius = 0.00001;
  9897. this._excludedMeshesIds = new Array();
  9898. this._includedOnlyMeshesIds = new Array();
  9899. scene.addLight(this);
  9900. }
  9901. /**
  9902. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9903. */
  9904. Light.prototype.toString = function (fullDetails) {
  9905. var ret = "Name: " + this.name;
  9906. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9907. if (this.animations) {
  9908. for (var i = 0; i < this.animations.length; i++) {
  9909. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9910. }
  9911. }
  9912. if (fullDetails) {
  9913. }
  9914. return ret;
  9915. };
  9916. Light.prototype.getShadowGenerator = function () {
  9917. return this._shadowGenerator;
  9918. };
  9919. Light.prototype.getAbsolutePosition = function () {
  9920. return BABYLON.Vector3.Zero();
  9921. };
  9922. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9923. };
  9924. Light.prototype._getWorldMatrix = function () {
  9925. return BABYLON.Matrix.Identity();
  9926. };
  9927. Light.prototype.canAffectMesh = function (mesh) {
  9928. if (!mesh) {
  9929. return true;
  9930. }
  9931. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9932. return false;
  9933. }
  9934. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9935. return false;
  9936. }
  9937. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9938. return false;
  9939. }
  9940. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9941. return false;
  9942. }
  9943. return true;
  9944. };
  9945. Light.prototype.getWorldMatrix = function () {
  9946. this._currentRenderId = this.getScene().getRenderId();
  9947. var worldMatrix = this._getWorldMatrix();
  9948. if (this.parent && this.parent.getWorldMatrix) {
  9949. if (!this._parentedWorldMatrix) {
  9950. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9951. }
  9952. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9953. this._markSyncedWithParent();
  9954. return this._parentedWorldMatrix;
  9955. }
  9956. return worldMatrix;
  9957. };
  9958. Light.prototype.dispose = function () {
  9959. if (this._shadowGenerator) {
  9960. this._shadowGenerator.dispose();
  9961. this._shadowGenerator = null;
  9962. }
  9963. // Animations
  9964. this.getScene().stopAnimation(this);
  9965. // Remove from scene
  9966. this.getScene().removeLight(this);
  9967. _super.prototype.dispose.call(this);
  9968. };
  9969. Light.prototype.getTypeID = function () {
  9970. return 0;
  9971. };
  9972. Light.prototype.clone = function (name) {
  9973. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9974. };
  9975. Light.prototype.serialize = function () {
  9976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9977. // Type
  9978. serializationObject.type = this.getTypeID();
  9979. // Parent
  9980. if (this.parent) {
  9981. serializationObject.parentId = this.parent.id;
  9982. }
  9983. // Inclusion / exclusions
  9984. if (this.excludedMeshes.length > 0) {
  9985. serializationObject.excludedMeshesIds = [];
  9986. this.excludedMeshes.forEach(function (mesh) {
  9987. serializationObject.excludedMeshesIds.push(mesh.id);
  9988. });
  9989. }
  9990. if (this.includedOnlyMeshes.length > 0) {
  9991. serializationObject.includedOnlyMeshesIds = [];
  9992. this.includedOnlyMeshes.forEach(function (mesh) {
  9993. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9994. });
  9995. }
  9996. // Animations
  9997. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9998. serializationObject.ranges = this.serializeAnimationRanges();
  9999. return serializationObject;
  10000. };
  10001. Light.GetConstructorFromName = function (type, name, scene) {
  10002. switch (type) {
  10003. case 0:
  10004. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10005. case 1:
  10006. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10007. case 2:
  10008. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10009. case 3:
  10010. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10011. }
  10012. };
  10013. Light.Parse = function (parsedLight, scene) {
  10014. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10015. // Inclusion / exclusions
  10016. if (parsedLight.excludedMeshesIds) {
  10017. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10018. }
  10019. if (parsedLight.includedOnlyMeshesIds) {
  10020. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10021. }
  10022. // Parent
  10023. if (parsedLight.parentId) {
  10024. light._waitingParentId = parsedLight.parentId;
  10025. }
  10026. // Animations
  10027. if (parsedLight.animations) {
  10028. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10029. var parsedAnimation = parsedLight.animations[animationIndex];
  10030. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10031. }
  10032. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10033. }
  10034. if (parsedLight.autoAnimate) {
  10035. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10036. }
  10037. return light;
  10038. };
  10039. __decorate([
  10040. BABYLON.serializeAsColor3()
  10041. ], Light.prototype, "diffuse", void 0);
  10042. __decorate([
  10043. BABYLON.serializeAsColor3()
  10044. ], Light.prototype, "specular", void 0);
  10045. __decorate([
  10046. BABYLON.serialize()
  10047. ], Light.prototype, "intensity", void 0);
  10048. __decorate([
  10049. BABYLON.serialize()
  10050. ], Light.prototype, "range", void 0);
  10051. __decorate([
  10052. BABYLON.serialize()
  10053. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10054. __decorate([
  10055. BABYLON.serialize()
  10056. ], Light.prototype, "excludeWithLayerMask", void 0);
  10057. __decorate([
  10058. BABYLON.serialize()
  10059. ], Light.prototype, "radius", void 0);
  10060. return Light;
  10061. })(BABYLON.Node);
  10062. BABYLON.Light = Light;
  10063. })(BABYLON || (BABYLON = {}));
  10064. var BABYLON;
  10065. (function (BABYLON) {
  10066. var PointLight = (function (_super) {
  10067. __extends(PointLight, _super);
  10068. function PointLight(name, position, scene) {
  10069. _super.call(this, name, scene);
  10070. this.position = position;
  10071. }
  10072. PointLight.prototype.getAbsolutePosition = function () {
  10073. return this.transformedPosition ? this.transformedPosition : this.position;
  10074. };
  10075. PointLight.prototype.computeTransformedPosition = function () {
  10076. if (this.parent && this.parent.getWorldMatrix) {
  10077. if (!this.transformedPosition) {
  10078. this.transformedPosition = BABYLON.Vector3.Zero();
  10079. }
  10080. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10081. return true;
  10082. }
  10083. return false;
  10084. };
  10085. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10086. if (this.parent && this.parent.getWorldMatrix) {
  10087. this.computeTransformedPosition();
  10088. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10089. return;
  10090. }
  10091. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10092. };
  10093. PointLight.prototype.needCube = function () {
  10094. return true;
  10095. };
  10096. PointLight.prototype.supportsVSM = function () {
  10097. return false;
  10098. };
  10099. PointLight.prototype.needRefreshPerFrame = function () {
  10100. return false;
  10101. };
  10102. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10103. switch (faceIndex) {
  10104. case 0:
  10105. return new BABYLON.Vector3(1, 0, 0);
  10106. case 1:
  10107. return new BABYLON.Vector3(-1, 0, 0);
  10108. case 2:
  10109. return new BABYLON.Vector3(0, -1, 0);
  10110. case 3:
  10111. return new BABYLON.Vector3(0, 1, 0);
  10112. case 4:
  10113. return new BABYLON.Vector3(0, 0, 1);
  10114. case 5:
  10115. return new BABYLON.Vector3(0, 0, -1);
  10116. }
  10117. return BABYLON.Vector3.Zero();
  10118. };
  10119. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10120. var activeCamera = this.getScene().activeCamera;
  10121. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10122. };
  10123. PointLight.prototype._getWorldMatrix = function () {
  10124. if (!this._worldMatrix) {
  10125. this._worldMatrix = BABYLON.Matrix.Identity();
  10126. }
  10127. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10128. return this._worldMatrix;
  10129. };
  10130. PointLight.prototype.getTypeID = function () {
  10131. return 0;
  10132. };
  10133. __decorate([
  10134. BABYLON.serializeAsVector3()
  10135. ], PointLight.prototype, "position", void 0);
  10136. return PointLight;
  10137. })(BABYLON.Light);
  10138. BABYLON.PointLight = PointLight;
  10139. })(BABYLON || (BABYLON = {}));
  10140. var BABYLON;
  10141. (function (BABYLON) {
  10142. var SpotLight = (function (_super) {
  10143. __extends(SpotLight, _super);
  10144. function SpotLight(name, position, direction, angle, exponent, scene) {
  10145. _super.call(this, name, scene);
  10146. this.position = position;
  10147. this.direction = direction;
  10148. this.angle = angle;
  10149. this.exponent = exponent;
  10150. }
  10151. SpotLight.prototype.getAbsolutePosition = function () {
  10152. return this.transformedPosition ? this.transformedPosition : this.position;
  10153. };
  10154. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10155. var activeCamera = this.getScene().activeCamera;
  10156. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10157. };
  10158. SpotLight.prototype.needCube = function () {
  10159. return false;
  10160. };
  10161. SpotLight.prototype.supportsVSM = function () {
  10162. return true;
  10163. };
  10164. SpotLight.prototype.needRefreshPerFrame = function () {
  10165. return false;
  10166. };
  10167. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10168. return this.direction;
  10169. };
  10170. SpotLight.prototype.setDirectionToTarget = function (target) {
  10171. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10172. return this.direction;
  10173. };
  10174. SpotLight.prototype.computeTransformedPosition = function () {
  10175. if (this.parent && this.parent.getWorldMatrix) {
  10176. if (!this.transformedPosition) {
  10177. this.transformedPosition = BABYLON.Vector3.Zero();
  10178. }
  10179. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10180. return true;
  10181. }
  10182. return false;
  10183. };
  10184. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10185. var normalizeDirection;
  10186. if (this.parent && this.parent.getWorldMatrix) {
  10187. if (!this._transformedDirection) {
  10188. this._transformedDirection = BABYLON.Vector3.Zero();
  10189. }
  10190. this.computeTransformedPosition();
  10191. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10192. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10193. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10194. }
  10195. else {
  10196. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10197. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10198. }
  10199. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10200. };
  10201. SpotLight.prototype._getWorldMatrix = function () {
  10202. if (!this._worldMatrix) {
  10203. this._worldMatrix = BABYLON.Matrix.Identity();
  10204. }
  10205. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10206. return this._worldMatrix;
  10207. };
  10208. SpotLight.prototype.getTypeID = function () {
  10209. return 2;
  10210. };
  10211. __decorate([
  10212. BABYLON.serializeAsVector3()
  10213. ], SpotLight.prototype, "position", void 0);
  10214. __decorate([
  10215. BABYLON.serializeAsVector3()
  10216. ], SpotLight.prototype, "direction", void 0);
  10217. __decorate([
  10218. BABYLON.serialize()
  10219. ], SpotLight.prototype, "angle", void 0);
  10220. __decorate([
  10221. BABYLON.serialize()
  10222. ], SpotLight.prototype, "exponent", void 0);
  10223. return SpotLight;
  10224. })(BABYLON.Light);
  10225. BABYLON.SpotLight = SpotLight;
  10226. })(BABYLON || (BABYLON = {}));
  10227. var BABYLON;
  10228. (function (BABYLON) {
  10229. var HemisphericLight = (function (_super) {
  10230. __extends(HemisphericLight, _super);
  10231. function HemisphericLight(name, direction, scene) {
  10232. _super.call(this, name, scene);
  10233. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10234. this.direction = direction;
  10235. }
  10236. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10237. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10238. return this.direction;
  10239. };
  10240. HemisphericLight.prototype.getShadowGenerator = function () {
  10241. return null;
  10242. };
  10243. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10244. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10245. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10246. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10247. };
  10248. HemisphericLight.prototype._getWorldMatrix = function () {
  10249. if (!this._worldMatrix) {
  10250. this._worldMatrix = BABYLON.Matrix.Identity();
  10251. }
  10252. return this._worldMatrix;
  10253. };
  10254. HemisphericLight.prototype.getTypeID = function () {
  10255. return 3;
  10256. };
  10257. __decorate([
  10258. BABYLON.serializeAsColor3()
  10259. ], HemisphericLight.prototype, "groundColor", void 0);
  10260. __decorate([
  10261. BABYLON.serializeAsVector3()
  10262. ], HemisphericLight.prototype, "direction", void 0);
  10263. return HemisphericLight;
  10264. })(BABYLON.Light);
  10265. BABYLON.HemisphericLight = HemisphericLight;
  10266. })(BABYLON || (BABYLON = {}));
  10267. var BABYLON;
  10268. (function (BABYLON) {
  10269. var DirectionalLight = (function (_super) {
  10270. __extends(DirectionalLight, _super);
  10271. function DirectionalLight(name, direction, scene) {
  10272. _super.call(this, name, scene);
  10273. this.shadowOrthoScale = 0.5;
  10274. this.autoUpdateExtends = true;
  10275. // Cache
  10276. this._orthoLeft = Number.MAX_VALUE;
  10277. this._orthoRight = Number.MIN_VALUE;
  10278. this._orthoTop = Number.MIN_VALUE;
  10279. this._orthoBottom = Number.MAX_VALUE;
  10280. this.position = direction.scale(-1);
  10281. this.direction = direction;
  10282. }
  10283. DirectionalLight.prototype.getAbsolutePosition = function () {
  10284. return this.transformedPosition ? this.transformedPosition : this.position;
  10285. };
  10286. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10287. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10288. return this.direction;
  10289. };
  10290. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10291. var activeCamera = this.getScene().activeCamera;
  10292. // Check extends
  10293. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10294. var tempVector3 = BABYLON.Vector3.Zero();
  10295. this._orthoLeft = Number.MAX_VALUE;
  10296. this._orthoRight = Number.MIN_VALUE;
  10297. this._orthoTop = Number.MIN_VALUE;
  10298. this._orthoBottom = Number.MAX_VALUE;
  10299. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10300. var mesh = renderList[meshIndex];
  10301. if (!mesh) {
  10302. continue;
  10303. }
  10304. var boundingInfo = mesh.getBoundingInfo();
  10305. if (!boundingInfo) {
  10306. continue;
  10307. }
  10308. var boundingBox = boundingInfo.boundingBox;
  10309. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10310. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10311. if (tempVector3.x < this._orthoLeft)
  10312. this._orthoLeft = tempVector3.x;
  10313. if (tempVector3.y < this._orthoBottom)
  10314. this._orthoBottom = tempVector3.y;
  10315. if (tempVector3.x > this._orthoRight)
  10316. this._orthoRight = tempVector3.x;
  10317. if (tempVector3.y > this._orthoTop)
  10318. this._orthoTop = tempVector3.y;
  10319. }
  10320. }
  10321. }
  10322. var xOffset = this._orthoRight - this._orthoLeft;
  10323. var yOffset = this._orthoTop - this._orthoBottom;
  10324. 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);
  10325. };
  10326. DirectionalLight.prototype.supportsVSM = function () {
  10327. return true;
  10328. };
  10329. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10330. return true;
  10331. };
  10332. DirectionalLight.prototype.needCube = function () {
  10333. return false;
  10334. };
  10335. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10336. return this.direction;
  10337. };
  10338. DirectionalLight.prototype.computeTransformedPosition = function () {
  10339. if (this.parent && this.parent.getWorldMatrix) {
  10340. if (!this.transformedPosition) {
  10341. this.transformedPosition = BABYLON.Vector3.Zero();
  10342. }
  10343. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10344. return true;
  10345. }
  10346. return false;
  10347. };
  10348. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10349. if (this.parent && this.parent.getWorldMatrix) {
  10350. if (!this._transformedDirection) {
  10351. this._transformedDirection = BABYLON.Vector3.Zero();
  10352. }
  10353. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10354. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10355. return;
  10356. }
  10357. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10358. };
  10359. DirectionalLight.prototype._getWorldMatrix = function () {
  10360. if (!this._worldMatrix) {
  10361. this._worldMatrix = BABYLON.Matrix.Identity();
  10362. }
  10363. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10364. return this._worldMatrix;
  10365. };
  10366. DirectionalLight.prototype.getTypeID = function () {
  10367. return 1;
  10368. };
  10369. __decorate([
  10370. BABYLON.serializeAsVector3()
  10371. ], DirectionalLight.prototype, "position", void 0);
  10372. __decorate([
  10373. BABYLON.serializeAsVector3()
  10374. ], DirectionalLight.prototype, "direction", void 0);
  10375. __decorate([
  10376. BABYLON.serialize()
  10377. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10378. __decorate([
  10379. BABYLON.serialize()
  10380. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10381. return DirectionalLight;
  10382. })(BABYLON.Light);
  10383. BABYLON.DirectionalLight = DirectionalLight;
  10384. })(BABYLON || (BABYLON = {}));
  10385. var BABYLON;
  10386. (function (BABYLON) {
  10387. var ShadowGenerator = (function () {
  10388. function ShadowGenerator(mapSize, light) {
  10389. var _this = this;
  10390. // Members
  10391. this._filter = ShadowGenerator.FILTER_NONE;
  10392. this.blurScale = 2;
  10393. this._blurBoxOffset = 0;
  10394. this._bias = 0.00005;
  10395. this._lightDirection = BABYLON.Vector3.Zero();
  10396. this.forceBackFacesOnly = false;
  10397. this._darkness = 0;
  10398. this._transparencyShadow = false;
  10399. this._viewMatrix = BABYLON.Matrix.Zero();
  10400. this._projectionMatrix = BABYLON.Matrix.Zero();
  10401. this._transformMatrix = BABYLON.Matrix.Zero();
  10402. this._worldViewProjection = BABYLON.Matrix.Zero();
  10403. this._currentFaceIndex = 0;
  10404. this._currentFaceIndexCache = 0;
  10405. this._light = light;
  10406. this._scene = light.getScene();
  10407. this._mapSize = mapSize;
  10408. light._shadowGenerator = this;
  10409. // Render target
  10410. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  10411. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10412. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10413. this._shadowMap.anisotropicFilteringLevel = 1;
  10414. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10415. this._shadowMap.renderParticles = false;
  10416. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10417. _this._currentFaceIndex = faceIndex;
  10418. });
  10419. this._shadowMap.onAfterUnbindObservable.add(function () {
  10420. if (!_this.useBlurVarianceShadowMap) {
  10421. return;
  10422. }
  10423. if (!_this._shadowMap2) {
  10424. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  10425. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10426. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10427. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10428. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10429. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10430. effect.setTexture("textureSampler", _this._shadowMap);
  10431. });
  10432. _this.blurBoxOffset = 1;
  10433. }
  10434. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10435. });
  10436. // Custom render function
  10437. var renderSubMesh = function (subMesh) {
  10438. var mesh = subMesh.getRenderingMesh();
  10439. var scene = _this._scene;
  10440. var engine = scene.getEngine();
  10441. // Culling
  10442. engine.setState(subMesh.getMaterial().backFaceCulling);
  10443. // Managing instances
  10444. var batch = mesh._getInstancesRenderList(subMesh._id);
  10445. if (batch.mustReturn) {
  10446. return;
  10447. }
  10448. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10449. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10450. engine.enableEffect(_this._effect);
  10451. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10452. var material = subMesh.getMaterial();
  10453. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10454. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10455. if (_this.getLight().needCube()) {
  10456. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10457. }
  10458. // Alpha test
  10459. if (material && material.needAlphaTesting()) {
  10460. var alphaTexture = material.getAlphaTestTexture();
  10461. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10462. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10463. }
  10464. // Bones
  10465. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10466. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10467. }
  10468. if (_this.forceBackFacesOnly) {
  10469. engine.setState(true, 0, false, true);
  10470. }
  10471. // Draw
  10472. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10473. if (_this.forceBackFacesOnly) {
  10474. engine.setState(true, 0, false, false);
  10475. }
  10476. }
  10477. else {
  10478. // Need to reset refresh rate of the shadowMap
  10479. _this._shadowMap.resetRefreshCounter();
  10480. }
  10481. };
  10482. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10483. var index;
  10484. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10485. renderSubMesh(opaqueSubMeshes.data[index]);
  10486. }
  10487. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10488. renderSubMesh(alphaTestSubMeshes.data[index]);
  10489. }
  10490. if (_this._transparencyShadow) {
  10491. for (index = 0; index < transparentSubMeshes.length; index++) {
  10492. renderSubMesh(transparentSubMeshes.data[index]);
  10493. }
  10494. }
  10495. };
  10496. this._shadowMap.onClearObservable.add(function (engine) {
  10497. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10498. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10499. }
  10500. else {
  10501. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10502. }
  10503. });
  10504. }
  10505. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10506. // Static
  10507. get: function () {
  10508. return ShadowGenerator._FILTER_NONE;
  10509. },
  10510. enumerable: true,
  10511. configurable: true
  10512. });
  10513. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10514. get: function () {
  10515. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10516. },
  10517. enumerable: true,
  10518. configurable: true
  10519. });
  10520. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10521. get: function () {
  10522. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10523. },
  10524. enumerable: true,
  10525. configurable: true
  10526. });
  10527. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10528. get: function () {
  10529. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10530. },
  10531. enumerable: true,
  10532. configurable: true
  10533. });
  10534. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10535. get: function () {
  10536. return this._bias;
  10537. },
  10538. set: function (bias) {
  10539. this._bias = bias;
  10540. },
  10541. enumerable: true,
  10542. configurable: true
  10543. });
  10544. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10545. get: function () {
  10546. return this._blurBoxOffset;
  10547. },
  10548. set: function (value) {
  10549. var _this = this;
  10550. if (this._blurBoxOffset === value) {
  10551. return;
  10552. }
  10553. this._blurBoxOffset = value;
  10554. if (this._boxBlurPostprocess) {
  10555. this._boxBlurPostprocess.dispose();
  10556. }
  10557. 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);
  10558. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  10559. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10560. });
  10561. },
  10562. enumerable: true,
  10563. configurable: true
  10564. });
  10565. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10566. get: function () {
  10567. return this._filter;
  10568. },
  10569. set: function (value) {
  10570. if (this._filter === value) {
  10571. return;
  10572. }
  10573. this._filter = value;
  10574. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10575. this._shadowMap.anisotropicFilteringLevel = 16;
  10576. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10577. }
  10578. else {
  10579. this._shadowMap.anisotropicFilteringLevel = 1;
  10580. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10581. }
  10582. },
  10583. enumerable: true,
  10584. configurable: true
  10585. });
  10586. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10587. get: function () {
  10588. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10589. },
  10590. set: function (value) {
  10591. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10592. },
  10593. enumerable: true,
  10594. configurable: true
  10595. });
  10596. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10597. get: function () {
  10598. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10599. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10600. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10601. },
  10602. set: function (value) {
  10603. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10604. },
  10605. enumerable: true,
  10606. configurable: true
  10607. });
  10608. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10609. get: function () {
  10610. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10611. },
  10612. set: function (value) {
  10613. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10614. },
  10615. enumerable: true,
  10616. configurable: true
  10617. });
  10618. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10619. var defines = [];
  10620. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10621. defines.push("#define VSM");
  10622. }
  10623. if (this.getLight().needCube()) {
  10624. defines.push("#define CUBEMAP");
  10625. }
  10626. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10627. var mesh = subMesh.getMesh();
  10628. var material = subMesh.getMaterial();
  10629. // Alpha test
  10630. if (material && material.needAlphaTesting()) {
  10631. defines.push("#define ALPHATEST");
  10632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10633. attribs.push(BABYLON.VertexBuffer.UVKind);
  10634. defines.push("#define UV1");
  10635. }
  10636. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10637. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10638. defines.push("#define UV2");
  10639. }
  10640. }
  10641. // Bones
  10642. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10643. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10644. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10645. if (mesh.numBoneInfluencers > 4) {
  10646. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10647. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10648. }
  10649. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10650. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10651. }
  10652. else {
  10653. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10654. }
  10655. // Instances
  10656. if (useInstances) {
  10657. defines.push("#define INSTANCES");
  10658. attribs.push("world0");
  10659. attribs.push("world1");
  10660. attribs.push("world2");
  10661. attribs.push("world3");
  10662. }
  10663. // Get correct effect
  10664. var join = defines.join("\n");
  10665. if (this._cachedDefines !== join) {
  10666. this._cachedDefines = join;
  10667. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10668. }
  10669. return this._effect.isReady();
  10670. };
  10671. ShadowGenerator.prototype.getShadowMap = function () {
  10672. return this._shadowMap;
  10673. };
  10674. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10675. if (this._shadowMap2) {
  10676. return this._shadowMap2;
  10677. }
  10678. return this._shadowMap;
  10679. };
  10680. ShadowGenerator.prototype.getLight = function () {
  10681. return this._light;
  10682. };
  10683. // Methods
  10684. ShadowGenerator.prototype.getTransformMatrix = function () {
  10685. var scene = this._scene;
  10686. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10687. return this._transformMatrix;
  10688. }
  10689. this._currentRenderID = scene.getRenderId();
  10690. this._currentFaceIndexCache = this._currentFaceIndex;
  10691. var lightPosition = this._light.position;
  10692. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10693. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10694. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10695. }
  10696. if (this._light.computeTransformedPosition()) {
  10697. lightPosition = this._light.transformedPosition;
  10698. }
  10699. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10700. this._cachedPosition = lightPosition.clone();
  10701. this._cachedDirection = this._lightDirection.clone();
  10702. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10703. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10704. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10705. }
  10706. return this._transformMatrix;
  10707. };
  10708. ShadowGenerator.prototype.getDarkness = function () {
  10709. return this._darkness;
  10710. };
  10711. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10712. if (darkness >= 1.0)
  10713. this._darkness = 1.0;
  10714. else if (darkness <= 0.0)
  10715. this._darkness = 0.0;
  10716. else
  10717. this._darkness = darkness;
  10718. };
  10719. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10720. this._transparencyShadow = hasShadow;
  10721. };
  10722. ShadowGenerator.prototype._packHalf = function (depth) {
  10723. var scale = depth * 255.0;
  10724. var fract = scale - Math.floor(scale);
  10725. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10726. };
  10727. ShadowGenerator.prototype.dispose = function () {
  10728. this._shadowMap.dispose();
  10729. if (this._shadowMap2) {
  10730. this._shadowMap2.dispose();
  10731. }
  10732. if (this._downSamplePostprocess) {
  10733. this._downSamplePostprocess.dispose();
  10734. }
  10735. if (this._boxBlurPostprocess) {
  10736. this._boxBlurPostprocess.dispose();
  10737. }
  10738. };
  10739. ShadowGenerator.prototype.serialize = function () {
  10740. var serializationObject = {};
  10741. serializationObject.lightId = this._light.id;
  10742. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10743. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10744. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10745. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10746. serializationObject.renderList = [];
  10747. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10748. var mesh = this.getShadowMap().renderList[meshIndex];
  10749. serializationObject.renderList.push(mesh.id);
  10750. }
  10751. return serializationObject;
  10752. };
  10753. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10754. //casting to point light, as light is missing the position attr and typescript complains.
  10755. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10756. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10757. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10758. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  10759. meshes.forEach(function (mesh) {
  10760. shadowGenerator.getShadowMap().renderList.push(mesh);
  10761. });
  10762. }
  10763. if (parsedShadowGenerator.usePoissonSampling) {
  10764. shadowGenerator.usePoissonSampling = true;
  10765. }
  10766. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10767. shadowGenerator.useVarianceShadowMap = true;
  10768. }
  10769. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10770. shadowGenerator.useBlurVarianceShadowMap = true;
  10771. if (parsedShadowGenerator.blurScale) {
  10772. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10773. }
  10774. if (parsedShadowGenerator.blurBoxOffset) {
  10775. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10776. }
  10777. }
  10778. if (parsedShadowGenerator.bias !== undefined) {
  10779. shadowGenerator.bias = parsedShadowGenerator.bias;
  10780. }
  10781. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10782. return shadowGenerator;
  10783. };
  10784. ShadowGenerator._FILTER_NONE = 0;
  10785. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10786. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10787. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10788. return ShadowGenerator;
  10789. })();
  10790. BABYLON.ShadowGenerator = ShadowGenerator;
  10791. })(BABYLON || (BABYLON = {}));
  10792. var BABYLON;
  10793. (function (BABYLON) {
  10794. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10795. if (boxMin.x > sphereCenter.x + sphereRadius)
  10796. return false;
  10797. if (sphereCenter.x - sphereRadius > boxMax.x)
  10798. return false;
  10799. if (boxMin.y > sphereCenter.y + sphereRadius)
  10800. return false;
  10801. if (sphereCenter.y - sphereRadius > boxMax.y)
  10802. return false;
  10803. if (boxMin.z > sphereCenter.z + sphereRadius)
  10804. return false;
  10805. if (sphereCenter.z - sphereRadius > boxMax.z)
  10806. return false;
  10807. return true;
  10808. };
  10809. var getLowestRoot = function (a, b, c, maxR) {
  10810. var determinant = b * b - 4.0 * a * c;
  10811. var result = { root: 0, found: false };
  10812. if (determinant < 0)
  10813. return result;
  10814. var sqrtD = Math.sqrt(determinant);
  10815. var r1 = (-b - sqrtD) / (2.0 * a);
  10816. var r2 = (-b + sqrtD) / (2.0 * a);
  10817. if (r1 > r2) {
  10818. var temp = r2;
  10819. r2 = r1;
  10820. r1 = temp;
  10821. }
  10822. if (r1 > 0 && r1 < maxR) {
  10823. result.root = r1;
  10824. result.found = true;
  10825. return result;
  10826. }
  10827. if (r2 > 0 && r2 < maxR) {
  10828. result.root = r2;
  10829. result.found = true;
  10830. return result;
  10831. }
  10832. return result;
  10833. };
  10834. var Collider = (function () {
  10835. function Collider() {
  10836. this.radius = new BABYLON.Vector3(1, 1, 1);
  10837. this.retry = 0;
  10838. this.basePointWorld = BABYLON.Vector3.Zero();
  10839. this.velocityWorld = BABYLON.Vector3.Zero();
  10840. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10841. this._collisionPoint = BABYLON.Vector3.Zero();
  10842. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10843. this._tempVector = BABYLON.Vector3.Zero();
  10844. this._tempVector2 = BABYLON.Vector3.Zero();
  10845. this._tempVector3 = BABYLON.Vector3.Zero();
  10846. this._tempVector4 = BABYLON.Vector3.Zero();
  10847. this._edge = BABYLON.Vector3.Zero();
  10848. this._baseToVertex = BABYLON.Vector3.Zero();
  10849. this._destinationPoint = BABYLON.Vector3.Zero();
  10850. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10851. this._displacementVector = BABYLON.Vector3.Zero();
  10852. }
  10853. // Methods
  10854. Collider.prototype._initialize = function (source, dir, e) {
  10855. this.velocity = dir;
  10856. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10857. this.basePoint = source;
  10858. source.multiplyToRef(this.radius, this.basePointWorld);
  10859. dir.multiplyToRef(this.radius, this.velocityWorld);
  10860. this.velocityWorldLength = this.velocityWorld.length();
  10861. this.epsilon = e;
  10862. this.collisionFound = false;
  10863. };
  10864. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10865. pa.subtractToRef(point, this._tempVector);
  10866. pb.subtractToRef(point, this._tempVector2);
  10867. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10868. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10869. if (d < 0)
  10870. return false;
  10871. pc.subtractToRef(point, this._tempVector3);
  10872. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10873. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10874. if (d < 0)
  10875. return false;
  10876. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10877. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10878. return d >= 0;
  10879. };
  10880. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10881. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10882. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10883. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10884. return false;
  10885. }
  10886. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10887. return false;
  10888. return true;
  10889. };
  10890. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10891. var t0;
  10892. var embeddedInPlane = false;
  10893. //defensive programming, actually not needed.
  10894. if (!trianglePlaneArray) {
  10895. trianglePlaneArray = [];
  10896. }
  10897. if (!trianglePlaneArray[faceIndex]) {
  10898. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10899. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10900. }
  10901. var trianglePlane = trianglePlaneArray[faceIndex];
  10902. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10903. return;
  10904. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10905. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10906. if (normalDotVelocity == 0) {
  10907. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10908. return;
  10909. embeddedInPlane = true;
  10910. t0 = 0;
  10911. }
  10912. else {
  10913. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10914. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10915. if (t0 > t1) {
  10916. var temp = t1;
  10917. t1 = t0;
  10918. t0 = temp;
  10919. }
  10920. if (t0 > 1.0 || t1 < 0.0)
  10921. return;
  10922. if (t0 < 0)
  10923. t0 = 0;
  10924. if (t0 > 1.0)
  10925. t0 = 1.0;
  10926. }
  10927. this._collisionPoint.copyFromFloats(0, 0, 0);
  10928. var found = false;
  10929. var t = 1.0;
  10930. if (!embeddedInPlane) {
  10931. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10932. this.velocity.scaleToRef(t0, this._tempVector);
  10933. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10934. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10935. found = true;
  10936. t = t0;
  10937. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10938. }
  10939. }
  10940. if (!found) {
  10941. var velocitySquaredLength = this.velocity.lengthSquared();
  10942. var a = velocitySquaredLength;
  10943. this.basePoint.subtractToRef(p1, this._tempVector);
  10944. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10945. var c = this._tempVector.lengthSquared() - 1.0;
  10946. var lowestRoot = getLowestRoot(a, b, c, t);
  10947. if (lowestRoot.found) {
  10948. t = lowestRoot.root;
  10949. found = true;
  10950. this._collisionPoint.copyFrom(p1);
  10951. }
  10952. this.basePoint.subtractToRef(p2, this._tempVector);
  10953. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10954. c = this._tempVector.lengthSquared() - 1.0;
  10955. lowestRoot = getLowestRoot(a, b, c, t);
  10956. if (lowestRoot.found) {
  10957. t = lowestRoot.root;
  10958. found = true;
  10959. this._collisionPoint.copyFrom(p2);
  10960. }
  10961. this.basePoint.subtractToRef(p3, this._tempVector);
  10962. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10963. c = this._tempVector.lengthSquared() - 1.0;
  10964. lowestRoot = getLowestRoot(a, b, c, t);
  10965. if (lowestRoot.found) {
  10966. t = lowestRoot.root;
  10967. found = true;
  10968. this._collisionPoint.copyFrom(p3);
  10969. }
  10970. p2.subtractToRef(p1, this._edge);
  10971. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10972. var edgeSquaredLength = this._edge.lengthSquared();
  10973. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10974. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10975. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10976. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10977. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10978. lowestRoot = getLowestRoot(a, b, c, t);
  10979. if (lowestRoot.found) {
  10980. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10981. if (f >= 0.0 && f <= 1.0) {
  10982. t = lowestRoot.root;
  10983. found = true;
  10984. this._edge.scaleInPlace(f);
  10985. p1.addToRef(this._edge, this._collisionPoint);
  10986. }
  10987. }
  10988. p3.subtractToRef(p2, this._edge);
  10989. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10990. edgeSquaredLength = this._edge.lengthSquared();
  10991. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10992. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10993. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10994. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10995. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10996. lowestRoot = getLowestRoot(a, b, c, t);
  10997. if (lowestRoot.found) {
  10998. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10999. if (f >= 0.0 && f <= 1.0) {
  11000. t = lowestRoot.root;
  11001. found = true;
  11002. this._edge.scaleInPlace(f);
  11003. p2.addToRef(this._edge, this._collisionPoint);
  11004. }
  11005. }
  11006. p1.subtractToRef(p3, this._edge);
  11007. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11008. edgeSquaredLength = this._edge.lengthSquared();
  11009. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11010. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11011. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11012. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11013. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11014. lowestRoot = getLowestRoot(a, b, c, t);
  11015. if (lowestRoot.found) {
  11016. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11017. if (f >= 0.0 && f <= 1.0) {
  11018. t = lowestRoot.root;
  11019. found = true;
  11020. this._edge.scaleInPlace(f);
  11021. p3.addToRef(this._edge, this._collisionPoint);
  11022. }
  11023. }
  11024. }
  11025. if (found) {
  11026. var distToCollision = t * this.velocity.length();
  11027. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11028. if (!this.intersectionPoint) {
  11029. this.intersectionPoint = this._collisionPoint.clone();
  11030. }
  11031. else {
  11032. this.intersectionPoint.copyFrom(this._collisionPoint);
  11033. }
  11034. this.nearestDistance = distToCollision;
  11035. this.collisionFound = true;
  11036. }
  11037. }
  11038. };
  11039. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11040. for (var i = indexStart; i < indexEnd; i += 3) {
  11041. var p1 = pts[indices[i] - decal];
  11042. var p2 = pts[indices[i + 1] - decal];
  11043. var p3 = pts[indices[i + 2] - decal];
  11044. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11045. }
  11046. };
  11047. Collider.prototype._getResponse = function (pos, vel) {
  11048. pos.addToRef(vel, this._destinationPoint);
  11049. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11050. this.basePoint.addToRef(vel, pos);
  11051. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11052. this._slidePlaneNormal.normalize();
  11053. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11054. pos.addInPlace(this._displacementVector);
  11055. this.intersectionPoint.addInPlace(this._displacementVector);
  11056. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11057. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11058. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11059. };
  11060. return Collider;
  11061. })();
  11062. BABYLON.Collider = Collider;
  11063. })(BABYLON || (BABYLON = {}));
  11064. var BABYLON;
  11065. (function (BABYLON) {
  11066. //WebWorker code will be inserted to this variable.
  11067. BABYLON.CollisionWorker = "";
  11068. (function (WorkerTaskType) {
  11069. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11070. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11071. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11072. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11073. var WorkerTaskType = BABYLON.WorkerTaskType;
  11074. (function (WorkerReplyType) {
  11075. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11076. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11077. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11078. var WorkerReplyType = BABYLON.WorkerReplyType;
  11079. var CollisionCoordinatorWorker = (function () {
  11080. function CollisionCoordinatorWorker() {
  11081. var _this = this;
  11082. this._scaledPosition = BABYLON.Vector3.Zero();
  11083. this._scaledVelocity = BABYLON.Vector3.Zero();
  11084. this.onMeshUpdated = function (mesh) {
  11085. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11086. };
  11087. this.onGeometryUpdated = function (geometry) {
  11088. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11089. };
  11090. this._afterRender = function () {
  11091. if (!_this._init)
  11092. return;
  11093. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11094. return;
  11095. }
  11096. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11097. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11098. if (_this._runningUpdated > 4) {
  11099. return;
  11100. }
  11101. ++_this._runningUpdated;
  11102. var payload = {
  11103. updatedMeshes: _this._addUpdateMeshesList,
  11104. updatedGeometries: _this._addUpdateGeometriesList,
  11105. removedGeometries: _this._toRemoveGeometryArray,
  11106. removedMeshes: _this._toRemoveMeshesArray
  11107. };
  11108. var message = {
  11109. payload: payload,
  11110. taskType: WorkerTaskType.UPDATE
  11111. };
  11112. var serializable = [];
  11113. for (var id in payload.updatedGeometries) {
  11114. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11115. //prepare transferables
  11116. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11117. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11118. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11119. }
  11120. }
  11121. _this._worker.postMessage(message, serializable);
  11122. _this._addUpdateMeshesList = {};
  11123. _this._addUpdateGeometriesList = {};
  11124. _this._toRemoveGeometryArray = [];
  11125. _this._toRemoveMeshesArray = [];
  11126. };
  11127. this._onMessageFromWorker = function (e) {
  11128. var returnData = e.data;
  11129. if (returnData.error != WorkerReplyType.SUCCESS) {
  11130. //TODO what errors can be returned from the worker?
  11131. BABYLON.Tools.Warn("error returned from worker!");
  11132. return;
  11133. }
  11134. switch (returnData.taskType) {
  11135. case WorkerTaskType.INIT:
  11136. _this._init = true;
  11137. //Update the worked with ALL of the scene's current state
  11138. _this._scene.meshes.forEach(function (mesh) {
  11139. _this.onMeshAdded(mesh);
  11140. });
  11141. _this._scene.getGeometries().forEach(function (geometry) {
  11142. _this.onGeometryAdded(geometry);
  11143. });
  11144. break;
  11145. case WorkerTaskType.UPDATE:
  11146. _this._runningUpdated--;
  11147. break;
  11148. case WorkerTaskType.COLLIDE:
  11149. _this._runningCollisionTask = false;
  11150. var returnPayload = returnData.payload;
  11151. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11152. return;
  11153. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11154. //cleanup
  11155. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11156. break;
  11157. }
  11158. };
  11159. this._collisionsCallbackArray = [];
  11160. this._init = false;
  11161. this._runningUpdated = 0;
  11162. this._runningCollisionTask = false;
  11163. this._addUpdateMeshesList = {};
  11164. this._addUpdateGeometriesList = {};
  11165. this._toRemoveGeometryArray = [];
  11166. this._toRemoveMeshesArray = [];
  11167. }
  11168. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11169. if (!this._init)
  11170. return;
  11171. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11172. return;
  11173. position.divideToRef(collider.radius, this._scaledPosition);
  11174. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11175. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11176. var payload = {
  11177. collider: {
  11178. position: this._scaledPosition.asArray(),
  11179. velocity: this._scaledVelocity.asArray(),
  11180. radius: collider.radius.asArray()
  11181. },
  11182. collisionId: collisionIndex,
  11183. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11184. maximumRetry: maximumRetry
  11185. };
  11186. var message = {
  11187. payload: payload,
  11188. taskType: WorkerTaskType.COLLIDE
  11189. };
  11190. this._worker.postMessage(message);
  11191. };
  11192. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11193. this._scene = scene;
  11194. this._scene.registerAfterRender(this._afterRender);
  11195. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11196. this._worker = new Worker(workerUrl);
  11197. this._worker.onmessage = this._onMessageFromWorker;
  11198. var message = {
  11199. payload: {},
  11200. taskType: WorkerTaskType.INIT
  11201. };
  11202. this._worker.postMessage(message);
  11203. };
  11204. CollisionCoordinatorWorker.prototype.destroy = function () {
  11205. this._scene.unregisterAfterRender(this._afterRender);
  11206. this._worker.terminate();
  11207. };
  11208. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11209. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11210. this.onMeshUpdated(mesh);
  11211. };
  11212. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11213. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11214. };
  11215. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11216. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11217. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11218. this.onGeometryUpdated(geometry);
  11219. };
  11220. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11221. this._toRemoveGeometryArray.push(geometry.id);
  11222. };
  11223. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11224. var submeshes = [];
  11225. if (mesh.subMeshes) {
  11226. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11227. return {
  11228. position: idx,
  11229. verticesStart: sm.verticesStart,
  11230. verticesCount: sm.verticesCount,
  11231. indexStart: sm.indexStart,
  11232. indexCount: sm.indexCount,
  11233. hasMaterial: !!sm.getMaterial(),
  11234. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11235. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11236. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11237. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11238. };
  11239. });
  11240. }
  11241. var geometryId = null;
  11242. if (mesh instanceof BABYLON.Mesh) {
  11243. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11244. }
  11245. else if (mesh instanceof BABYLON.InstancedMesh) {
  11246. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11247. }
  11248. return {
  11249. uniqueId: mesh.uniqueId,
  11250. id: mesh.id,
  11251. name: mesh.name,
  11252. geometryId: geometryId,
  11253. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11254. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11255. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11256. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11257. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11258. subMeshes: submeshes,
  11259. checkCollisions: mesh.checkCollisions
  11260. };
  11261. };
  11262. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11263. return {
  11264. id: geometry.id,
  11265. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11266. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11267. indices: new Int32Array(geometry.getIndices() || []),
  11268. };
  11269. };
  11270. return CollisionCoordinatorWorker;
  11271. })();
  11272. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11273. var CollisionCoordinatorLegacy = (function () {
  11274. function CollisionCoordinatorLegacy() {
  11275. this._scaledPosition = BABYLON.Vector3.Zero();
  11276. this._scaledVelocity = BABYLON.Vector3.Zero();
  11277. this._finalPosition = BABYLON.Vector3.Zero();
  11278. }
  11279. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11280. position.divideToRef(collider.radius, this._scaledPosition);
  11281. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11282. collider.collidedMesh = null;
  11283. collider.retry = 0;
  11284. collider.initialVelocity = this._scaledVelocity;
  11285. collider.initialPosition = this._scaledPosition;
  11286. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11287. this._finalPosition.multiplyInPlace(collider.radius);
  11288. //run the callback
  11289. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11290. };
  11291. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11292. this._scene = scene;
  11293. };
  11294. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11295. //Legacy need no destruction method.
  11296. };
  11297. //No update in legacy mode
  11298. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11299. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11300. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11301. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11302. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11303. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11304. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11305. if (excludedMesh === void 0) { excludedMesh = null; }
  11306. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11307. if (collider.retry >= maximumRetry) {
  11308. finalPosition.copyFrom(position);
  11309. return;
  11310. }
  11311. collider._initialize(position, velocity, closeDistance);
  11312. // Check all meshes
  11313. for (var index = 0; index < this._scene.meshes.length; index++) {
  11314. var mesh = this._scene.meshes[index];
  11315. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11316. mesh._checkCollision(collider);
  11317. }
  11318. }
  11319. if (!collider.collisionFound) {
  11320. position.addToRef(velocity, finalPosition);
  11321. return;
  11322. }
  11323. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11324. collider._getResponse(position, velocity);
  11325. }
  11326. if (velocity.length() <= closeDistance) {
  11327. finalPosition.copyFrom(position);
  11328. return;
  11329. }
  11330. collider.retry++;
  11331. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11332. };
  11333. return CollisionCoordinatorLegacy;
  11334. })();
  11335. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11336. })(BABYLON || (BABYLON = {}));
  11337. var BABYLON;
  11338. (function (BABYLON) {
  11339. var Camera = (function (_super) {
  11340. __extends(Camera, _super);
  11341. function Camera(name, position, scene) {
  11342. _super.call(this, name, scene);
  11343. this.upVector = BABYLON.Vector3.Up();
  11344. this.orthoLeft = null;
  11345. this.orthoRight = null;
  11346. this.orthoBottom = null;
  11347. this.orthoTop = null;
  11348. this.fov = 0.8;
  11349. this.minZ = 1.0;
  11350. this.maxZ = 10000.0;
  11351. this.inertia = 0.9;
  11352. this.mode = Camera.PERSPECTIVE_CAMERA;
  11353. this.isIntermediate = false;
  11354. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11355. this.layerMask = 0x0FFFFFFF;
  11356. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11357. // Camera rig members
  11358. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11359. this._rigCameras = new Array();
  11360. // Cache
  11361. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11362. this._projectionMatrix = new BABYLON.Matrix();
  11363. this._postProcesses = new Array();
  11364. this._activeMeshes = new BABYLON.SmartArray(256);
  11365. this._globalPosition = BABYLON.Vector3.Zero();
  11366. scene.addCamera(this);
  11367. if (!scene.activeCamera) {
  11368. scene.activeCamera = this;
  11369. }
  11370. this.position = position;
  11371. }
  11372. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11373. get: function () {
  11374. return Camera._PERSPECTIVE_CAMERA;
  11375. },
  11376. enumerable: true,
  11377. configurable: true
  11378. });
  11379. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11380. get: function () {
  11381. return Camera._ORTHOGRAPHIC_CAMERA;
  11382. },
  11383. enumerable: true,
  11384. configurable: true
  11385. });
  11386. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11387. get: function () {
  11388. return Camera._FOVMODE_VERTICAL_FIXED;
  11389. },
  11390. enumerable: true,
  11391. configurable: true
  11392. });
  11393. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11394. get: function () {
  11395. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11396. },
  11397. enumerable: true,
  11398. configurable: true
  11399. });
  11400. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11401. get: function () {
  11402. return Camera._RIG_MODE_NONE;
  11403. },
  11404. enumerable: true,
  11405. configurable: true
  11406. });
  11407. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11408. get: function () {
  11409. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11410. },
  11411. enumerable: true,
  11412. configurable: true
  11413. });
  11414. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11415. get: function () {
  11416. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11417. },
  11418. enumerable: true,
  11419. configurable: true
  11420. });
  11421. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11422. get: function () {
  11423. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11424. },
  11425. enumerable: true,
  11426. configurable: true
  11427. });
  11428. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11429. get: function () {
  11430. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11431. },
  11432. enumerable: true,
  11433. configurable: true
  11434. });
  11435. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11436. get: function () {
  11437. return Camera._RIG_MODE_VR;
  11438. },
  11439. enumerable: true,
  11440. configurable: true
  11441. });
  11442. /**
  11443. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11444. */
  11445. Camera.prototype.toString = function (fullDetails) {
  11446. var ret = "Name: " + this.name;
  11447. ret += ", type: " + this.getTypeName();
  11448. if (this.animations) {
  11449. for (var i = 0; i < this.animations.length; i++) {
  11450. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11451. }
  11452. }
  11453. if (fullDetails) {
  11454. }
  11455. return ret;
  11456. };
  11457. Object.defineProperty(Camera.prototype, "globalPosition", {
  11458. get: function () {
  11459. return this._globalPosition;
  11460. },
  11461. enumerable: true,
  11462. configurable: true
  11463. });
  11464. Camera.prototype.getActiveMeshes = function () {
  11465. return this._activeMeshes;
  11466. };
  11467. Camera.prototype.isActiveMesh = function (mesh) {
  11468. return (this._activeMeshes.indexOf(mesh) !== -1);
  11469. };
  11470. //Cache
  11471. Camera.prototype._initCache = function () {
  11472. _super.prototype._initCache.call(this);
  11473. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11474. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11475. this._cache.mode = undefined;
  11476. this._cache.minZ = undefined;
  11477. this._cache.maxZ = undefined;
  11478. this._cache.fov = undefined;
  11479. this._cache.aspectRatio = undefined;
  11480. this._cache.orthoLeft = undefined;
  11481. this._cache.orthoRight = undefined;
  11482. this._cache.orthoBottom = undefined;
  11483. this._cache.orthoTop = undefined;
  11484. this._cache.renderWidth = undefined;
  11485. this._cache.renderHeight = undefined;
  11486. };
  11487. Camera.prototype._updateCache = function (ignoreParentClass) {
  11488. if (!ignoreParentClass) {
  11489. _super.prototype._updateCache.call(this);
  11490. }
  11491. var engine = this.getEngine();
  11492. this._cache.position.copyFrom(this.position);
  11493. this._cache.upVector.copyFrom(this.upVector);
  11494. this._cache.mode = this.mode;
  11495. this._cache.minZ = this.minZ;
  11496. this._cache.maxZ = this.maxZ;
  11497. this._cache.fov = this.fov;
  11498. this._cache.aspectRatio = engine.getAspectRatio(this);
  11499. this._cache.orthoLeft = this.orthoLeft;
  11500. this._cache.orthoRight = this.orthoRight;
  11501. this._cache.orthoBottom = this.orthoBottom;
  11502. this._cache.orthoTop = this.orthoTop;
  11503. this._cache.renderWidth = engine.getRenderWidth();
  11504. this._cache.renderHeight = engine.getRenderHeight();
  11505. };
  11506. Camera.prototype._updateFromScene = function () {
  11507. this.updateCache();
  11508. this._update();
  11509. };
  11510. // Synchronized
  11511. Camera.prototype._isSynchronized = function () {
  11512. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11513. };
  11514. Camera.prototype._isSynchronizedViewMatrix = function () {
  11515. if (!_super.prototype._isSynchronized.call(this))
  11516. return false;
  11517. return this._cache.position.equals(this.position)
  11518. && this._cache.upVector.equals(this.upVector)
  11519. && this.isSynchronizedWithParent();
  11520. };
  11521. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11522. var check = this._cache.mode === this.mode
  11523. && this._cache.minZ === this.minZ
  11524. && this._cache.maxZ === this.maxZ;
  11525. if (!check) {
  11526. return false;
  11527. }
  11528. var engine = this.getEngine();
  11529. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11530. check = this._cache.fov === this.fov
  11531. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11532. }
  11533. else {
  11534. check = this._cache.orthoLeft === this.orthoLeft
  11535. && this._cache.orthoRight === this.orthoRight
  11536. && this._cache.orthoBottom === this.orthoBottom
  11537. && this._cache.orthoTop === this.orthoTop
  11538. && this._cache.renderWidth === engine.getRenderWidth()
  11539. && this._cache.renderHeight === engine.getRenderHeight();
  11540. }
  11541. return check;
  11542. };
  11543. // Controls
  11544. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11545. };
  11546. Camera.prototype.detachControl = function (element) {
  11547. };
  11548. Camera.prototype._update = function () {
  11549. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11550. this._updateRigCameras();
  11551. }
  11552. this._checkInputs();
  11553. };
  11554. Camera.prototype._checkInputs = function () {
  11555. };
  11556. Camera.prototype._cascadePostProcessesToRigCams = function () {
  11557. // invalidate framebuffer
  11558. if (this._postProcesses.length > 0) {
  11559. this._postProcesses[0].markTextureDirty();
  11560. }
  11561. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  11562. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  11563. var cam = this._rigCameras[i];
  11564. var rigPostProcess = cam._rigPostProcess;
  11565. // for VR rig, there does not have to be a post process
  11566. if (rigPostProcess) {
  11567. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  11568. if (isPass) {
  11569. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  11570. cam.isIntermediate = this._postProcesses.length === 0;
  11571. }
  11572. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  11573. rigPostProcess.markTextureDirty();
  11574. }
  11575. }
  11576. };
  11577. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11578. if (insertAt === void 0) { insertAt = null; }
  11579. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11580. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11581. return 0;
  11582. }
  11583. if (insertAt == null || insertAt < 0) {
  11584. this._postProcesses.push(postProcess);
  11585. }
  11586. else {
  11587. this._postProcesses.splice(insertAt, 0, postProcess);
  11588. }
  11589. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11590. return this._postProcesses.indexOf(postProcess);
  11591. };
  11592. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11593. if (atIndices === void 0) { atIndices = null; }
  11594. var result = [];
  11595. var i;
  11596. var index;
  11597. if (!atIndices) {
  11598. var idx = this._postProcesses.indexOf(postProcess);
  11599. if (idx !== -1) {
  11600. this._postProcesses.splice(idx, 1);
  11601. }
  11602. }
  11603. else {
  11604. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11605. // iterate descending, so can just splice as we go
  11606. for (i = atIndices.length - 1; i >= 0; i--) {
  11607. if (this._postProcesses[atIndices[i]] !== postProcess) {
  11608. result.push(i);
  11609. continue;
  11610. }
  11611. this._postProcesses.splice(index, 1);
  11612. }
  11613. }
  11614. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11615. return result;
  11616. };
  11617. Camera.prototype.getWorldMatrix = function () {
  11618. if (!this._worldMatrix) {
  11619. this._worldMatrix = BABYLON.Matrix.Identity();
  11620. }
  11621. var viewMatrix = this.getViewMatrix();
  11622. viewMatrix.invertToRef(this._worldMatrix);
  11623. return this._worldMatrix;
  11624. };
  11625. Camera.prototype._getViewMatrix = function () {
  11626. return BABYLON.Matrix.Identity();
  11627. };
  11628. Camera.prototype.getViewMatrix = function (force) {
  11629. this._computedViewMatrix = this._computeViewMatrix(force);
  11630. if (!force && this._isSynchronizedViewMatrix()) {
  11631. return this._computedViewMatrix;
  11632. }
  11633. if (!this.parent || !this.parent.getWorldMatrix) {
  11634. this._globalPosition.copyFrom(this.position);
  11635. }
  11636. else {
  11637. if (!this._worldMatrix) {
  11638. this._worldMatrix = BABYLON.Matrix.Identity();
  11639. }
  11640. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11641. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11642. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11643. this._computedViewMatrix.invert();
  11644. this._markSyncedWithParent();
  11645. }
  11646. this._currentRenderId = this.getScene().getRenderId();
  11647. return this._computedViewMatrix;
  11648. };
  11649. Camera.prototype._computeViewMatrix = function (force) {
  11650. if (!force && this._isSynchronizedViewMatrix()) {
  11651. return this._computedViewMatrix;
  11652. }
  11653. this._computedViewMatrix = this._getViewMatrix();
  11654. this._currentRenderId = this.getScene().getRenderId();
  11655. return this._computedViewMatrix;
  11656. };
  11657. Camera.prototype.getProjectionMatrix = function (force) {
  11658. if (!force && this._isSynchronizedProjectionMatrix()) {
  11659. return this._projectionMatrix;
  11660. }
  11661. var engine = this.getEngine();
  11662. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11663. if (this.minZ <= 0) {
  11664. this.minZ = 0.1;
  11665. }
  11666. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11667. return this._projectionMatrix;
  11668. }
  11669. var halfWidth = engine.getRenderWidth() / 2.0;
  11670. var halfHeight = engine.getRenderHeight() / 2.0;
  11671. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11672. return this._projectionMatrix;
  11673. };
  11674. Camera.prototype.dispose = function () {
  11675. // Animations
  11676. this.getScene().stopAnimation(this);
  11677. // Remove from scene
  11678. this.getScene().removeCamera(this);
  11679. while (this._rigCameras.length > 0) {
  11680. this._rigCameras.pop().dispose();
  11681. }
  11682. // Postprocesses
  11683. for (var i = 0; i < this._postProcesses.length; ++i) {
  11684. this._postProcesses[i].dispose(this);
  11685. }
  11686. _super.prototype.dispose.call(this);
  11687. };
  11688. // ---- Camera rigs section ----
  11689. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11690. while (this._rigCameras.length > 0) {
  11691. this._rigCameras.pop().dispose();
  11692. }
  11693. this.cameraRigMode = mode;
  11694. this._cameraRigParams = {};
  11695. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11696. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11697. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11698. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11699. // create the rig cameras, unless none
  11700. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11701. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11702. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11703. }
  11704. switch (this.cameraRigMode) {
  11705. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11706. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11707. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  11708. break;
  11709. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11710. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11711. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11712. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11713. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11714. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  11715. break;
  11716. case Camera.RIG_MODE_VR:
  11717. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11718. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11719. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11720. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11721. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11722. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11723. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11724. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  11725. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11726. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11727. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11728. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11729. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11730. if (metrics.compensateDistortion) {
  11731. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  11732. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  11733. }
  11734. break;
  11735. }
  11736. this._cascadePostProcessesToRigCams();
  11737. this._update();
  11738. };
  11739. Camera.prototype._getVRProjectionMatrix = function () {
  11740. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11741. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11742. return this._projectionMatrix;
  11743. };
  11744. Camera.prototype.setCameraRigParameter = function (name, value) {
  11745. if (!this._cameraRigParams) {
  11746. this._cameraRigParams = {};
  11747. }
  11748. this._cameraRigParams[name] = value;
  11749. //provisionnally:
  11750. if (name === "interaxialDistance") {
  11751. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11752. }
  11753. };
  11754. /**
  11755. * needs to be overridden by children so sub has required properties to be copied
  11756. */
  11757. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11758. return null;
  11759. };
  11760. /**
  11761. * May need to be overridden by children
  11762. */
  11763. Camera.prototype._updateRigCameras = function () {
  11764. for (var i = 0; i < this._rigCameras.length; i++) {
  11765. this._rigCameras[i].minZ = this.minZ;
  11766. this._rigCameras[i].maxZ = this.maxZ;
  11767. this._rigCameras[i].fov = this.fov;
  11768. }
  11769. // only update viewport when ANAGLYPH
  11770. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11771. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11772. }
  11773. };
  11774. Camera.prototype._setupInputs = function () {
  11775. };
  11776. Camera.prototype.serialize = function () {
  11777. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11778. // Type
  11779. serializationObject.type = this.getTypeName();
  11780. // Parent
  11781. if (this.parent) {
  11782. serializationObject.parentId = this.parent.id;
  11783. }
  11784. if (this.inputs) {
  11785. this.inputs.serialize(serializationObject);
  11786. }
  11787. // Animations
  11788. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11789. serializationObject.ranges = this.serializeAnimationRanges();
  11790. return serializationObject;
  11791. };
  11792. Camera.prototype.getTypeName = function () {
  11793. return "Camera";
  11794. };
  11795. Camera.prototype.clone = function (name) {
  11796. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11797. };
  11798. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11799. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11800. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11801. switch (type) {
  11802. case "ArcRotateCamera":
  11803. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11804. case "DeviceOrientationCamera":
  11805. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11806. case "FollowCamera":
  11807. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11808. case "ArcFollowCamera":
  11809. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11810. case "GamepadCamera":
  11811. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11812. case "TouchCamera":
  11813. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11814. case "VirtualJoysticksCamera":
  11815. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11816. case "WebVRFreeCamera":
  11817. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11818. case "VRDeviceOrientationFreeCamera":
  11819. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11820. case "AnaglyphArcRotateCamera":
  11821. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11822. case "AnaglyphFreeCamera":
  11823. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11824. case "AnaglyphGamepadCamera":
  11825. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11826. case "AnaglyphUniversalCamera":
  11827. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11828. case "StereoscopicArcRotateCamera":
  11829. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11830. case "StereoscopicFreeCamera":
  11831. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11832. case "StereoscopicGamepadCamera":
  11833. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11834. case "StereoscopicUniversalCamera":
  11835. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11836. case "FreeCamera":
  11837. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11838. default:
  11839. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11840. }
  11841. };
  11842. Camera.Parse = function (parsedCamera, scene) {
  11843. var type = parsedCamera.type;
  11844. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11845. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11846. // Parent
  11847. if (parsedCamera.parentId) {
  11848. camera._waitingParentId = parsedCamera.parentId;
  11849. }
  11850. //If camera has an input manager, let it parse inputs settings
  11851. if (camera.inputs) {
  11852. camera.inputs.parse(parsedCamera);
  11853. camera._setupInputs();
  11854. }
  11855. // Target
  11856. if (parsedCamera.target) {
  11857. if (camera.setTarget) {
  11858. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11859. }
  11860. }
  11861. // Apply 3d rig, when found
  11862. if (parsedCamera.cameraRigMode) {
  11863. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11864. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11865. }
  11866. // Animations
  11867. if (parsedCamera.animations) {
  11868. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11869. var parsedAnimation = parsedCamera.animations[animationIndex];
  11870. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11871. }
  11872. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11873. }
  11874. if (parsedCamera.autoAnimate) {
  11875. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11876. }
  11877. return camera;
  11878. };
  11879. // Statics
  11880. Camera._PERSPECTIVE_CAMERA = 0;
  11881. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11882. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11883. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11884. Camera._RIG_MODE_NONE = 0;
  11885. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11886. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11887. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11888. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11889. Camera._RIG_MODE_VR = 20;
  11890. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11891. __decorate([
  11892. BABYLON.serializeAsVector3()
  11893. ], Camera.prototype, "position", void 0);
  11894. __decorate([
  11895. BABYLON.serializeAsVector3()
  11896. ], Camera.prototype, "upVector", void 0);
  11897. __decorate([
  11898. BABYLON.serialize()
  11899. ], Camera.prototype, "orthoLeft", void 0);
  11900. __decorate([
  11901. BABYLON.serialize()
  11902. ], Camera.prototype, "orthoRight", void 0);
  11903. __decorate([
  11904. BABYLON.serialize()
  11905. ], Camera.prototype, "orthoBottom", void 0);
  11906. __decorate([
  11907. BABYLON.serialize()
  11908. ], Camera.prototype, "orthoTop", void 0);
  11909. __decorate([
  11910. BABYLON.serialize()
  11911. ], Camera.prototype, "fov", void 0);
  11912. __decorate([
  11913. BABYLON.serialize()
  11914. ], Camera.prototype, "minZ", void 0);
  11915. __decorate([
  11916. BABYLON.serialize()
  11917. ], Camera.prototype, "maxZ", void 0);
  11918. __decorate([
  11919. BABYLON.serialize()
  11920. ], Camera.prototype, "inertia", void 0);
  11921. __decorate([
  11922. BABYLON.serialize()
  11923. ], Camera.prototype, "mode", void 0);
  11924. __decorate([
  11925. BABYLON.serialize()
  11926. ], Camera.prototype, "layerMask", void 0);
  11927. __decorate([
  11928. BABYLON.serialize()
  11929. ], Camera.prototype, "fovMode", void 0);
  11930. __decorate([
  11931. BABYLON.serialize()
  11932. ], Camera.prototype, "cameraRigMode", void 0);
  11933. __decorate([
  11934. BABYLON.serialize()
  11935. ], Camera.prototype, "interaxialDistance", void 0);
  11936. __decorate([
  11937. BABYLON.serialize()
  11938. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11939. return Camera;
  11940. })(BABYLON.Node);
  11941. BABYLON.Camera = Camera;
  11942. })(BABYLON || (BABYLON = {}));
  11943. var BABYLON;
  11944. (function (BABYLON) {
  11945. BABYLON.CameraInputTypes = {};
  11946. var CameraInputsManager = (function () {
  11947. function CameraInputsManager(camera) {
  11948. this.attached = {};
  11949. this.camera = camera;
  11950. this.checkInputs = function () { };
  11951. }
  11952. CameraInputsManager.prototype.add = function (input) {
  11953. var type = input.getSimpleName();
  11954. if (this.attached[type]) {
  11955. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11956. return;
  11957. }
  11958. this.attached[type] = input;
  11959. input.camera = this.camera;
  11960. //for checkInputs, we are dynamically creating a function
  11961. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11962. if (input.checkInputs) {
  11963. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11964. }
  11965. if (this.attachedElement) {
  11966. input.attachControl(this.attachedElement);
  11967. }
  11968. };
  11969. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11970. for (var cam in this.attached) {
  11971. var input = this.attached[cam];
  11972. if (input === inputToRemove) {
  11973. input.detachControl(this.attachedElement);
  11974. delete this.attached[cam];
  11975. this.rebuildInputCheck();
  11976. }
  11977. }
  11978. };
  11979. CameraInputsManager.prototype.removeByType = function (inputType) {
  11980. for (var cam in this.attached) {
  11981. var input = this.attached[cam];
  11982. if (input.getTypeName() === inputType) {
  11983. input.detachControl(this.attachedElement);
  11984. delete this.attached[cam];
  11985. this.rebuildInputCheck();
  11986. }
  11987. }
  11988. };
  11989. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11990. var current = this.checkInputs;
  11991. return function () {
  11992. current();
  11993. fn();
  11994. };
  11995. };
  11996. CameraInputsManager.prototype.attachInput = function (input) {
  11997. input.attachControl(this.attachedElement, this.noPreventDefault);
  11998. };
  11999. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12000. if (this.attachedElement) {
  12001. return;
  12002. }
  12003. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12004. this.attachedElement = element;
  12005. this.noPreventDefault = noPreventDefault;
  12006. for (var cam in this.attached) {
  12007. var input = this.attached[cam];
  12008. this.attached[cam].attachControl(element, noPreventDefault);
  12009. }
  12010. };
  12011. CameraInputsManager.prototype.detachElement = function (element) {
  12012. if (this.attachedElement !== element) {
  12013. return;
  12014. }
  12015. for (var cam in this.attached) {
  12016. var input = this.attached[cam];
  12017. this.attached[cam].detachControl(element);
  12018. }
  12019. this.attachedElement = null;
  12020. };
  12021. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12022. this.checkInputs = function () { };
  12023. for (var cam in this.attached) {
  12024. var input = this.attached[cam];
  12025. if (input.checkInputs) {
  12026. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12027. }
  12028. }
  12029. };
  12030. CameraInputsManager.prototype.clear = function () {
  12031. if (this.attachedElement) {
  12032. this.detachElement(this.attachedElement);
  12033. }
  12034. this.attached = {};
  12035. this.attachedElement = null;
  12036. this.checkInputs = function () { };
  12037. };
  12038. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12039. var inputs = {};
  12040. for (var cam in this.attached) {
  12041. var input = this.attached[cam];
  12042. var res = BABYLON.SerializationHelper.Serialize(input);
  12043. inputs[input.getTypeName()] = res;
  12044. }
  12045. serializedCamera.inputsmgr = inputs;
  12046. };
  12047. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12048. var parsedInputs = parsedCamera.inputsmgr;
  12049. if (parsedInputs) {
  12050. this.clear();
  12051. for (var n in parsedInputs) {
  12052. var construct = BABYLON.CameraInputTypes[n];
  12053. if (construct) {
  12054. var parsedinput = parsedInputs[n];
  12055. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12056. this.add(input);
  12057. }
  12058. }
  12059. }
  12060. else {
  12061. //2016-03-08 this part is for managing backward compatibility
  12062. for (var n in this.attached) {
  12063. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12064. if (construct) {
  12065. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12066. this.remove(this.attached[n]);
  12067. this.add(input);
  12068. }
  12069. }
  12070. }
  12071. };
  12072. return CameraInputsManager;
  12073. })();
  12074. BABYLON.CameraInputsManager = CameraInputsManager;
  12075. })(BABYLON || (BABYLON = {}));
  12076. var BABYLON;
  12077. (function (BABYLON) {
  12078. var FreeCameraMouseInput = (function () {
  12079. function FreeCameraMouseInput(touchEnabled) {
  12080. if (touchEnabled === void 0) { touchEnabled = true; }
  12081. this.touchEnabled = touchEnabled;
  12082. this.angularSensibility = 2000.0;
  12083. }
  12084. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12085. var _this = this;
  12086. if (!this._pointerInput) {
  12087. var camera = this.camera;
  12088. var engine = this.camera.getEngine();
  12089. this._pointerInput = function (p, s) {
  12090. var evt = p.event;
  12091. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12092. return;
  12093. }
  12094. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12095. try {
  12096. evt.srcElement.setPointerCapture(evt.pointerId);
  12097. }
  12098. catch (e) {
  12099. }
  12100. _this.previousPosition = {
  12101. x: evt.clientX,
  12102. y: evt.clientY
  12103. };
  12104. if (!noPreventDefault) {
  12105. evt.preventDefault();
  12106. }
  12107. }
  12108. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12109. try {
  12110. evt.srcElement.releasePointerCapture(evt.pointerId);
  12111. }
  12112. catch (e) {
  12113. }
  12114. _this.previousPosition = null;
  12115. if (!noPreventDefault) {
  12116. evt.preventDefault();
  12117. }
  12118. }
  12119. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12120. if (!_this.previousPosition && !engine.isPointerLock) {
  12121. return;
  12122. }
  12123. var offsetX;
  12124. var offsetY;
  12125. if (!engine.isPointerLock) {
  12126. offsetX = evt.clientX - _this.previousPosition.x;
  12127. offsetY = evt.clientY - _this.previousPosition.y;
  12128. }
  12129. else {
  12130. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12131. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12132. }
  12133. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12134. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12135. _this.previousPosition = {
  12136. x: evt.clientX,
  12137. y: evt.clientY
  12138. };
  12139. if (!noPreventDefault) {
  12140. evt.preventDefault();
  12141. }
  12142. }
  12143. };
  12144. }
  12145. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12146. };
  12147. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12148. if (this._observer && element) {
  12149. this.camera.getScene().onPointerObservable.remove(this._observer);
  12150. this._observer = null;
  12151. this.previousPosition = null;
  12152. }
  12153. };
  12154. FreeCameraMouseInput.prototype.getTypeName = function () {
  12155. return "FreeCameraMouseInput";
  12156. };
  12157. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12158. return "mouse";
  12159. };
  12160. __decorate([
  12161. BABYLON.serialize()
  12162. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12163. return FreeCameraMouseInput;
  12164. })();
  12165. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12166. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12167. })(BABYLON || (BABYLON = {}));
  12168. var BABYLON;
  12169. (function (BABYLON) {
  12170. var FreeCameraKeyboardMoveInput = (function () {
  12171. function FreeCameraKeyboardMoveInput() {
  12172. this._keys = [];
  12173. this.keysUp = [38];
  12174. this.keysDown = [40];
  12175. this.keysLeft = [37];
  12176. this.keysRight = [39];
  12177. }
  12178. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12179. var _this = this;
  12180. if (!this._onKeyDown) {
  12181. this._onKeyDown = function (evt) {
  12182. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12183. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12184. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12185. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12186. var index = _this._keys.indexOf(evt.keyCode);
  12187. if (index === -1) {
  12188. _this._keys.push(evt.keyCode);
  12189. }
  12190. if (!noPreventDefault) {
  12191. evt.preventDefault();
  12192. }
  12193. }
  12194. };
  12195. this._onKeyUp = function (evt) {
  12196. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12197. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12198. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12199. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12200. var index = _this._keys.indexOf(evt.keyCode);
  12201. if (index >= 0) {
  12202. _this._keys.splice(index, 1);
  12203. }
  12204. if (!noPreventDefault) {
  12205. evt.preventDefault();
  12206. }
  12207. }
  12208. };
  12209. BABYLON.Tools.RegisterTopRootEvents([
  12210. { name: "keydown", handler: this._onKeyDown },
  12211. { name: "keyup", handler: this._onKeyUp },
  12212. { name: "blur", handler: this._onLostFocus }
  12213. ]);
  12214. }
  12215. };
  12216. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12217. if (this._onKeyDown) {
  12218. BABYLON.Tools.UnregisterTopRootEvents([
  12219. { name: "keydown", handler: this._onKeyDown },
  12220. { name: "keyup", handler: this._onKeyUp },
  12221. { name: "blur", handler: this._onLostFocus }
  12222. ]);
  12223. this._keys = [];
  12224. this._onKeyDown = null;
  12225. this._onKeyUp = null;
  12226. }
  12227. };
  12228. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12229. if (this._onKeyDown) {
  12230. var camera = this.camera;
  12231. // Keyboard
  12232. for (var index = 0; index < this._keys.length; index++) {
  12233. var keyCode = this._keys[index];
  12234. var speed = camera._computeLocalCameraSpeed();
  12235. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12236. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12237. }
  12238. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12239. camera._localDirection.copyFromFloats(0, 0, speed);
  12240. }
  12241. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12242. camera._localDirection.copyFromFloats(speed, 0, 0);
  12243. }
  12244. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12245. camera._localDirection.copyFromFloats(0, 0, -speed);
  12246. }
  12247. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12248. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12249. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12250. }
  12251. }
  12252. };
  12253. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12254. return "FreeCameraKeyboardMoveInput";
  12255. };
  12256. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12257. this._keys = [];
  12258. };
  12259. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12260. return "keyboard";
  12261. };
  12262. __decorate([
  12263. BABYLON.serialize()
  12264. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12265. __decorate([
  12266. BABYLON.serialize()
  12267. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12268. __decorate([
  12269. BABYLON.serialize()
  12270. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12271. __decorate([
  12272. BABYLON.serialize()
  12273. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12274. return FreeCameraKeyboardMoveInput;
  12275. })();
  12276. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12277. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12278. })(BABYLON || (BABYLON = {}));
  12279. var BABYLON;
  12280. (function (BABYLON) {
  12281. var FreeCameraTouchInput = (function () {
  12282. function FreeCameraTouchInput() {
  12283. this._offsetX = null;
  12284. this._offsetY = null;
  12285. this._pointerCount = 0;
  12286. this._pointerPressed = [];
  12287. this.touchAngularSensibility = 200000.0;
  12288. this.touchMoveSensibility = 250.0;
  12289. }
  12290. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12291. var _this = this;
  12292. var previousPosition;
  12293. if (this._pointerInput === undefined) {
  12294. this._onLostFocus = function (evt) {
  12295. _this._offsetX = null;
  12296. _this._offsetY = null;
  12297. };
  12298. this._pointerInput = function (p, s) {
  12299. var evt = p.event;
  12300. if (evt.pointerType === "mouse") {
  12301. return;
  12302. }
  12303. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12304. if (!noPreventDefault) {
  12305. evt.preventDefault();
  12306. }
  12307. _this._pointerPressed.push(evt.pointerId);
  12308. if (_this._pointerPressed.length !== 1) {
  12309. return;
  12310. }
  12311. previousPosition = {
  12312. x: evt.clientX,
  12313. y: evt.clientY
  12314. };
  12315. }
  12316. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12317. if (!noPreventDefault) {
  12318. evt.preventDefault();
  12319. }
  12320. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12321. if (index === -1) {
  12322. return;
  12323. }
  12324. _this._pointerPressed.splice(index, 1);
  12325. if (index != 0) {
  12326. return;
  12327. }
  12328. previousPosition = null;
  12329. _this._offsetX = null;
  12330. _this._offsetY = null;
  12331. }
  12332. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12333. if (!noPreventDefault) {
  12334. evt.preventDefault();
  12335. }
  12336. if (!previousPosition) {
  12337. return;
  12338. }
  12339. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12340. if (index != 0) {
  12341. return;
  12342. }
  12343. _this._offsetX = evt.clientX - previousPosition.x;
  12344. _this._offsetY = -(evt.clientY - previousPosition.y);
  12345. }
  12346. };
  12347. }
  12348. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12349. element.addEventListener("blur", this._onLostFocus);
  12350. };
  12351. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12352. if (this._pointerInput && element) {
  12353. this.camera.getScene().onPointerObservable.remove(this._observer);
  12354. this._observer = null;
  12355. element.removeEventListener("blur", this._onLostFocus);
  12356. this._onLostFocus = null;
  12357. this._pointerPressed = [];
  12358. this._offsetX = null;
  12359. this._offsetY = null;
  12360. this._pointerCount = 0;
  12361. }
  12362. };
  12363. FreeCameraTouchInput.prototype.checkInputs = function () {
  12364. if (this._offsetX) {
  12365. var camera = this.camera;
  12366. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12367. if (this._pointerPressed.length > 1) {
  12368. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12369. }
  12370. else {
  12371. var speed = camera._computeLocalCameraSpeed();
  12372. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12373. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12374. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12375. }
  12376. }
  12377. };
  12378. FreeCameraTouchInput.prototype.getTypeName = function () {
  12379. return "FreeCameraTouchInput";
  12380. };
  12381. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12382. return "touch";
  12383. };
  12384. __decorate([
  12385. BABYLON.serialize()
  12386. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12387. __decorate([
  12388. BABYLON.serialize()
  12389. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12390. return FreeCameraTouchInput;
  12391. })();
  12392. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12393. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12394. })(BABYLON || (BABYLON = {}));
  12395. var BABYLON;
  12396. (function (BABYLON) {
  12397. var FreeCameraDeviceOrientationInput = (function () {
  12398. function FreeCameraDeviceOrientationInput() {
  12399. var _this = this;
  12400. this._screenOrientationAngle = 0;
  12401. this._screenQuaternion = new BABYLON.Quaternion();
  12402. this._alpha = 0;
  12403. this._beta = 0;
  12404. this._gamma = 0;
  12405. this._orientationChanged = function () {
  12406. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12407. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12408. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12409. };
  12410. this._deviceOrientation = function (evt) {
  12411. _this._alpha = evt.alpha;
  12412. _this._beta = evt.beta;
  12413. _this._gamma = evt.gamma;
  12414. };
  12415. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12416. this._orientationChanged();
  12417. }
  12418. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12419. get: function () {
  12420. return this._camera;
  12421. },
  12422. set: function (camera) {
  12423. this._camera = camera;
  12424. if (!this._camera.rotationQuaternion)
  12425. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12426. },
  12427. enumerable: true,
  12428. configurable: true
  12429. });
  12430. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12431. window.addEventListener("orientationchange", this._orientationChanged);
  12432. window.addEventListener("deviceorientation", this._deviceOrientation);
  12433. };
  12434. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12435. window.removeEventListener("orientationchange", this._orientationChanged);
  12436. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12437. };
  12438. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12439. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12440. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12441. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12442. //Mirror on XY Plane
  12443. this._camera.rotationQuaternion.z *= -1;
  12444. this._camera.rotationQuaternion.w *= -1;
  12445. };
  12446. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12447. return "FreeCameraDeviceOrientationInput";
  12448. };
  12449. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12450. return "deviceOrientation";
  12451. };
  12452. return FreeCameraDeviceOrientationInput;
  12453. })();
  12454. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12455. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12456. })(BABYLON || (BABYLON = {}));
  12457. var BABYLON;
  12458. (function (BABYLON) {
  12459. var FreeCameraVRDeviceOrientationInput = (function () {
  12460. function FreeCameraVRDeviceOrientationInput() {
  12461. this.alphaCorrection = 1;
  12462. this.betaCorrection = 1;
  12463. this.gammaCorrection = 1;
  12464. this._alpha = 0;
  12465. this._beta = 0;
  12466. this._gamma = 0;
  12467. this._dirty = false;
  12468. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12469. }
  12470. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12471. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12472. };
  12473. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12474. var camera = this.camera;
  12475. this._alpha = evt.alpha;
  12476. this._beta = evt.beta;
  12477. this._gamma = evt.gamma;
  12478. this._dirty = true;
  12479. };
  12480. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12481. if (this._dirty) {
  12482. this._dirty = false;
  12483. var rotationX = this._gamma;
  12484. if (rotationX < 0) {
  12485. rotationX = 90 + rotationX;
  12486. }
  12487. else {
  12488. // Incline it in the correct angle.
  12489. rotationX = 270 - rotationX;
  12490. }
  12491. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12492. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12493. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12494. }
  12495. };
  12496. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12497. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12498. };
  12499. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12500. return "FreeCameraVRDeviceOrientationInput";
  12501. };
  12502. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12503. return "VRDeviceOrientation";
  12504. };
  12505. return FreeCameraVRDeviceOrientationInput;
  12506. })();
  12507. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12508. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12509. })(BABYLON || (BABYLON = {}));
  12510. var BABYLON;
  12511. (function (BABYLON) {
  12512. var FreeCameraGamepadInput = (function () {
  12513. function FreeCameraGamepadInput() {
  12514. this.gamepadAngularSensibility = 200;
  12515. this.gamepadMoveSensibility = 40;
  12516. }
  12517. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12518. var _this = this;
  12519. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12520. };
  12521. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12522. if (this._gamepads) {
  12523. this._gamepads.dispose();
  12524. }
  12525. this.gamepad = null;
  12526. };
  12527. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12528. if (this.gamepad) {
  12529. var camera = this.camera;
  12530. var LSValues = this.gamepad.leftStick;
  12531. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12532. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12533. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12534. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12535. var RSValues = this.gamepad.rightStick;
  12536. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12537. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12538. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12539. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12540. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12541. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12542. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12543. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12544. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12545. }
  12546. };
  12547. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12548. // Only the first gamepad can control the camera
  12549. if (gamepad.index === 0) {
  12550. this.gamepad = gamepad;
  12551. }
  12552. };
  12553. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12554. return "FreeCameraGamepadInput";
  12555. };
  12556. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12557. return "gamepad";
  12558. };
  12559. __decorate([
  12560. BABYLON.serialize()
  12561. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12562. __decorate([
  12563. BABYLON.serialize()
  12564. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12565. return FreeCameraGamepadInput;
  12566. })();
  12567. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12568. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12569. })(BABYLON || (BABYLON = {}));
  12570. var BABYLON;
  12571. (function (BABYLON) {
  12572. var ArcRotateCameraKeyboardMoveInput = (function () {
  12573. function ArcRotateCameraKeyboardMoveInput() {
  12574. this._keys = [];
  12575. this.keysUp = [38];
  12576. this.keysDown = [40];
  12577. this.keysLeft = [37];
  12578. this.keysRight = [39];
  12579. }
  12580. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12581. var _this = this;
  12582. this._onKeyDown = function (evt) {
  12583. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12584. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12585. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12586. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12587. var index = _this._keys.indexOf(evt.keyCode);
  12588. if (index === -1) {
  12589. _this._keys.push(evt.keyCode);
  12590. }
  12591. if (evt.preventDefault) {
  12592. if (!noPreventDefault) {
  12593. evt.preventDefault();
  12594. }
  12595. }
  12596. }
  12597. };
  12598. this._onKeyUp = function (evt) {
  12599. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12600. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12601. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12602. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12603. var index = _this._keys.indexOf(evt.keyCode);
  12604. if (index >= 0) {
  12605. _this._keys.splice(index, 1);
  12606. }
  12607. if (evt.preventDefault) {
  12608. if (!noPreventDefault) {
  12609. evt.preventDefault();
  12610. }
  12611. }
  12612. }
  12613. };
  12614. this._onLostFocus = function () {
  12615. _this._keys = [];
  12616. };
  12617. BABYLON.Tools.RegisterTopRootEvents([
  12618. { name: "keydown", handler: this._onKeyDown },
  12619. { name: "keyup", handler: this._onKeyUp },
  12620. { name: "blur", handler: this._onLostFocus }
  12621. ]);
  12622. };
  12623. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12624. BABYLON.Tools.UnregisterTopRootEvents([
  12625. { name: "keydown", handler: this._onKeyDown },
  12626. { name: "keyup", handler: this._onKeyUp },
  12627. { name: "blur", handler: this._onLostFocus }
  12628. ]);
  12629. this._keys = [];
  12630. this._onKeyDown = null;
  12631. this._onKeyUp = null;
  12632. this._onLostFocus = null;
  12633. };
  12634. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12635. if (this._onKeyDown) {
  12636. var camera = this.camera;
  12637. for (var index = 0; index < this._keys.length; index++) {
  12638. var keyCode = this._keys[index];
  12639. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12640. camera.inertialAlphaOffset -= 0.01;
  12641. }
  12642. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12643. camera.inertialBetaOffset -= 0.01;
  12644. }
  12645. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12646. camera.inertialAlphaOffset += 0.01;
  12647. }
  12648. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12649. camera.inertialBetaOffset += 0.01;
  12650. }
  12651. }
  12652. }
  12653. };
  12654. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12655. return "ArcRotateCameraKeyboardMoveInput";
  12656. };
  12657. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12658. return "keyboard";
  12659. };
  12660. __decorate([
  12661. BABYLON.serialize()
  12662. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12663. __decorate([
  12664. BABYLON.serialize()
  12665. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12666. __decorate([
  12667. BABYLON.serialize()
  12668. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12669. __decorate([
  12670. BABYLON.serialize()
  12671. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12672. return ArcRotateCameraKeyboardMoveInput;
  12673. })();
  12674. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12675. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12676. })(BABYLON || (BABYLON = {}));
  12677. var BABYLON;
  12678. (function (BABYLON) {
  12679. var ArcRotateCameraMouseWheelInput = (function () {
  12680. function ArcRotateCameraMouseWheelInput() {
  12681. this.wheelPrecision = 3.0;
  12682. }
  12683. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12684. var _this = this;
  12685. this._wheel = function (p, s) {
  12686. //sanity check - this should be a PointerWheel event.
  12687. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12688. return;
  12689. var event = p.event;
  12690. var delta = 0;
  12691. if (event.wheelDelta) {
  12692. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12693. }
  12694. else if (event.detail) {
  12695. delta = -event.detail / _this.wheelPrecision;
  12696. }
  12697. if (delta)
  12698. _this.camera.inertialRadiusOffset += delta;
  12699. if (event.preventDefault) {
  12700. if (!noPreventDefault) {
  12701. event.preventDefault();
  12702. }
  12703. }
  12704. };
  12705. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12706. };
  12707. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12708. if (this._observer && element) {
  12709. this.camera.getScene().onPointerObservable.remove(this._observer);
  12710. this._observer = null;
  12711. this._wheel = null;
  12712. }
  12713. };
  12714. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12715. return "ArcRotateCameraMouseWheelInput";
  12716. };
  12717. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12718. return "mousewheel";
  12719. };
  12720. __decorate([
  12721. BABYLON.serialize()
  12722. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12723. return ArcRotateCameraMouseWheelInput;
  12724. })();
  12725. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12726. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12727. })(BABYLON || (BABYLON = {}));
  12728. var BABYLON;
  12729. (function (BABYLON) {
  12730. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12731. var ArcRotateCameraPointersInput = (function () {
  12732. function ArcRotateCameraPointersInput() {
  12733. this.angularSensibilityX = 1000.0;
  12734. this.angularSensibilityY = 1000.0;
  12735. this.pinchPrecision = 6.0;
  12736. this.panningSensibility = 50.0;
  12737. this._isRightClick = false;
  12738. this._isCtrlPushed = false;
  12739. this.pinchInwards = true;
  12740. }
  12741. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12742. var _this = this;
  12743. var engine = this.camera.getEngine();
  12744. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12745. var pointA, pointB;
  12746. var previousPinchDistance = 0;
  12747. this._pointerInput = function (p, s) {
  12748. var evt = p.event;
  12749. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12750. try {
  12751. evt.srcElement.setPointerCapture(evt.pointerId);
  12752. }
  12753. catch (e) {
  12754. }
  12755. // Manage panning with right click
  12756. _this._isRightClick = evt.button === 2;
  12757. // manage pointers
  12758. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  12759. if (pointA === undefined) {
  12760. pointA = cacheSoloPointer;
  12761. }
  12762. else if (pointB === undefined) {
  12763. pointB = cacheSoloPointer;
  12764. }
  12765. if (!noPreventDefault) {
  12766. evt.preventDefault();
  12767. }
  12768. }
  12769. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12770. try {
  12771. evt.srcElement.releasePointerCapture(evt.pointerId);
  12772. }
  12773. catch (e) {
  12774. }
  12775. cacheSoloPointer = null;
  12776. previousPinchDistance = 0;
  12777. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12778. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12779. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12780. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12781. pointA = pointB = undefined;
  12782. if (!noPreventDefault) {
  12783. evt.preventDefault();
  12784. }
  12785. }
  12786. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12787. if (!noPreventDefault) {
  12788. evt.preventDefault();
  12789. }
  12790. // One button down
  12791. if (pointA && pointB === undefined) {
  12792. if (_this.panningSensibility !== 0 &&
  12793. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  12794. (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12795. _this.camera
  12796. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12797. _this.camera
  12798. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12799. }
  12800. else {
  12801. var offsetX = evt.clientX - cacheSoloPointer.x;
  12802. var offsetY = evt.clientY - cacheSoloPointer.y;
  12803. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12804. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12805. }
  12806. cacheSoloPointer.x = evt.clientX;
  12807. cacheSoloPointer.y = evt.clientY;
  12808. }
  12809. else if (pointA && pointB) {
  12810. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12811. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  12812. ed.x = evt.clientX;
  12813. ed.y = evt.clientY;
  12814. var direction = _this.pinchInwards ? 1 : -1;
  12815. var distX = pointA.x - pointB.x;
  12816. var distY = pointA.y - pointB.y;
  12817. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12818. if (previousPinchDistance === 0) {
  12819. previousPinchDistance = pinchSquaredDistance;
  12820. return;
  12821. }
  12822. if (pinchSquaredDistance !== previousPinchDistance) {
  12823. _this.camera
  12824. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  12825. (_this.pinchPrecision *
  12826. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  12827. direction);
  12828. previousPinchDistance = pinchSquaredDistance;
  12829. }
  12830. }
  12831. }
  12832. };
  12833. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12834. this._onContextMenu = function (evt) {
  12835. evt.preventDefault();
  12836. };
  12837. if (!this.camera._useCtrlForPanning) {
  12838. element.addEventListener("contextmenu", this._onContextMenu, false);
  12839. }
  12840. this._onLostFocus = function () {
  12841. //this._keys = [];
  12842. pointA = pointB = undefined;
  12843. previousPinchDistance = 0;
  12844. cacheSoloPointer = null;
  12845. };
  12846. this._onKeyDown = function (evt) {
  12847. _this._isCtrlPushed = evt.ctrlKey;
  12848. };
  12849. this._onKeyUp = function (evt) {
  12850. _this._isCtrlPushed = evt.ctrlKey;
  12851. };
  12852. this._onMouseMove = function (evt) {
  12853. if (!engine.isPointerLock) {
  12854. return;
  12855. }
  12856. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12857. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12858. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12859. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12860. if (!noPreventDefault) {
  12861. evt.preventDefault();
  12862. }
  12863. };
  12864. this._onGestureStart = function (e) {
  12865. if (window.MSGesture === undefined) {
  12866. return;
  12867. }
  12868. if (!_this._MSGestureHandler) {
  12869. _this._MSGestureHandler = new MSGesture();
  12870. _this._MSGestureHandler.target = element;
  12871. }
  12872. _this._MSGestureHandler.addPointer(e.pointerId);
  12873. };
  12874. this._onGesture = function (e) {
  12875. _this.camera.radius *= e.scale;
  12876. if (e.preventDefault) {
  12877. if (!noPreventDefault) {
  12878. e.stopPropagation();
  12879. e.preventDefault();
  12880. }
  12881. }
  12882. };
  12883. element.addEventListener("mousemove", this._onMouseMove, false);
  12884. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12885. element.addEventListener("MSGestureChange", this._onGesture, false);
  12886. BABYLON.Tools.RegisterTopRootEvents([
  12887. { name: "keydown", handler: this._onKeyDown },
  12888. { name: "keyup", handler: this._onKeyUp },
  12889. { name: "blur", handler: this._onLostFocus }
  12890. ]);
  12891. };
  12892. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12893. if (element && this._observer) {
  12894. this.camera.getScene().onPointerObservable.remove(this._observer);
  12895. this._observer = null;
  12896. element.removeEventListener("contextmenu", this._onContextMenu);
  12897. element.removeEventListener("mousemove", this._onMouseMove);
  12898. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12899. element.removeEventListener("MSGestureChange", this._onGesture);
  12900. this._isRightClick = false;
  12901. this._isCtrlPushed = false;
  12902. this.pinchInwards = true;
  12903. this._onKeyDown = null;
  12904. this._onKeyUp = null;
  12905. this._onMouseMove = null;
  12906. this._onGestureStart = null;
  12907. this._onGesture = null;
  12908. this._MSGestureHandler = null;
  12909. this._onLostFocus = null;
  12910. this._onContextMenu = null;
  12911. }
  12912. BABYLON.Tools.UnregisterTopRootEvents([
  12913. { name: "keydown", handler: this._onKeyDown },
  12914. { name: "keyup", handler: this._onKeyUp },
  12915. { name: "blur", handler: this._onLostFocus }
  12916. ]);
  12917. };
  12918. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12919. return "ArcRotateCameraPointersInput";
  12920. };
  12921. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12922. return "pointers";
  12923. };
  12924. __decorate([
  12925. BABYLON.serialize()
  12926. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12927. __decorate([
  12928. BABYLON.serialize()
  12929. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12930. __decorate([
  12931. BABYLON.serialize()
  12932. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12933. __decorate([
  12934. BABYLON.serialize()
  12935. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12936. return ArcRotateCameraPointersInput;
  12937. })();
  12938. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12939. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12940. })(BABYLON || (BABYLON = {}));
  12941. var BABYLON;
  12942. (function (BABYLON) {
  12943. var ArcRotateCameraGamepadInput = (function () {
  12944. function ArcRotateCameraGamepadInput() {
  12945. this.gamepadRotationSensibility = 80;
  12946. this.gamepadMoveSensibility = 40;
  12947. }
  12948. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12949. var _this = this;
  12950. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12951. };
  12952. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12953. if (this._gamepads) {
  12954. this._gamepads.dispose();
  12955. }
  12956. this.gamepad = null;
  12957. };
  12958. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12959. if (this.gamepad) {
  12960. var camera = this.camera;
  12961. var RSValues = this.gamepad.rightStick;
  12962. if (RSValues.x != 0) {
  12963. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12964. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12965. camera.inertialAlphaOffset += normalizedRX;
  12966. }
  12967. }
  12968. if (RSValues.y != 0) {
  12969. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12970. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12971. camera.inertialBetaOffset += normalizedRY;
  12972. }
  12973. }
  12974. var LSValues = this.gamepad.leftStick;
  12975. if (LSValues.y != 0) {
  12976. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12977. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12978. this.camera.inertialRadiusOffset -= normalizedLY;
  12979. }
  12980. }
  12981. }
  12982. };
  12983. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12984. // Only the first gamepad can control the camera
  12985. if (gamepad.index === 0) {
  12986. this.gamepad = gamepad;
  12987. }
  12988. };
  12989. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12990. return "ArcRotateCameraGamepadInput";
  12991. };
  12992. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12993. return "gamepad";
  12994. };
  12995. __decorate([
  12996. BABYLON.serialize()
  12997. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12998. __decorate([
  12999. BABYLON.serialize()
  13000. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13001. return ArcRotateCameraGamepadInput;
  13002. })();
  13003. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13004. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13005. })(BABYLON || (BABYLON = {}));
  13006. var BABYLON;
  13007. (function (BABYLON) {
  13008. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13009. function ArcRotateCameraVRDeviceOrientationInput() {
  13010. this.alphaCorrection = 1;
  13011. this.betaCorrection = 1;
  13012. this.gammaCorrection = 1;
  13013. this._alpha = 0;
  13014. this._beta = 0;
  13015. this._gamma = 0;
  13016. this._dirty = false;
  13017. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13018. }
  13019. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13020. this.camera.attachControl(element, noPreventDefault);
  13021. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13022. };
  13023. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13024. var camera = this.camera;
  13025. this._alpha = +evt.alpha | 0;
  13026. this._beta = +evt.beta | 0;
  13027. this._gamma = +evt.gamma | 0;
  13028. this._dirty = true;
  13029. };
  13030. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13031. if (this._dirty) {
  13032. this._dirty = false;
  13033. if (this._gamma < 0) {
  13034. this._gamma = 180 + this._gamma;
  13035. }
  13036. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13037. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13038. }
  13039. };
  13040. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13041. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13042. };
  13043. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13044. return "ArcRotateCameraVRDeviceOrientationInput";
  13045. };
  13046. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13047. return "VRDeviceOrientation";
  13048. };
  13049. return ArcRotateCameraVRDeviceOrientationInput;
  13050. })();
  13051. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13052. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13053. })(BABYLON || (BABYLON = {}));
  13054. var BABYLON;
  13055. (function (BABYLON) {
  13056. var TargetCamera = (function (_super) {
  13057. __extends(TargetCamera, _super);
  13058. function TargetCamera(name, position, scene) {
  13059. _super.call(this, name, position, scene);
  13060. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13061. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13062. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13063. this.speed = 2.0;
  13064. this.noRotationConstraint = false;
  13065. this.lockedTarget = null;
  13066. this._currentTarget = BABYLON.Vector3.Zero();
  13067. this._viewMatrix = BABYLON.Matrix.Zero();
  13068. this._camMatrix = BABYLON.Matrix.Zero();
  13069. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13070. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13071. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13072. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13073. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13074. this._lookAtTemp = BABYLON.Matrix.Zero();
  13075. this._tempMatrix = BABYLON.Matrix.Zero();
  13076. }
  13077. TargetCamera.prototype.getFrontPosition = function (distance) {
  13078. var direction = this.getTarget().subtract(this.position);
  13079. direction.normalize();
  13080. direction.scaleInPlace(distance);
  13081. return this.globalPosition.add(direction);
  13082. };
  13083. TargetCamera.prototype._getLockedTargetPosition = function () {
  13084. if (!this.lockedTarget) {
  13085. return null;
  13086. }
  13087. return this.lockedTarget.position || this.lockedTarget;
  13088. };
  13089. // Cache
  13090. TargetCamera.prototype._initCache = function () {
  13091. _super.prototype._initCache.call(this);
  13092. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13093. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13094. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13095. };
  13096. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13097. if (!ignoreParentClass) {
  13098. _super.prototype._updateCache.call(this);
  13099. }
  13100. var lockedTargetPosition = this._getLockedTargetPosition();
  13101. if (!lockedTargetPosition) {
  13102. this._cache.lockedTarget = null;
  13103. }
  13104. else {
  13105. if (!this._cache.lockedTarget) {
  13106. this._cache.lockedTarget = lockedTargetPosition.clone();
  13107. }
  13108. else {
  13109. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13110. }
  13111. }
  13112. this._cache.rotation.copyFrom(this.rotation);
  13113. if (this.rotationQuaternion)
  13114. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13115. };
  13116. // Synchronized
  13117. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13118. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13119. return false;
  13120. }
  13121. var lockedTargetPosition = this._getLockedTargetPosition();
  13122. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13123. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13124. };
  13125. // Methods
  13126. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13127. var engine = this.getEngine();
  13128. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  13129. };
  13130. // Target
  13131. TargetCamera.prototype.setTarget = function (target) {
  13132. this.upVector.normalize();
  13133. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13134. this._camMatrix.invert();
  13135. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13136. var vDir = target.subtract(this.position);
  13137. if (vDir.x >= 0.0) {
  13138. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13139. }
  13140. else {
  13141. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13142. }
  13143. this.rotation.z = 0;
  13144. if (isNaN(this.rotation.x)) {
  13145. this.rotation.x = 0;
  13146. }
  13147. if (isNaN(this.rotation.y)) {
  13148. this.rotation.y = 0;
  13149. }
  13150. if (isNaN(this.rotation.z)) {
  13151. this.rotation.z = 0;
  13152. }
  13153. if (this.rotationQuaternion) {
  13154. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13155. }
  13156. };
  13157. TargetCamera.prototype.getTarget = function () {
  13158. return this._currentTarget;
  13159. };
  13160. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13161. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13162. };
  13163. TargetCamera.prototype._updatePosition = function () {
  13164. this.position.addInPlace(this.cameraDirection);
  13165. };
  13166. TargetCamera.prototype._checkInputs = function () {
  13167. var needToMove = this._decideIfNeedsToMove();
  13168. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13169. // Move
  13170. if (needToMove) {
  13171. this._updatePosition();
  13172. }
  13173. // Rotate
  13174. if (needToRotate) {
  13175. this.rotation.x += this.cameraRotation.x;
  13176. this.rotation.y += this.cameraRotation.y;
  13177. if (!this.noRotationConstraint) {
  13178. var limit = (Math.PI / 2) * 0.95;
  13179. if (this.rotation.x > limit)
  13180. this.rotation.x = limit;
  13181. if (this.rotation.x < -limit)
  13182. this.rotation.x = -limit;
  13183. }
  13184. }
  13185. // Inertia
  13186. if (needToMove) {
  13187. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13188. this.cameraDirection.x = 0;
  13189. }
  13190. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13191. this.cameraDirection.y = 0;
  13192. }
  13193. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13194. this.cameraDirection.z = 0;
  13195. }
  13196. this.cameraDirection.scaleInPlace(this.inertia);
  13197. }
  13198. if (needToRotate) {
  13199. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13200. this.cameraRotation.x = 0;
  13201. }
  13202. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13203. this.cameraRotation.y = 0;
  13204. }
  13205. this.cameraRotation.scaleInPlace(this.inertia);
  13206. }
  13207. _super.prototype._checkInputs.call(this);
  13208. };
  13209. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13210. if (this.rotationQuaternion) {
  13211. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13212. //update the up vector!
  13213. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13214. }
  13215. else {
  13216. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13217. }
  13218. };
  13219. TargetCamera.prototype._getViewMatrix = function () {
  13220. if (!this.lockedTarget) {
  13221. // Compute
  13222. this._updateCameraRotationMatrix();
  13223. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13224. // Computing target and final matrix
  13225. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13226. }
  13227. else {
  13228. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13229. }
  13230. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13231. return this._viewMatrix;
  13232. };
  13233. TargetCamera.prototype._getVRViewMatrix = function () {
  13234. this._updateCameraRotationMatrix();
  13235. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13236. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  13237. // Computing target and final matrix
  13238. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13239. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  13240. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  13241. return this._viewMatrix;
  13242. };
  13243. /**
  13244. * @override
  13245. * Override Camera.createRigCamera
  13246. */
  13247. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13248. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13249. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13250. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13251. if (!this.rotationQuaternion) {
  13252. this.rotationQuaternion = new BABYLON.Quaternion();
  13253. }
  13254. rigCamera._cameraRigParams = {};
  13255. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  13256. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  13257. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13258. }
  13259. return rigCamera;
  13260. }
  13261. return null;
  13262. };
  13263. /**
  13264. * @override
  13265. * Override Camera._updateRigCameras
  13266. */
  13267. TargetCamera.prototype._updateRigCameras = function () {
  13268. var camLeft = this._rigCameras[0];
  13269. var camRight = this._rigCameras[1];
  13270. switch (this.cameraRigMode) {
  13271. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13272. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13273. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13275. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13276. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13277. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13278. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13279. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13280. camLeft.setTarget(this.getTarget());
  13281. camRight.setTarget(this.getTarget());
  13282. break;
  13283. case BABYLON.Camera.RIG_MODE_VR:
  13284. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13285. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13286. camLeft.position.copyFrom(this.position);
  13287. camRight.position.copyFrom(this.position);
  13288. break;
  13289. }
  13290. _super.prototype._updateRigCameras.call(this);
  13291. };
  13292. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13293. if (!this._rigCamTransformMatrix) {
  13294. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13295. }
  13296. var target = this.getTarget();
  13297. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13298. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13299. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13300. };
  13301. TargetCamera.prototype.getTypeName = function () {
  13302. return "TargetCamera";
  13303. };
  13304. __decorate([
  13305. BABYLON.serializeAsVector3()
  13306. ], TargetCamera.prototype, "rotation", void 0);
  13307. __decorate([
  13308. BABYLON.serialize()
  13309. ], TargetCamera.prototype, "speed", void 0);
  13310. __decorate([
  13311. BABYLON.serializeAsMeshReference("lockedTargetId")
  13312. ], TargetCamera.prototype, "lockedTarget", void 0);
  13313. return TargetCamera;
  13314. })(BABYLON.Camera);
  13315. BABYLON.TargetCamera = TargetCamera;
  13316. })(BABYLON || (BABYLON = {}));
  13317. var BABYLON;
  13318. (function (BABYLON) {
  13319. var FreeCamera = (function (_super) {
  13320. __extends(FreeCamera, _super);
  13321. function FreeCamera(name, position, scene) {
  13322. var _this = this;
  13323. _super.call(this, name, position, scene);
  13324. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13325. this.checkCollisions = false;
  13326. this.applyGravity = false;
  13327. this._collider = new BABYLON.Collider();
  13328. this._needMoveForGravity = false;
  13329. this._oldPosition = BABYLON.Vector3.Zero();
  13330. this._diffPosition = BABYLON.Vector3.Zero();
  13331. this._newPosition = BABYLON.Vector3.Zero();
  13332. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13333. if (collidedMesh === void 0) { collidedMesh = null; }
  13334. //TODO move this to the collision coordinator!
  13335. if (_this.getScene().workerCollisions)
  13336. newPosition.multiplyInPlace(_this._collider.radius);
  13337. var updatePosition = function (newPos) {
  13338. _this._newPosition.copyFrom(newPos);
  13339. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13340. var oldPosition = _this.position.clone();
  13341. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13342. _this.position.addInPlace(_this._diffPosition);
  13343. if (_this.onCollide && collidedMesh) {
  13344. _this.onCollide(collidedMesh);
  13345. }
  13346. }
  13347. };
  13348. updatePosition(newPosition);
  13349. };
  13350. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13351. this.inputs.addKeyboard().addMouse();
  13352. }
  13353. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13354. //-- begin properties for backward compatibility for inputs
  13355. get: function () {
  13356. var mouse = this.inputs.attached["mouse"];
  13357. if (mouse)
  13358. return mouse.angularSensibility;
  13359. },
  13360. set: function (value) {
  13361. var mouse = this.inputs.attached["mouse"];
  13362. if (mouse)
  13363. mouse.angularSensibility = value;
  13364. },
  13365. enumerable: true,
  13366. configurable: true
  13367. });
  13368. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13369. get: function () {
  13370. var keyboard = this.inputs.attached["keyboard"];
  13371. if (keyboard)
  13372. return keyboard.keysUp;
  13373. },
  13374. set: function (value) {
  13375. var keyboard = this.inputs.attached["keyboard"];
  13376. if (keyboard)
  13377. keyboard.keysUp = value;
  13378. },
  13379. enumerable: true,
  13380. configurable: true
  13381. });
  13382. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13383. get: function () {
  13384. var keyboard = this.inputs.attached["keyboard"];
  13385. if (keyboard)
  13386. return keyboard.keysDown;
  13387. },
  13388. set: function (value) {
  13389. var keyboard = this.inputs.attached["keyboard"];
  13390. if (keyboard)
  13391. keyboard.keysDown = value;
  13392. },
  13393. enumerable: true,
  13394. configurable: true
  13395. });
  13396. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13397. get: function () {
  13398. var keyboard = this.inputs.attached["keyboard"];
  13399. if (keyboard)
  13400. return keyboard.keysLeft;
  13401. },
  13402. set: function (value) {
  13403. var keyboard = this.inputs.attached["keyboard"];
  13404. if (keyboard)
  13405. keyboard.keysLeft = value;
  13406. },
  13407. enumerable: true,
  13408. configurable: true
  13409. });
  13410. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13411. get: function () {
  13412. var keyboard = this.inputs.attached["keyboard"];
  13413. if (keyboard)
  13414. return keyboard.keysRight;
  13415. },
  13416. set: function (value) {
  13417. var keyboard = this.inputs.attached["keyboard"];
  13418. if (keyboard)
  13419. keyboard.keysRight = value;
  13420. },
  13421. enumerable: true,
  13422. configurable: true
  13423. });
  13424. // Controls
  13425. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13426. this.inputs.attachElement(element, noPreventDefault);
  13427. };
  13428. FreeCamera.prototype.detachControl = function (element) {
  13429. this.inputs.detachElement(element);
  13430. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13431. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13432. };
  13433. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13434. var globalPosition;
  13435. if (this.parent) {
  13436. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13437. }
  13438. else {
  13439. globalPosition = this.position;
  13440. }
  13441. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13442. this._collider.radius = this.ellipsoid;
  13443. //no need for clone, as long as gravity is not on.
  13444. var actualVelocity = velocity;
  13445. //add gravity to the velocity to prevent the dual-collision checking
  13446. if (this.applyGravity) {
  13447. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13448. actualVelocity = velocity.add(this.getScene().gravity);
  13449. }
  13450. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13451. };
  13452. FreeCamera.prototype._checkInputs = function () {
  13453. if (!this._localDirection) {
  13454. this._localDirection = BABYLON.Vector3.Zero();
  13455. this._transformedDirection = BABYLON.Vector3.Zero();
  13456. }
  13457. this.inputs.checkInputs();
  13458. _super.prototype._checkInputs.call(this);
  13459. };
  13460. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13461. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13462. };
  13463. FreeCamera.prototype._updatePosition = function () {
  13464. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13465. this._collideWithWorld(this.cameraDirection);
  13466. }
  13467. else {
  13468. this.position.addInPlace(this.cameraDirection);
  13469. }
  13470. };
  13471. FreeCamera.prototype.dispose = function () {
  13472. this.inputs.clear();
  13473. _super.prototype.dispose.call(this);
  13474. };
  13475. FreeCamera.prototype.getTypeName = function () {
  13476. return "FreeCamera";
  13477. };
  13478. __decorate([
  13479. BABYLON.serializeAsVector3()
  13480. ], FreeCamera.prototype, "ellipsoid", void 0);
  13481. __decorate([
  13482. BABYLON.serialize()
  13483. ], FreeCamera.prototype, "checkCollisions", void 0);
  13484. __decorate([
  13485. BABYLON.serialize()
  13486. ], FreeCamera.prototype, "applyGravity", void 0);
  13487. return FreeCamera;
  13488. })(BABYLON.TargetCamera);
  13489. BABYLON.FreeCamera = FreeCamera;
  13490. })(BABYLON || (BABYLON = {}));
  13491. var BABYLON;
  13492. (function (BABYLON) {
  13493. var FreeCameraInputsManager = (function (_super) {
  13494. __extends(FreeCameraInputsManager, _super);
  13495. function FreeCameraInputsManager(camera) {
  13496. _super.call(this, camera);
  13497. }
  13498. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13499. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13500. return this;
  13501. };
  13502. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13503. if (touchEnabled === void 0) { touchEnabled = true; }
  13504. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13505. return this;
  13506. };
  13507. FreeCameraInputsManager.prototype.addGamepad = function () {
  13508. this.add(new BABYLON.FreeCameraGamepadInput());
  13509. return this;
  13510. };
  13511. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13512. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13513. return this;
  13514. };
  13515. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13516. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13517. return this;
  13518. };
  13519. FreeCameraInputsManager.prototype.addTouch = function () {
  13520. this.add(new BABYLON.FreeCameraTouchInput());
  13521. return this;
  13522. };
  13523. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13524. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13525. return this;
  13526. };
  13527. return FreeCameraInputsManager;
  13528. })(BABYLON.CameraInputsManager);
  13529. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13530. })(BABYLON || (BABYLON = {}));
  13531. var BABYLON;
  13532. (function (BABYLON) {
  13533. var FollowCamera = (function (_super) {
  13534. __extends(FollowCamera, _super);
  13535. function FollowCamera(name, position, scene, target) {
  13536. _super.call(this, name, position, scene);
  13537. this.radius = 12;
  13538. this.rotationOffset = 0;
  13539. this.heightOffset = 4;
  13540. this.cameraAcceleration = 0.05;
  13541. this.maxCameraSpeed = 20;
  13542. this.target = target;
  13543. }
  13544. FollowCamera.prototype.getRadians = function (degrees) {
  13545. return degrees * Math.PI / 180;
  13546. };
  13547. FollowCamera.prototype.follow = function (cameraTarget) {
  13548. if (!cameraTarget)
  13549. return;
  13550. var yRotation;
  13551. if (cameraTarget.rotationQuaternion) {
  13552. var rotMatrix = new BABYLON.Matrix();
  13553. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13554. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13555. }
  13556. else {
  13557. yRotation = cameraTarget.rotation.y;
  13558. }
  13559. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13560. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13561. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13562. var dx = targetX - this.position.x;
  13563. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13564. var dz = (targetZ) - this.position.z;
  13565. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13566. var vy = dy * this.cameraAcceleration;
  13567. var vz = dz * this.cameraAcceleration * 2;
  13568. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13569. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13570. }
  13571. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13572. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13573. }
  13574. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13575. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13576. }
  13577. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13578. this.setTarget(cameraTarget.position);
  13579. };
  13580. FollowCamera.prototype._checkInputs = function () {
  13581. _super.prototype._checkInputs.call(this);
  13582. this.follow(this.target);
  13583. };
  13584. FollowCamera.prototype.getTypeName = function () {
  13585. return "FollowCamera";
  13586. };
  13587. __decorate([
  13588. BABYLON.serialize()
  13589. ], FollowCamera.prototype, "radius", void 0);
  13590. __decorate([
  13591. BABYLON.serialize()
  13592. ], FollowCamera.prototype, "rotationOffset", void 0);
  13593. __decorate([
  13594. BABYLON.serialize()
  13595. ], FollowCamera.prototype, "heightOffset", void 0);
  13596. __decorate([
  13597. BABYLON.serialize()
  13598. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13599. __decorate([
  13600. BABYLON.serialize()
  13601. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13602. __decorate([
  13603. BABYLON.serializeAsMeshReference("lockedTargetId")
  13604. ], FollowCamera.prototype, "target", void 0);
  13605. return FollowCamera;
  13606. })(BABYLON.TargetCamera);
  13607. BABYLON.FollowCamera = FollowCamera;
  13608. var ArcFollowCamera = (function (_super) {
  13609. __extends(ArcFollowCamera, _super);
  13610. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13611. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13612. this.alpha = alpha;
  13613. this.beta = beta;
  13614. this.radius = radius;
  13615. this.target = target;
  13616. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13617. this.follow();
  13618. }
  13619. ArcFollowCamera.prototype.follow = function () {
  13620. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13621. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13622. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13623. this.position = this.target.position.add(this._cartesianCoordinates);
  13624. this.setTarget(this.target.position);
  13625. };
  13626. ArcFollowCamera.prototype._checkInputs = function () {
  13627. _super.prototype._checkInputs.call(this);
  13628. this.follow();
  13629. };
  13630. ArcFollowCamera.prototype.getTypeName = function () {
  13631. return "ArcFollowCamera";
  13632. };
  13633. return ArcFollowCamera;
  13634. })(BABYLON.TargetCamera);
  13635. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13636. })(BABYLON || (BABYLON = {}));
  13637. var BABYLON;
  13638. (function (BABYLON) {
  13639. // We're mainly based on the logic defined into the FreeCamera code
  13640. var TouchCamera = (function (_super) {
  13641. __extends(TouchCamera, _super);
  13642. //-- end properties for backward compatibility for inputs
  13643. function TouchCamera(name, position, scene) {
  13644. _super.call(this, name, position, scene);
  13645. this.inputs.addTouch();
  13646. this._setupInputs();
  13647. }
  13648. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13649. //-- Begin properties for backward compatibility for inputs
  13650. get: function () {
  13651. var touch = this.inputs.attached["touch"];
  13652. if (touch)
  13653. return touch.touchAngularSensibility;
  13654. },
  13655. set: function (value) {
  13656. var touch = this.inputs.attached["touch"];
  13657. if (touch)
  13658. touch.touchAngularSensibility = value;
  13659. },
  13660. enumerable: true,
  13661. configurable: true
  13662. });
  13663. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13664. get: function () {
  13665. var touch = this.inputs.attached["touch"];
  13666. if (touch)
  13667. return touch.touchMoveSensibility;
  13668. },
  13669. set: function (value) {
  13670. var touch = this.inputs.attached["touch"];
  13671. if (touch)
  13672. touch.touchMoveSensibility = value;
  13673. },
  13674. enumerable: true,
  13675. configurable: true
  13676. });
  13677. TouchCamera.prototype.getTypeName = function () {
  13678. return "TouchCamera";
  13679. };
  13680. TouchCamera.prototype._setupInputs = function () {
  13681. var mouse = this.inputs.attached["mouse"];
  13682. if (mouse) {
  13683. mouse.touchEnabled = false;
  13684. }
  13685. };
  13686. return TouchCamera;
  13687. })(BABYLON.FreeCamera);
  13688. BABYLON.TouchCamera = TouchCamera;
  13689. })(BABYLON || (BABYLON = {}));
  13690. var BABYLON;
  13691. (function (BABYLON) {
  13692. var ArcRotateCamera = (function (_super) {
  13693. __extends(ArcRotateCamera, _super);
  13694. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13695. var _this = this;
  13696. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13697. this.inertialAlphaOffset = 0;
  13698. this.inertialBetaOffset = 0;
  13699. this.inertialRadiusOffset = 0;
  13700. this.lowerAlphaLimit = null;
  13701. this.upperAlphaLimit = null;
  13702. this.lowerBetaLimit = 0.01;
  13703. this.upperBetaLimit = Math.PI;
  13704. this.lowerRadiusLimit = null;
  13705. this.upperRadiusLimit = null;
  13706. this.inertialPanningX = 0;
  13707. this.inertialPanningY = 0;
  13708. //-- end properties for backward compatibility for inputs
  13709. this.zoomOnFactor = 1;
  13710. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13711. this.allowUpsideDown = true;
  13712. this._viewMatrix = new BABYLON.Matrix();
  13713. // Panning
  13714. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13715. this.checkCollisions = false;
  13716. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13717. this._collider = new BABYLON.Collider();
  13718. this._previousPosition = BABYLON.Vector3.Zero();
  13719. this._collisionVelocity = BABYLON.Vector3.Zero();
  13720. this._newPosition = BABYLON.Vector3.Zero();
  13721. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13722. if (collidedMesh === void 0) { collidedMesh = null; }
  13723. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13724. newPosition.multiplyInPlace(_this._collider.radius);
  13725. }
  13726. if (!collidedMesh) {
  13727. _this._previousPosition.copyFrom(_this.position);
  13728. }
  13729. else {
  13730. _this.setPosition(newPosition);
  13731. if (_this.onCollide) {
  13732. _this.onCollide(collidedMesh);
  13733. }
  13734. }
  13735. // Recompute because of constraints
  13736. var cosa = Math.cos(_this.alpha);
  13737. var sina = Math.sin(_this.alpha);
  13738. var cosb = Math.cos(_this.beta);
  13739. var sinb = Math.sin(_this.beta);
  13740. if (sinb === 0) {
  13741. sinb = 0.0001;
  13742. }
  13743. var target = _this._getTargetPosition();
  13744. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13745. _this.position.copyFrom(_this._newPosition);
  13746. var up = _this.upVector;
  13747. if (_this.allowUpsideDown && _this.beta < 0) {
  13748. up = up.clone();
  13749. up = up.negate();
  13750. }
  13751. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13752. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13753. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13754. _this._collisionTriggered = false;
  13755. };
  13756. if (!target) {
  13757. this.target = BABYLON.Vector3.Zero();
  13758. }
  13759. else {
  13760. this.target = target;
  13761. }
  13762. this.alpha = alpha;
  13763. this.beta = beta;
  13764. this.radius = radius;
  13765. this.getViewMatrix();
  13766. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13767. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13768. }
  13769. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13770. //-- begin properties for backward compatibility for inputs
  13771. get: function () {
  13772. var pointers = this.inputs.attached["pointers"];
  13773. if (pointers)
  13774. return pointers.angularSensibilityX;
  13775. },
  13776. set: function (value) {
  13777. var pointers = this.inputs.attached["pointers"];
  13778. if (pointers) {
  13779. pointers.angularSensibilityX = value;
  13780. }
  13781. },
  13782. enumerable: true,
  13783. configurable: true
  13784. });
  13785. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13786. get: function () {
  13787. var pointers = this.inputs.attached["pointers"];
  13788. if (pointers)
  13789. return pointers.angularSensibilityY;
  13790. },
  13791. set: function (value) {
  13792. var pointers = this.inputs.attached["pointers"];
  13793. if (pointers) {
  13794. pointers.angularSensibilityY = value;
  13795. }
  13796. },
  13797. enumerable: true,
  13798. configurable: true
  13799. });
  13800. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13801. get: function () {
  13802. var pointers = this.inputs.attached["pointers"];
  13803. if (pointers)
  13804. return pointers.pinchPrecision;
  13805. },
  13806. set: function (value) {
  13807. var pointers = this.inputs.attached["pointers"];
  13808. if (pointers) {
  13809. pointers.pinchPrecision = value;
  13810. }
  13811. },
  13812. enumerable: true,
  13813. configurable: true
  13814. });
  13815. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13816. get: function () {
  13817. var pointers = this.inputs.attached["pointers"];
  13818. if (pointers)
  13819. return pointers.panningSensibility;
  13820. },
  13821. set: function (value) {
  13822. var pointers = this.inputs.attached["pointers"];
  13823. if (pointers) {
  13824. pointers.panningSensibility = value;
  13825. }
  13826. },
  13827. enumerable: true,
  13828. configurable: true
  13829. });
  13830. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13831. get: function () {
  13832. var keyboard = this.inputs.attached["keyboard"];
  13833. if (keyboard)
  13834. return keyboard.keysUp;
  13835. },
  13836. set: function (value) {
  13837. var keyboard = this.inputs.attached["keyboard"];
  13838. if (keyboard)
  13839. keyboard.keysUp = value;
  13840. },
  13841. enumerable: true,
  13842. configurable: true
  13843. });
  13844. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13845. get: function () {
  13846. var keyboard = this.inputs.attached["keyboard"];
  13847. if (keyboard)
  13848. return keyboard.keysDown;
  13849. },
  13850. set: function (value) {
  13851. var keyboard = this.inputs.attached["keyboard"];
  13852. if (keyboard)
  13853. keyboard.keysDown = value;
  13854. },
  13855. enumerable: true,
  13856. configurable: true
  13857. });
  13858. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13859. get: function () {
  13860. var keyboard = this.inputs.attached["keyboard"];
  13861. if (keyboard)
  13862. return keyboard.keysLeft;
  13863. },
  13864. set: function (value) {
  13865. var keyboard = this.inputs.attached["keyboard"];
  13866. if (keyboard)
  13867. keyboard.keysLeft = value;
  13868. },
  13869. enumerable: true,
  13870. configurable: true
  13871. });
  13872. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13873. get: function () {
  13874. var keyboard = this.inputs.attached["keyboard"];
  13875. if (keyboard)
  13876. return keyboard.keysRight;
  13877. },
  13878. set: function (value) {
  13879. var keyboard = this.inputs.attached["keyboard"];
  13880. if (keyboard)
  13881. keyboard.keysRight = value;
  13882. },
  13883. enumerable: true,
  13884. configurable: true
  13885. });
  13886. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13887. get: function () {
  13888. var mousewheel = this.inputs.attached["mousewheel"];
  13889. if (mousewheel)
  13890. return mousewheel.wheelPrecision;
  13891. },
  13892. set: function (value) {
  13893. var mousewheel = this.inputs.attached["mousewheel"];
  13894. if (mousewheel)
  13895. mousewheel.wheelPrecision = value;
  13896. },
  13897. enumerable: true,
  13898. configurable: true
  13899. });
  13900. // Cache
  13901. ArcRotateCamera.prototype._initCache = function () {
  13902. _super.prototype._initCache.call(this);
  13903. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13904. this._cache.alpha = undefined;
  13905. this._cache.beta = undefined;
  13906. this._cache.radius = undefined;
  13907. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13908. };
  13909. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13910. if (!ignoreParentClass) {
  13911. _super.prototype._updateCache.call(this);
  13912. }
  13913. this._cache.target.copyFrom(this._getTargetPosition());
  13914. this._cache.alpha = this.alpha;
  13915. this._cache.beta = this.beta;
  13916. this._cache.radius = this.radius;
  13917. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13918. };
  13919. ArcRotateCamera.prototype._getTargetPosition = function () {
  13920. if (this.target.getAbsolutePosition) {
  13921. return this.target.getAbsolutePosition();
  13922. }
  13923. return this.target;
  13924. };
  13925. // Synchronized
  13926. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13927. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13928. return false;
  13929. return this._cache.target.equals(this.target)
  13930. && this._cache.alpha === this.alpha
  13931. && this._cache.beta === this.beta
  13932. && this._cache.radius === this.radius
  13933. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13934. };
  13935. // Methods
  13936. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13937. var _this = this;
  13938. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13939. this._useCtrlForPanning = useCtrlForPanning;
  13940. this.inputs.attachElement(element, noPreventDefault);
  13941. this._reset = function () {
  13942. _this.inertialAlphaOffset = 0;
  13943. _this.inertialBetaOffset = 0;
  13944. _this.inertialRadiusOffset = 0;
  13945. };
  13946. };
  13947. ArcRotateCamera.prototype.detachControl = function (element) {
  13948. this.inputs.detachElement(element);
  13949. if (this._reset) {
  13950. this._reset();
  13951. }
  13952. };
  13953. ArcRotateCamera.prototype._checkInputs = function () {
  13954. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13955. if (this._collisionTriggered) {
  13956. return;
  13957. }
  13958. this.inputs.checkInputs();
  13959. // Inertia
  13960. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13961. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13962. this.beta += this.inertialBetaOffset;
  13963. this.radius -= this.inertialRadiusOffset;
  13964. this.inertialAlphaOffset *= this.inertia;
  13965. this.inertialBetaOffset *= this.inertia;
  13966. this.inertialRadiusOffset *= this.inertia;
  13967. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13968. this.inertialAlphaOffset = 0;
  13969. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13970. this.inertialBetaOffset = 0;
  13971. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13972. this.inertialRadiusOffset = 0;
  13973. }
  13974. // Panning inertia
  13975. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13976. if (!this._localDirection) {
  13977. this._localDirection = BABYLON.Vector3.Zero();
  13978. this._transformedDirection = BABYLON.Vector3.Zero();
  13979. }
  13980. this.inertialPanningX *= this.inertia;
  13981. this.inertialPanningY *= this.inertia;
  13982. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13983. this.inertialPanningX = 0;
  13984. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13985. this.inertialPanningY = 0;
  13986. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13987. this._localDirection.multiplyInPlace(this.panningAxis);
  13988. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13989. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13990. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13991. if (!this.panningAxis.y) {
  13992. this._transformedDirection.y = 0;
  13993. }
  13994. if (!this.target.getAbsolutePosition) {
  13995. this.target.addInPlace(this._transformedDirection);
  13996. }
  13997. }
  13998. // Limits
  13999. this._checkLimits();
  14000. _super.prototype._checkInputs.call(this);
  14001. };
  14002. ArcRotateCamera.prototype._checkLimits = function () {
  14003. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14004. if (this.allowUpsideDown && this.beta > Math.PI) {
  14005. this.beta = this.beta - (2 * Math.PI);
  14006. }
  14007. }
  14008. else {
  14009. if (this.beta < this.lowerBetaLimit) {
  14010. this.beta = this.lowerBetaLimit;
  14011. }
  14012. }
  14013. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14014. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14015. this.beta = this.beta + (2 * Math.PI);
  14016. }
  14017. }
  14018. else {
  14019. if (this.beta > this.upperBetaLimit) {
  14020. this.beta = this.upperBetaLimit;
  14021. }
  14022. }
  14023. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14024. this.alpha = this.lowerAlphaLimit;
  14025. }
  14026. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14027. this.alpha = this.upperAlphaLimit;
  14028. }
  14029. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14030. this.radius = this.lowerRadiusLimit;
  14031. }
  14032. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14033. this.radius = this.upperRadiusLimit;
  14034. }
  14035. };
  14036. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14037. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14038. this.radius = radiusv3.length();
  14039. // Alpha
  14040. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14041. if (radiusv3.z < 0) {
  14042. this.alpha = 2 * Math.PI - this.alpha;
  14043. }
  14044. // Beta
  14045. this.beta = Math.acos(radiusv3.y / this.radius);
  14046. this._checkLimits();
  14047. };
  14048. ArcRotateCamera.prototype.setPosition = function (position) {
  14049. if (this.position.equals(position)) {
  14050. return;
  14051. }
  14052. this.position = position;
  14053. this.rebuildAnglesAndRadius();
  14054. };
  14055. ArcRotateCamera.prototype.setTarget = function (target) {
  14056. if (this._getTargetPosition().equals(target)) {
  14057. return;
  14058. }
  14059. this.target = target;
  14060. this.rebuildAnglesAndRadius();
  14061. };
  14062. ArcRotateCamera.prototype._getViewMatrix = function () {
  14063. // Compute
  14064. var cosa = Math.cos(this.alpha);
  14065. var sina = Math.sin(this.alpha);
  14066. var cosb = Math.cos(this.beta);
  14067. var sinb = Math.sin(this.beta);
  14068. if (sinb === 0) {
  14069. sinb = 0.0001;
  14070. }
  14071. var target = this._getTargetPosition();
  14072. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14073. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14074. this._collider.radius = this.collisionRadius;
  14075. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14076. this._collisionTriggered = true;
  14077. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14078. }
  14079. else {
  14080. this.position.copyFrom(this._newPosition);
  14081. var up = this.upVector;
  14082. if (this.allowUpsideDown && this.beta < 0) {
  14083. up = up.clone();
  14084. up = up.negate();
  14085. }
  14086. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14087. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14088. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14089. }
  14090. return this._viewMatrix;
  14091. };
  14092. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14093. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14094. meshes = meshes || this.getScene().meshes;
  14095. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14096. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14097. this.radius = distance * this.zoomOnFactor;
  14098. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14099. };
  14100. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14101. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14102. var meshesOrMinMaxVector;
  14103. var distance;
  14104. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14105. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14106. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14107. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14108. }
  14109. else {
  14110. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14111. distance = meshesOrMinMaxVectorAndDistance.distance;
  14112. }
  14113. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14114. if (!doNotUpdateMaxZ) {
  14115. this.maxZ = distance * 2;
  14116. }
  14117. };
  14118. /**
  14119. * @override
  14120. * Override Camera.createRigCamera
  14121. */
  14122. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14123. var alphaShift;
  14124. switch (this.cameraRigMode) {
  14125. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14126. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14127. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14128. case BABYLON.Camera.RIG_MODE_VR:
  14129. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14130. break;
  14131. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14132. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14133. break;
  14134. }
  14135. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14136. rigCam._cameraRigParams = {};
  14137. return rigCam;
  14138. };
  14139. /**
  14140. * @override
  14141. * Override Camera._updateRigCameras
  14142. */
  14143. ArcRotateCamera.prototype._updateRigCameras = function () {
  14144. var camLeft = this._rigCameras[0];
  14145. var camRight = this._rigCameras[1];
  14146. camLeft.beta = camRight.beta = this.beta;
  14147. camLeft.radius = camRight.radius = this.radius;
  14148. switch (this.cameraRigMode) {
  14149. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14150. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14151. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14152. case BABYLON.Camera.RIG_MODE_VR:
  14153. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14154. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14155. break;
  14156. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14157. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14158. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14159. break;
  14160. }
  14161. _super.prototype._updateRigCameras.call(this);
  14162. };
  14163. ArcRotateCamera.prototype.dispose = function () {
  14164. this.inputs.clear();
  14165. _super.prototype.dispose.call(this);
  14166. };
  14167. ArcRotateCamera.prototype.getTypeName = function () {
  14168. return "ArcRotateCamera";
  14169. };
  14170. __decorate([
  14171. BABYLON.serialize()
  14172. ], ArcRotateCamera.prototype, "alpha", void 0);
  14173. __decorate([
  14174. BABYLON.serialize()
  14175. ], ArcRotateCamera.prototype, "beta", void 0);
  14176. __decorate([
  14177. BABYLON.serialize()
  14178. ], ArcRotateCamera.prototype, "radius", void 0);
  14179. __decorate([
  14180. BABYLON.serializeAsVector3()
  14181. ], ArcRotateCamera.prototype, "target", void 0);
  14182. __decorate([
  14183. BABYLON.serialize()
  14184. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14185. __decorate([
  14186. BABYLON.serialize()
  14187. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14188. __decorate([
  14189. BABYLON.serialize()
  14190. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14191. __decorate([
  14192. BABYLON.serialize()
  14193. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14194. __decorate([
  14195. BABYLON.serialize()
  14196. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14197. __decorate([
  14198. BABYLON.serialize()
  14199. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14200. __decorate([
  14201. BABYLON.serialize()
  14202. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14203. __decorate([
  14204. BABYLON.serialize()
  14205. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14206. __decorate([
  14207. BABYLON.serialize()
  14208. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14209. __decorate([
  14210. BABYLON.serialize()
  14211. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14212. __decorate([
  14213. BABYLON.serialize()
  14214. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14215. __decorate([
  14216. BABYLON.serialize()
  14217. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14218. __decorate([
  14219. BABYLON.serialize()
  14220. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14221. return ArcRotateCamera;
  14222. })(BABYLON.TargetCamera);
  14223. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14224. })(BABYLON || (BABYLON = {}));
  14225. var BABYLON;
  14226. (function (BABYLON) {
  14227. var ArcRotateCameraInputsManager = (function (_super) {
  14228. __extends(ArcRotateCameraInputsManager, _super);
  14229. function ArcRotateCameraInputsManager(camera) {
  14230. _super.call(this, camera);
  14231. }
  14232. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14233. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14234. return this;
  14235. };
  14236. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14237. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14238. return this;
  14239. };
  14240. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14241. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14242. return this;
  14243. };
  14244. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14245. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14246. return this;
  14247. };
  14248. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14249. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14250. return this;
  14251. };
  14252. return ArcRotateCameraInputsManager;
  14253. })(BABYLON.CameraInputsManager);
  14254. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14255. })(BABYLON || (BABYLON = {}));
  14256. var BABYLON;
  14257. (function (BABYLON) {
  14258. var RenderingManager = (function () {
  14259. function RenderingManager(scene) {
  14260. this._renderingGroups = new Array();
  14261. this._scene = scene;
  14262. }
  14263. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14264. if (this._scene._activeParticleSystems.length === 0) {
  14265. return;
  14266. }
  14267. // Particles
  14268. var activeCamera = this._scene.activeCamera;
  14269. var beforeParticlesDate = BABYLON.Tools.Now;
  14270. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14271. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14272. if (particleSystem.renderingGroupId !== index) {
  14273. continue;
  14274. }
  14275. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14276. continue;
  14277. }
  14278. this._clearDepthBuffer();
  14279. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14280. this._scene._activeParticles += particleSystem.render();
  14281. }
  14282. }
  14283. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  14284. };
  14285. RenderingManager.prototype._renderSprites = function (index) {
  14286. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14287. return;
  14288. }
  14289. // Sprites
  14290. var activeCamera = this._scene.activeCamera;
  14291. var beforeSpritessDate = BABYLON.Tools.Now;
  14292. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14293. var spriteManager = this._scene.spriteManagers[id];
  14294. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14295. this._clearDepthBuffer();
  14296. spriteManager.render();
  14297. }
  14298. }
  14299. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  14300. };
  14301. RenderingManager.prototype._clearDepthBuffer = function () {
  14302. if (this._depthBufferAlreadyCleaned) {
  14303. return;
  14304. }
  14305. this._scene.getEngine().clear(0, false, true);
  14306. this._depthBufferAlreadyCleaned = true;
  14307. };
  14308. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14309. if (this._currentRenderSprites) {
  14310. this._renderSprites(this._currentIndex);
  14311. }
  14312. if (this._currentRenderParticles) {
  14313. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14314. }
  14315. };
  14316. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14317. this._currentActiveMeshes = activeMeshes;
  14318. this._currentRenderParticles = renderParticles;
  14319. this._currentRenderSprites = renderSprites;
  14320. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14321. this._depthBufferAlreadyCleaned = index == 0;
  14322. var renderingGroup = this._renderingGroups[index];
  14323. var needToStepBack = false;
  14324. this._currentIndex = index;
  14325. if (renderingGroup) {
  14326. this._clearDepthBuffer();
  14327. if (!renderingGroup.onBeforeTransparentRendering) {
  14328. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14329. }
  14330. if (!renderingGroup.render(customRenderFunction)) {
  14331. this._renderingGroups.splice(index, 1);
  14332. needToStepBack = true;
  14333. this._renderSpritesAndParticles();
  14334. }
  14335. }
  14336. else {
  14337. this._renderSpritesAndParticles();
  14338. }
  14339. if (needToStepBack) {
  14340. index--;
  14341. }
  14342. }
  14343. };
  14344. RenderingManager.prototype.reset = function () {
  14345. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14346. if (renderingGroup) {
  14347. renderingGroup.prepare();
  14348. }
  14349. });
  14350. };
  14351. RenderingManager.prototype.dispatch = function (subMesh) {
  14352. var mesh = subMesh.getMesh();
  14353. var renderingGroupId = mesh.renderingGroupId || 0;
  14354. if (!this._renderingGroups[renderingGroupId]) {
  14355. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14356. }
  14357. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14358. };
  14359. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14360. return RenderingManager;
  14361. })();
  14362. BABYLON.RenderingManager = RenderingManager;
  14363. })(BABYLON || (BABYLON = {}));
  14364. var BABYLON;
  14365. (function (BABYLON) {
  14366. var RenderingGroup = (function () {
  14367. function RenderingGroup(index, scene) {
  14368. this.index = index;
  14369. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14370. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14371. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14372. this._scene = scene;
  14373. }
  14374. RenderingGroup.prototype.render = function (customRenderFunction) {
  14375. if (customRenderFunction) {
  14376. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14377. return true;
  14378. }
  14379. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14380. if (this.onBeforeTransparentRendering) {
  14381. this.onBeforeTransparentRendering();
  14382. }
  14383. return false;
  14384. }
  14385. var engine = this._scene.getEngine();
  14386. // Opaque
  14387. var subIndex;
  14388. var submesh;
  14389. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14390. submesh = this._opaqueSubMeshes.data[subIndex];
  14391. submesh.render(false);
  14392. }
  14393. // Alpha test
  14394. engine.setAlphaTesting(true);
  14395. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14396. submesh = this._alphaTestSubMeshes.data[subIndex];
  14397. submesh.render(false);
  14398. }
  14399. engine.setAlphaTesting(false);
  14400. if (this.onBeforeTransparentRendering) {
  14401. this.onBeforeTransparentRendering();
  14402. }
  14403. // Transparent
  14404. if (this._transparentSubMeshes.length) {
  14405. // Sorting
  14406. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14407. submesh = this._transparentSubMeshes.data[subIndex];
  14408. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14409. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14410. }
  14411. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14412. sortedArray.sort(function (a, b) {
  14413. // Alpha index first
  14414. if (a._alphaIndex > b._alphaIndex) {
  14415. return 1;
  14416. }
  14417. if (a._alphaIndex < b._alphaIndex) {
  14418. return -1;
  14419. }
  14420. // Then distance to camera
  14421. if (a._distanceToCamera < b._distanceToCamera) {
  14422. return 1;
  14423. }
  14424. if (a._distanceToCamera > b._distanceToCamera) {
  14425. return -1;
  14426. }
  14427. return 0;
  14428. });
  14429. // Rendering
  14430. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14431. submesh = sortedArray[subIndex];
  14432. submesh.render(true);
  14433. }
  14434. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14435. }
  14436. return true;
  14437. };
  14438. RenderingGroup.prototype.prepare = function () {
  14439. this._opaqueSubMeshes.reset();
  14440. this._transparentSubMeshes.reset();
  14441. this._alphaTestSubMeshes.reset();
  14442. };
  14443. RenderingGroup.prototype.dispatch = function (subMesh) {
  14444. var material = subMesh.getMaterial();
  14445. var mesh = subMesh.getMesh();
  14446. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14447. this._transparentSubMeshes.push(subMesh);
  14448. }
  14449. else if (material.needAlphaTesting()) {
  14450. this._alphaTestSubMeshes.push(subMesh);
  14451. }
  14452. else {
  14453. this._opaqueSubMeshes.push(subMesh); // Opaque
  14454. }
  14455. };
  14456. return RenderingGroup;
  14457. })();
  14458. BABYLON.RenderingGroup = RenderingGroup;
  14459. })(BABYLON || (BABYLON = {}));
  14460. var BABYLON;
  14461. (function (BABYLON) {
  14462. var PointerEventTypes = (function () {
  14463. function PointerEventTypes() {
  14464. }
  14465. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14466. get: function () {
  14467. return PointerEventTypes._POINTERDOWN;
  14468. },
  14469. enumerable: true,
  14470. configurable: true
  14471. });
  14472. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14473. get: function () {
  14474. return PointerEventTypes._POINTERUP;
  14475. },
  14476. enumerable: true,
  14477. configurable: true
  14478. });
  14479. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14480. get: function () {
  14481. return PointerEventTypes._POINTERMOVE;
  14482. },
  14483. enumerable: true,
  14484. configurable: true
  14485. });
  14486. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14487. get: function () {
  14488. return PointerEventTypes._POINTERWHEEL;
  14489. },
  14490. enumerable: true,
  14491. configurable: true
  14492. });
  14493. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14494. get: function () {
  14495. return PointerEventTypes._POINTERPICK;
  14496. },
  14497. enumerable: true,
  14498. configurable: true
  14499. });
  14500. PointerEventTypes._POINTERDOWN = 0x01;
  14501. PointerEventTypes._POINTERUP = 0x02;
  14502. PointerEventTypes._POINTERMOVE = 0x04;
  14503. PointerEventTypes._POINTERWHEEL = 0x08;
  14504. PointerEventTypes._POINTERPICK = 0x10;
  14505. return PointerEventTypes;
  14506. })();
  14507. BABYLON.PointerEventTypes = PointerEventTypes;
  14508. /**
  14509. * This class is used to store pointer related info for the onPrePointerObservable event.
  14510. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14511. */
  14512. var PointerInfoPre = (function () {
  14513. function PointerInfoPre(type, event, localX, localY) {
  14514. this.type = type;
  14515. this.event = event;
  14516. this.skipOnPointerObservable = false;
  14517. this.localPosition = new BABYLON.Vector2(localX, localY);
  14518. }
  14519. return PointerInfoPre;
  14520. })();
  14521. BABYLON.PointerInfoPre = PointerInfoPre;
  14522. /**
  14523. * This type contains all the data related to a pointer event in Babylon.js.
  14524. * 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.
  14525. */
  14526. var PointerInfo = (function () {
  14527. function PointerInfo(type, event, pickInfo) {
  14528. this.type = type;
  14529. this.event = event;
  14530. this.pickInfo = pickInfo;
  14531. }
  14532. return PointerInfo;
  14533. })();
  14534. BABYLON.PointerInfo = PointerInfo;
  14535. /**
  14536. * Represents a scene to be rendered by the engine.
  14537. * @see http://doc.babylonjs.com/page.php?p=21911
  14538. */
  14539. var Scene = (function () {
  14540. /**
  14541. * @constructor
  14542. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14543. */
  14544. function Scene(engine) {
  14545. // Members
  14546. this.autoClear = true;
  14547. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14548. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14549. this.forceWireframe = false;
  14550. this.forcePointsCloud = false;
  14551. this.forceShowBoundingBoxes = false;
  14552. this.animationsEnabled = true;
  14553. this.constantlyUpdateMeshUnderPointer = false;
  14554. // Events
  14555. /**
  14556. * An event triggered when the scene is disposed.
  14557. * @type {BABYLON.Observable}
  14558. */
  14559. this.onDisposeObservable = new BABYLON.Observable();
  14560. /**
  14561. * An event triggered before rendering the scene
  14562. * @type {BABYLON.Observable}
  14563. */
  14564. this.onBeforeRenderObservable = new BABYLON.Observable();
  14565. /**
  14566. * An event triggered after rendering the scene
  14567. * @type {BABYLON.Observable}
  14568. */
  14569. this.onAfterRenderObservable = new BABYLON.Observable();
  14570. /**
  14571. * An event triggered when the scene is ready
  14572. * @type {BABYLON.Observable}
  14573. */
  14574. this.onReadyObservable = new BABYLON.Observable();
  14575. /**
  14576. * An event triggered before rendering a camera
  14577. * @type {BABYLON.Observable}
  14578. */
  14579. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14580. /**
  14581. * An event triggered after rendering a camera
  14582. * @type {BABYLON.Observable}
  14583. */
  14584. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14585. /**
  14586. * An event triggered when a camera is created
  14587. * @type {BABYLON.Observable}
  14588. */
  14589. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14590. /**
  14591. * An event triggered when a camera is removed
  14592. * @type {BABYLON.Observable}
  14593. */
  14594. this.onCameraRemovedObservable = new BABYLON.Observable();
  14595. /**
  14596. * An event triggered when a light is created
  14597. * @type {BABYLON.Observable}
  14598. */
  14599. this.onNewLightAddedObservable = new BABYLON.Observable();
  14600. /**
  14601. * An event triggered when a light is removed
  14602. * @type {BABYLON.Observable}
  14603. */
  14604. this.onLightRemovedObservable = new BABYLON.Observable();
  14605. /**
  14606. * An event triggered when a geometry is created
  14607. * @type {BABYLON.Observable}
  14608. */
  14609. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14610. /**
  14611. * An event triggered when a geometry is removed
  14612. * @type {BABYLON.Observable}
  14613. */
  14614. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14615. /**
  14616. * An event triggered when a mesh is created
  14617. * @type {BABYLON.Observable}
  14618. */
  14619. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14620. /**
  14621. * An event triggered when a mesh is removed
  14622. * @type {BABYLON.Observable}
  14623. */
  14624. this.onMeshRemovedObservable = new BABYLON.Observable();
  14625. // Animations
  14626. this.animations = [];
  14627. /**
  14628. * 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).
  14629. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14630. */
  14631. this.onPrePointerObservable = new BABYLON.Observable();
  14632. /**
  14633. * Observable event triggered each time an input event is received from the rendering canvas
  14634. */
  14635. this.onPointerObservable = new BABYLON.Observable();
  14636. 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
  14637. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14638. this._startingPointerTime = 0;
  14639. // Fog
  14640. /**
  14641. * is fog enabled on this scene.
  14642. * @type {boolean}
  14643. */
  14644. this.fogEnabled = true;
  14645. this.fogMode = Scene.FOGMODE_NONE;
  14646. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14647. this.fogDensity = 0.1;
  14648. this.fogStart = 0;
  14649. this.fogEnd = 1000.0;
  14650. // Lights
  14651. /**
  14652. * is shadow enabled on this scene.
  14653. * @type {boolean}
  14654. */
  14655. this.shadowsEnabled = true;
  14656. /**
  14657. * is light enabled on this scene.
  14658. * @type {boolean}
  14659. */
  14660. this.lightsEnabled = true;
  14661. /**
  14662. * All of the lights added to this scene.
  14663. * @see BABYLON.Light
  14664. * @type {BABYLON.Light[]}
  14665. */
  14666. this.lights = new Array();
  14667. // Cameras
  14668. /**
  14669. * All of the cameras added to this scene.
  14670. * @see BABYLON.Camera
  14671. * @type {BABYLON.Camera[]}
  14672. */
  14673. this.cameras = new Array();
  14674. this.activeCameras = new Array();
  14675. // Meshes
  14676. /**
  14677. * All of the (abstract) meshes added to this scene.
  14678. * @see BABYLON.AbstractMesh
  14679. * @type {BABYLON.AbstractMesh[]}
  14680. */
  14681. this.meshes = new Array();
  14682. // Geometries
  14683. this._geometries = new Array();
  14684. this.materials = new Array();
  14685. this.multiMaterials = new Array();
  14686. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14687. // Textures
  14688. this.texturesEnabled = true;
  14689. this.textures = new Array();
  14690. // Particles
  14691. this.particlesEnabled = true;
  14692. this.particleSystems = new Array();
  14693. // Sprites
  14694. this.spritesEnabled = true;
  14695. this.spriteManagers = new Array();
  14696. // Layers
  14697. this.layers = new Array();
  14698. // Skeletons
  14699. this.skeletonsEnabled = true;
  14700. this.skeletons = new Array();
  14701. // Lens flares
  14702. this.lensFlaresEnabled = true;
  14703. this.lensFlareSystems = new Array();
  14704. // Collisions
  14705. this.collisionsEnabled = true;
  14706. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14707. // Postprocesses
  14708. this.postProcessesEnabled = true;
  14709. // Customs render targets
  14710. this.renderTargetsEnabled = true;
  14711. this.dumpNextRenderTargets = false;
  14712. this.customRenderTargets = new Array();
  14713. // Imported meshes
  14714. this.importedMeshesFiles = new Array();
  14715. // Probes
  14716. this.probesEnabled = true;
  14717. this.reflectionProbes = new Array();
  14718. this._actionManagers = new Array();
  14719. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14720. // Procedural textures
  14721. this.proceduralTexturesEnabled = true;
  14722. this._proceduralTextures = new Array();
  14723. this.soundTracks = new Array();
  14724. this._audioEnabled = true;
  14725. this._headphone = false;
  14726. this._totalVertices = 0;
  14727. this._activeIndices = 0;
  14728. this._activeParticles = 0;
  14729. this._lastFrameDuration = 0;
  14730. this._evaluateActiveMeshesDuration = 0;
  14731. this._renderTargetsDuration = 0;
  14732. this._particlesDuration = 0;
  14733. this._renderDuration = 0;
  14734. this._spritesDuration = 0;
  14735. this._animationRatio = 0;
  14736. this._renderId = 0;
  14737. this._executeWhenReadyTimeoutId = -1;
  14738. this._intermediateRendering = false;
  14739. this._toBeDisposed = new BABYLON.SmartArray(256);
  14740. this._pendingData = []; //ANY
  14741. this._activeMeshes = new BABYLON.SmartArray(256);
  14742. this._processedMaterials = new BABYLON.SmartArray(256);
  14743. this._renderTargets = new BABYLON.SmartArray(256);
  14744. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14745. this._activeSkeletons = new BABYLON.SmartArray(32);
  14746. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14747. this._activeBones = 0;
  14748. this._activeAnimatables = new Array();
  14749. this._transformMatrix = BABYLON.Matrix.Zero();
  14750. this._edgesRenderers = new BABYLON.SmartArray(16);
  14751. this._uniqueIdCounter = 0;
  14752. this._engine = engine;
  14753. engine.scenes.push(this);
  14754. this._renderingManager = new BABYLON.RenderingManager(this);
  14755. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14756. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14757. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14758. if (BABYLON.OutlineRenderer) {
  14759. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14760. }
  14761. this.attachControl();
  14762. if (BABYLON.SoundTrack) {
  14763. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14764. }
  14765. //simplification queue
  14766. if (BABYLON.SimplificationQueue) {
  14767. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14768. }
  14769. //collision coordinator initialization. For now legacy per default.
  14770. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14771. }
  14772. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14773. get: function () {
  14774. return Scene._FOGMODE_NONE;
  14775. },
  14776. enumerable: true,
  14777. configurable: true
  14778. });
  14779. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14780. get: function () {
  14781. return Scene._FOGMODE_EXP;
  14782. },
  14783. enumerable: true,
  14784. configurable: true
  14785. });
  14786. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14787. get: function () {
  14788. return Scene._FOGMODE_EXP2;
  14789. },
  14790. enumerable: true,
  14791. configurable: true
  14792. });
  14793. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14794. get: function () {
  14795. return Scene._FOGMODE_LINEAR;
  14796. },
  14797. enumerable: true,
  14798. configurable: true
  14799. });
  14800. Object.defineProperty(Scene.prototype, "onDispose", {
  14801. set: function (callback) {
  14802. if (this._onDisposeObserver) {
  14803. this.onDisposeObservable.remove(this._onDisposeObserver);
  14804. }
  14805. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(Scene.prototype, "beforeRender", {
  14811. set: function (callback) {
  14812. if (this._onBeforeRenderObserver) {
  14813. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14814. }
  14815. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14816. },
  14817. enumerable: true,
  14818. configurable: true
  14819. });
  14820. Object.defineProperty(Scene.prototype, "afterRender", {
  14821. set: function (callback) {
  14822. if (this._onAfterRenderObserver) {
  14823. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14824. }
  14825. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14826. },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14831. set: function (callback) {
  14832. if (this._onBeforeCameraRenderObserver) {
  14833. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14834. }
  14835. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14836. },
  14837. enumerable: true,
  14838. configurable: true
  14839. });
  14840. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14841. set: function (callback) {
  14842. if (this._onAfterCameraRenderObserver) {
  14843. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14844. }
  14845. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14846. },
  14847. enumerable: true,
  14848. configurable: true
  14849. });
  14850. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14851. get: function () {
  14852. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14853. },
  14854. enumerable: true,
  14855. configurable: true
  14856. });
  14857. Object.defineProperty(Scene.prototype, "actionManager", {
  14858. /**
  14859. * This scene's action manager
  14860. * @type {BABYLON.ActionManager}
  14861. */
  14862. get: function () {
  14863. if (!this._sceneActionManager) {
  14864. this.actionManager = new BABYLON.ActionManager(this);
  14865. }
  14866. return this._sceneActionManager;
  14867. },
  14868. /**
  14869. * This scene's action manager
  14870. * @type {BABYLON.ActionManager}
  14871. */
  14872. set: function (value) {
  14873. this._sceneActionManager = value;
  14874. },
  14875. enumerable: true,
  14876. configurable: true
  14877. });
  14878. Object.defineProperty(Scene.prototype, "debugLayer", {
  14879. // Properties
  14880. get: function () {
  14881. if (!this._debugLayer) {
  14882. this._debugLayer = new BABYLON.DebugLayer(this);
  14883. }
  14884. return this._debugLayer;
  14885. },
  14886. enumerable: true,
  14887. configurable: true
  14888. });
  14889. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14890. get: function () {
  14891. return this._workerCollisions;
  14892. },
  14893. set: function (enabled) {
  14894. enabled = (enabled && !!Worker);
  14895. this._workerCollisions = enabled;
  14896. if (this.collisionCoordinator) {
  14897. this.collisionCoordinator.destroy();
  14898. }
  14899. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14900. this.collisionCoordinator.init(this);
  14901. },
  14902. enumerable: true,
  14903. configurable: true
  14904. });
  14905. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14906. get: function () {
  14907. return this._selectionOctree;
  14908. },
  14909. enumerable: true,
  14910. configurable: true
  14911. });
  14912. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14913. /**
  14914. * The mesh that is currently under the pointer.
  14915. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14916. */
  14917. get: function () {
  14918. return this._pointerOverMesh;
  14919. },
  14920. enumerable: true,
  14921. configurable: true
  14922. });
  14923. Object.defineProperty(Scene.prototype, "pointerX", {
  14924. /**
  14925. * Current on-screen X position of the pointer
  14926. * @return {number} X position of the pointer
  14927. */
  14928. get: function () {
  14929. return this._pointerX;
  14930. },
  14931. enumerable: true,
  14932. configurable: true
  14933. });
  14934. Object.defineProperty(Scene.prototype, "pointerY", {
  14935. /**
  14936. * Current on-screen Y position of the pointer
  14937. * @return {number} Y position of the pointer
  14938. */
  14939. get: function () {
  14940. return this._pointerY;
  14941. },
  14942. enumerable: true,
  14943. configurable: true
  14944. });
  14945. Scene.prototype.getCachedMaterial = function () {
  14946. return this._cachedMaterial;
  14947. };
  14948. Scene.prototype.getBoundingBoxRenderer = function () {
  14949. return this._boundingBoxRenderer;
  14950. };
  14951. Scene.prototype.getOutlineRenderer = function () {
  14952. return this._outlineRenderer;
  14953. };
  14954. Scene.prototype.getEngine = function () {
  14955. return this._engine;
  14956. };
  14957. Scene.prototype.getTotalVertices = function () {
  14958. return this._totalVertices;
  14959. };
  14960. Scene.prototype.getActiveIndices = function () {
  14961. return this._activeIndices;
  14962. };
  14963. Scene.prototype.getActiveParticles = function () {
  14964. return this._activeParticles;
  14965. };
  14966. Scene.prototype.getActiveBones = function () {
  14967. return this._activeBones;
  14968. };
  14969. // Stats
  14970. Scene.prototype.getLastFrameDuration = function () {
  14971. return this._lastFrameDuration;
  14972. };
  14973. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14974. return this._evaluateActiveMeshesDuration;
  14975. };
  14976. Scene.prototype.getActiveMeshes = function () {
  14977. return this._activeMeshes;
  14978. };
  14979. Scene.prototype.getRenderTargetsDuration = function () {
  14980. return this._renderTargetsDuration;
  14981. };
  14982. Scene.prototype.getRenderDuration = function () {
  14983. return this._renderDuration;
  14984. };
  14985. Scene.prototype.getParticlesDuration = function () {
  14986. return this._particlesDuration;
  14987. };
  14988. Scene.prototype.getSpritesDuration = function () {
  14989. return this._spritesDuration;
  14990. };
  14991. Scene.prototype.getAnimationRatio = function () {
  14992. return this._animationRatio;
  14993. };
  14994. Scene.prototype.getRenderId = function () {
  14995. return this._renderId;
  14996. };
  14997. Scene.prototype.incrementRenderId = function () {
  14998. this._renderId++;
  14999. };
  15000. Scene.prototype._updatePointerPosition = function (evt) {
  15001. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15002. this._pointerX = evt.clientX - canvasRect.left;
  15003. this._pointerY = evt.clientY - canvasRect.top;
  15004. this._unTranslatedPointerX = this._pointerX;
  15005. this._unTranslatedPointerY = this._pointerY;
  15006. if (this.cameraToUseForPointers) {
  15007. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15008. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15009. }
  15010. };
  15011. // Pointers handling
  15012. /**
  15013. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15014. * @param attachUp defines if you want to attach events to pointerup
  15015. * @param attachDown defines if you want to attach events to pointerdown
  15016. * @param attachMove defines if you want to attach events to pointermove
  15017. */
  15018. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15019. var _this = this;
  15020. if (attachUp === void 0) { attachUp = true; }
  15021. if (attachDown === void 0) { attachDown = true; }
  15022. if (attachMove === void 0) { attachMove = true; }
  15023. var spritePredicate = function (sprite) {
  15024. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15025. };
  15026. this._onPointerMove = function (evt) {
  15027. _this._updatePointerPosition(evt);
  15028. // PreObservable support
  15029. if (_this.onPrePointerObservable.hasObservers()) {
  15030. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15031. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15032. _this.onPrePointerObservable.notifyObservers(pi, type);
  15033. if (pi.skipOnPointerObservable) {
  15034. return;
  15035. }
  15036. }
  15037. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15038. return;
  15039. }
  15040. var canvas = _this._engine.getRenderingCanvas();
  15041. if (!_this.pointerMovePredicate) {
  15042. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  15043. }
  15044. // Meshes
  15045. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15046. if (pickResult.hit && pickResult.pickedMesh) {
  15047. _this.setPointerOverSprite(null);
  15048. _this.setPointerOverMesh(pickResult.pickedMesh);
  15049. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15050. canvas.style.cursor = "pointer";
  15051. }
  15052. else {
  15053. canvas.style.cursor = "";
  15054. }
  15055. }
  15056. else {
  15057. _this.setPointerOverMesh(null);
  15058. // Sprites
  15059. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15060. if (pickResult.hit && pickResult.pickedSprite) {
  15061. canvas.style.cursor = "pointer";
  15062. _this.setPointerOverSprite(pickResult.pickedSprite);
  15063. }
  15064. else {
  15065. _this.setPointerOverSprite(null);
  15066. // Restore pointer
  15067. canvas.style.cursor = "";
  15068. }
  15069. }
  15070. if (_this.onPointerMove) {
  15071. _this.onPointerMove(evt, pickResult);
  15072. }
  15073. if (_this.onPointerObservable.hasObservers()) {
  15074. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15075. var pi = new PointerInfo(type, evt, pickResult);
  15076. _this.onPointerObservable.notifyObservers(pi, type);
  15077. }
  15078. };
  15079. this._onPointerDown = function (evt) {
  15080. _this._updatePointerPosition(evt);
  15081. // PreObservable support
  15082. if (_this.onPrePointerObservable.hasObservers()) {
  15083. var type = PointerEventTypes.POINTERDOWN;
  15084. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15085. _this.onPrePointerObservable.notifyObservers(pi, type);
  15086. if (pi.skipOnPointerObservable) {
  15087. return;
  15088. }
  15089. }
  15090. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15091. return;
  15092. }
  15093. _this._startingPointerPosition.x = _this._pointerX;
  15094. _this._startingPointerPosition.y = _this._pointerY;
  15095. _this._startingPointerTime = new Date().getTime();
  15096. if (!_this.pointerDownPredicate) {
  15097. _this.pointerDownPredicate = function (mesh) {
  15098. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  15099. };
  15100. }
  15101. // Meshes
  15102. _this._pickedDownMesh = null;
  15103. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15104. if (pickResult.hit && pickResult.pickedMesh) {
  15105. if (pickResult.pickedMesh.actionManager) {
  15106. _this._pickedDownMesh = pickResult.pickedMesh;
  15107. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  15108. switch (evt.button) {
  15109. case 0:
  15110. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15111. break;
  15112. case 1:
  15113. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15114. break;
  15115. case 2:
  15116. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15117. break;
  15118. }
  15119. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15120. }
  15121. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15122. var that = _this;
  15123. window.setTimeout(function () {
  15124. 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);
  15125. if (pickResult.hit && pickResult.pickedMesh) {
  15126. if (pickResult.pickedMesh.actionManager) {
  15127. 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)) {
  15128. that._startingPointerTime = 0;
  15129. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15130. }
  15131. }
  15132. }
  15133. }, BABYLON.ActionManager.LongPressDelay);
  15134. }
  15135. }
  15136. }
  15137. if (_this.onPointerDown) {
  15138. _this.onPointerDown(evt, pickResult);
  15139. }
  15140. if (_this.onPointerObservable.hasObservers()) {
  15141. var type = PointerEventTypes.POINTERDOWN;
  15142. var pi = new PointerInfo(type, evt, pickResult);
  15143. _this.onPointerObservable.notifyObservers(pi, type);
  15144. }
  15145. // Sprites
  15146. _this._pickedDownSprite = null;
  15147. if (_this.spriteManagers.length > 0) {
  15148. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15149. if (pickResult.hit && pickResult.pickedSprite) {
  15150. if (pickResult.pickedSprite.actionManager) {
  15151. _this._pickedDownSprite = pickResult.pickedSprite;
  15152. switch (evt.button) {
  15153. case 0:
  15154. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15155. break;
  15156. case 1:
  15157. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15158. break;
  15159. case 2:
  15160. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15161. break;
  15162. }
  15163. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15164. }
  15165. }
  15166. }
  15167. };
  15168. this._onPointerUp = function (evt) {
  15169. _this._updatePointerPosition(evt);
  15170. // PreObservable support
  15171. if (_this.onPrePointerObservable.hasObservers()) {
  15172. var type = PointerEventTypes.POINTERUP;
  15173. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15174. _this.onPrePointerObservable.notifyObservers(pi, type);
  15175. if (pi.skipOnPointerObservable) {
  15176. return;
  15177. }
  15178. }
  15179. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15180. return;
  15181. }
  15182. if (!_this.pointerUpPredicate) {
  15183. _this.pointerUpPredicate = function (mesh) {
  15184. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15185. };
  15186. }
  15187. // Meshes
  15188. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15189. if (pickResult.hit && pickResult.pickedMesh) {
  15190. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15191. if (_this.onPointerPick) {
  15192. _this.onPointerPick(evt, pickResult);
  15193. }
  15194. if (_this.onPointerObservable.hasObservers()) {
  15195. var type = PointerEventTypes.POINTERPICK;
  15196. var pi = new PointerInfo(type, evt, pickResult);
  15197. _this.onPointerObservable.notifyObservers(pi, type);
  15198. }
  15199. }
  15200. if (pickResult.pickedMesh.actionManager) {
  15201. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15202. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15203. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15204. }
  15205. }
  15206. }
  15207. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15208. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15209. }
  15210. if (_this.onPointerUp) {
  15211. _this.onPointerUp(evt, pickResult);
  15212. }
  15213. if (_this.onPointerObservable.hasObservers()) {
  15214. var type = PointerEventTypes.POINTERUP;
  15215. var pi = new PointerInfo(type, evt, pickResult);
  15216. _this.onPointerObservable.notifyObservers(pi, type);
  15217. }
  15218. _this._startingPointerTime = 0;
  15219. // Sprites
  15220. if (_this.spriteManagers.length > 0) {
  15221. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15222. if (pickResult.hit && pickResult.pickedSprite) {
  15223. if (pickResult.pickedSprite.actionManager) {
  15224. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15225. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15226. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15227. }
  15228. }
  15229. }
  15230. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15231. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15232. }
  15233. }
  15234. };
  15235. this._onKeyDown = function (evt) {
  15236. if (_this.actionManager) {
  15237. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15238. }
  15239. };
  15240. this._onKeyUp = function (evt) {
  15241. if (_this.actionManager) {
  15242. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15243. }
  15244. };
  15245. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15246. if (attachMove) {
  15247. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15248. // Wheel
  15249. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  15250. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15251. }
  15252. if (attachDown) {
  15253. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15254. }
  15255. if (attachUp) {
  15256. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15257. }
  15258. BABYLON.Tools.RegisterTopRootEvents([
  15259. { name: "keydown", handler: this._onKeyDown },
  15260. { name: "keyup", handler: this._onKeyUp }
  15261. ]);
  15262. };
  15263. Scene.prototype.detachControl = function () {
  15264. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15265. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  15266. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  15267. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  15268. // Wheel
  15269. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  15270. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  15271. BABYLON.Tools.UnregisterTopRootEvents([
  15272. { name: "keydown", handler: this._onKeyDown },
  15273. { name: "keyup", handler: this._onKeyUp }
  15274. ]);
  15275. };
  15276. // Ready
  15277. Scene.prototype.isReady = function () {
  15278. if (this._pendingData.length > 0) {
  15279. return false;
  15280. }
  15281. var index;
  15282. for (index = 0; index < this._geometries.length; index++) {
  15283. var geometry = this._geometries[index];
  15284. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15285. return false;
  15286. }
  15287. }
  15288. for (index = 0; index < this.meshes.length; index++) {
  15289. var mesh = this.meshes[index];
  15290. if (!mesh.isReady()) {
  15291. return false;
  15292. }
  15293. var mat = mesh.material;
  15294. if (mat) {
  15295. if (!mat.isReady(mesh)) {
  15296. return false;
  15297. }
  15298. }
  15299. }
  15300. return true;
  15301. };
  15302. Scene.prototype.resetCachedMaterial = function () {
  15303. this._cachedMaterial = null;
  15304. };
  15305. Scene.prototype.registerBeforeRender = function (func) {
  15306. this.onBeforeRenderObservable.add(func);
  15307. };
  15308. Scene.prototype.unregisterBeforeRender = function (func) {
  15309. this.onBeforeRenderObservable.removeCallback(func);
  15310. };
  15311. Scene.prototype.registerAfterRender = function (func) {
  15312. this.onAfterRenderObservable.add(func);
  15313. };
  15314. Scene.prototype.unregisterAfterRender = function (func) {
  15315. this.onAfterRenderObservable.removeCallback(func);
  15316. };
  15317. Scene.prototype._addPendingData = function (data) {
  15318. this._pendingData.push(data);
  15319. };
  15320. Scene.prototype._removePendingData = function (data) {
  15321. var index = this._pendingData.indexOf(data);
  15322. if (index !== -1) {
  15323. this._pendingData.splice(index, 1);
  15324. }
  15325. };
  15326. Scene.prototype.getWaitingItemsCount = function () {
  15327. return this._pendingData.length;
  15328. };
  15329. /**
  15330. * Registers a function to be executed when the scene is ready.
  15331. * @param {Function} func - the function to be executed.
  15332. */
  15333. Scene.prototype.executeWhenReady = function (func) {
  15334. var _this = this;
  15335. this.onReadyObservable.add(func);
  15336. if (this._executeWhenReadyTimeoutId !== -1) {
  15337. return;
  15338. }
  15339. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15340. _this._checkIsReady();
  15341. }, 150);
  15342. };
  15343. Scene.prototype._checkIsReady = function () {
  15344. var _this = this;
  15345. if (this.isReady()) {
  15346. this.onReadyObservable.notifyObservers(this);
  15347. this.onReadyObservable.clear();
  15348. this._executeWhenReadyTimeoutId = -1;
  15349. return;
  15350. }
  15351. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15352. _this._checkIsReady();
  15353. }, 150);
  15354. };
  15355. // Animations
  15356. /**
  15357. * Will start the animation sequence of a given target
  15358. * @param target - the target
  15359. * @param {number} from - from which frame should animation start
  15360. * @param {number} to - till which frame should animation run.
  15361. * @param {boolean} [loop] - should the animation loop
  15362. * @param {number} [speedRatio] - the speed in which to run the animation
  15363. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15364. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15365. * @return {BABYLON.Animatable} the animatable object created for this animation
  15366. * @see BABYLON.Animatable
  15367. * @see http://doc.babylonjs.com/page.php?p=22081
  15368. */
  15369. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15370. if (speedRatio === void 0) { speedRatio = 1.0; }
  15371. this.stopAnimation(target);
  15372. if (!animatable) {
  15373. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15374. }
  15375. // Local animations
  15376. if (target.animations) {
  15377. animatable.appendAnimations(target, target.animations);
  15378. }
  15379. // Children animations
  15380. if (target.getAnimatables) {
  15381. var animatables = target.getAnimatables();
  15382. for (var index = 0; index < animatables.length; index++) {
  15383. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15384. }
  15385. }
  15386. animatable.reset();
  15387. return animatable;
  15388. };
  15389. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15390. if (speedRatio === undefined) {
  15391. speedRatio = 1.0;
  15392. }
  15393. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15394. return animatable;
  15395. };
  15396. Scene.prototype.getAnimatableByTarget = function (target) {
  15397. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15398. if (this._activeAnimatables[index].target === target) {
  15399. return this._activeAnimatables[index];
  15400. }
  15401. }
  15402. return null;
  15403. };
  15404. Object.defineProperty(Scene.prototype, "Animatables", {
  15405. get: function () {
  15406. return this._activeAnimatables;
  15407. },
  15408. enumerable: true,
  15409. configurable: true
  15410. });
  15411. /**
  15412. * Will stop the animation of the given target
  15413. * @param target - the target
  15414. * @see beginAnimation
  15415. */
  15416. Scene.prototype.stopAnimation = function (target) {
  15417. var animatable = this.getAnimatableByTarget(target);
  15418. if (animatable) {
  15419. animatable.stop();
  15420. }
  15421. };
  15422. Scene.prototype._animate = function () {
  15423. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15424. return;
  15425. }
  15426. if (!this._animationStartDate) {
  15427. if (this._pendingData.length > 0) {
  15428. return;
  15429. }
  15430. this._animationStartDate = BABYLON.Tools.Now;
  15431. }
  15432. // Getting time
  15433. var now = BABYLON.Tools.Now;
  15434. var delay = now - this._animationStartDate;
  15435. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15436. this._activeAnimatables[index]._animate(delay);
  15437. }
  15438. };
  15439. // Matrix
  15440. Scene.prototype.getViewMatrix = function () {
  15441. return this._viewMatrix;
  15442. };
  15443. Scene.prototype.getProjectionMatrix = function () {
  15444. return this._projectionMatrix;
  15445. };
  15446. Scene.prototype.getTransformMatrix = function () {
  15447. return this._transformMatrix;
  15448. };
  15449. Scene.prototype.setTransformMatrix = function (view, projection) {
  15450. this._viewMatrix = view;
  15451. this._projectionMatrix = projection;
  15452. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15453. };
  15454. // Methods
  15455. Scene.prototype.addMesh = function (newMesh) {
  15456. newMesh.uniqueId = this._uniqueIdCounter++;
  15457. var position = this.meshes.push(newMesh);
  15458. //notify the collision coordinator
  15459. this.collisionCoordinator.onMeshAdded(newMesh);
  15460. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15461. };
  15462. Scene.prototype.removeMesh = function (toRemove) {
  15463. var index = this.meshes.indexOf(toRemove);
  15464. if (index !== -1) {
  15465. // Remove from the scene if mesh found
  15466. this.meshes.splice(index, 1);
  15467. }
  15468. //notify the collision coordinator
  15469. this.collisionCoordinator.onMeshRemoved(toRemove);
  15470. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15471. return index;
  15472. };
  15473. Scene.prototype.removeSkeleton = function (toRemove) {
  15474. var index = this.skeletons.indexOf(toRemove);
  15475. if (index !== -1) {
  15476. // Remove from the scene if mesh found
  15477. this.skeletons.splice(index, 1);
  15478. }
  15479. return index;
  15480. };
  15481. Scene.prototype.removeLight = function (toRemove) {
  15482. var index = this.lights.indexOf(toRemove);
  15483. if (index !== -1) {
  15484. // Remove from the scene if mesh found
  15485. this.lights.splice(index, 1);
  15486. }
  15487. this.onLightRemovedObservable.notifyObservers(toRemove);
  15488. return index;
  15489. };
  15490. Scene.prototype.removeCamera = function (toRemove) {
  15491. var index = this.cameras.indexOf(toRemove);
  15492. if (index !== -1) {
  15493. // Remove from the scene if mesh found
  15494. this.cameras.splice(index, 1);
  15495. }
  15496. // Remove from activeCameras
  15497. var index2 = this.activeCameras.indexOf(toRemove);
  15498. if (index2 !== -1) {
  15499. // Remove from the scene if mesh found
  15500. this.activeCameras.splice(index2, 1);
  15501. }
  15502. // Reset the activeCamera
  15503. if (this.activeCamera === toRemove) {
  15504. if (this.cameras.length > 0) {
  15505. this.activeCamera = this.cameras[0];
  15506. }
  15507. else {
  15508. this.activeCamera = null;
  15509. }
  15510. }
  15511. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15512. return index;
  15513. };
  15514. Scene.prototype.addLight = function (newLight) {
  15515. newLight.uniqueId = this._uniqueIdCounter++;
  15516. var position = this.lights.push(newLight);
  15517. this.onNewLightAddedObservable.notifyObservers(newLight);
  15518. };
  15519. Scene.prototype.addCamera = function (newCamera) {
  15520. newCamera.uniqueId = this._uniqueIdCounter++;
  15521. var position = this.cameras.push(newCamera);
  15522. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15523. };
  15524. /**
  15525. * Switch active camera
  15526. * @param {Camera} newCamera - new active camera
  15527. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15528. */
  15529. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15530. if (attachControl === void 0) { attachControl = true; }
  15531. var canvas = this._engine.getRenderingCanvas();
  15532. this.activeCamera.detachControl(canvas);
  15533. this.activeCamera = newCamera;
  15534. if (attachControl) {
  15535. newCamera.attachControl(canvas);
  15536. }
  15537. };
  15538. /**
  15539. * sets the active camera of the scene using its ID
  15540. * @param {string} id - the camera's ID
  15541. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15542. * @see activeCamera
  15543. */
  15544. Scene.prototype.setActiveCameraByID = function (id) {
  15545. var camera = this.getCameraByID(id);
  15546. if (camera) {
  15547. this.activeCamera = camera;
  15548. return camera;
  15549. }
  15550. return null;
  15551. };
  15552. /**
  15553. * sets the active camera of the scene using its name
  15554. * @param {string} name - the camera's name
  15555. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15556. * @see activeCamera
  15557. */
  15558. Scene.prototype.setActiveCameraByName = function (name) {
  15559. var camera = this.getCameraByName(name);
  15560. if (camera) {
  15561. this.activeCamera = camera;
  15562. return camera;
  15563. }
  15564. return null;
  15565. };
  15566. /**
  15567. * get a material using its id
  15568. * @param {string} the material's ID
  15569. * @return {BABYLON.Material|null} the material or null if none found.
  15570. */
  15571. Scene.prototype.getMaterialByID = function (id) {
  15572. for (var index = 0; index < this.materials.length; index++) {
  15573. if (this.materials[index].id === id) {
  15574. return this.materials[index];
  15575. }
  15576. }
  15577. return null;
  15578. };
  15579. /**
  15580. * get a material using its name
  15581. * @param {string} the material's name
  15582. * @return {BABYLON.Material|null} the material or null if none found.
  15583. */
  15584. Scene.prototype.getMaterialByName = function (name) {
  15585. for (var index = 0; index < this.materials.length; index++) {
  15586. if (this.materials[index].name === name) {
  15587. return this.materials[index];
  15588. }
  15589. }
  15590. return null;
  15591. };
  15592. Scene.prototype.getLensFlareSystemByName = function (name) {
  15593. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15594. if (this.lensFlareSystems[index].name === name) {
  15595. return this.lensFlareSystems[index];
  15596. }
  15597. }
  15598. return null;
  15599. };
  15600. Scene.prototype.getLensFlareSystemByID = function (id) {
  15601. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15602. if (this.lensFlareSystems[index].id === id) {
  15603. return this.lensFlareSystems[index];
  15604. }
  15605. }
  15606. return null;
  15607. };
  15608. Scene.prototype.getCameraByID = function (id) {
  15609. for (var index = 0; index < this.cameras.length; index++) {
  15610. if (this.cameras[index].id === id) {
  15611. return this.cameras[index];
  15612. }
  15613. }
  15614. return null;
  15615. };
  15616. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15617. for (var index = 0; index < this.cameras.length; index++) {
  15618. if (this.cameras[index].uniqueId === uniqueId) {
  15619. return this.cameras[index];
  15620. }
  15621. }
  15622. return null;
  15623. };
  15624. /**
  15625. * get a camera using its name
  15626. * @param {string} the camera's name
  15627. * @return {BABYLON.Camera|null} the camera or null if none found.
  15628. */
  15629. Scene.prototype.getCameraByName = function (name) {
  15630. for (var index = 0; index < this.cameras.length; index++) {
  15631. if (this.cameras[index].name === name) {
  15632. return this.cameras[index];
  15633. }
  15634. }
  15635. return null;
  15636. };
  15637. /**
  15638. * get a bone using its id
  15639. * @param {string} the bone's id
  15640. * @return {BABYLON.Bone|null} the bone or null if not found
  15641. */
  15642. Scene.prototype.getBoneByID = function (id) {
  15643. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15644. var skeleton = this.skeletons[skeletonIndex];
  15645. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15646. if (skeleton.bones[boneIndex].id === id) {
  15647. return skeleton.bones[boneIndex];
  15648. }
  15649. }
  15650. }
  15651. return null;
  15652. };
  15653. /**
  15654. * get a bone using its id
  15655. * @param {string} the bone's name
  15656. * @return {BABYLON.Bone|null} the bone or null if not found
  15657. */
  15658. Scene.prototype.getBoneByName = function (name) {
  15659. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15660. var skeleton = this.skeletons[skeletonIndex];
  15661. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15662. if (skeleton.bones[boneIndex].name === name) {
  15663. return skeleton.bones[boneIndex];
  15664. }
  15665. }
  15666. }
  15667. return null;
  15668. };
  15669. /**
  15670. * get a light node using its name
  15671. * @param {string} the light's name
  15672. * @return {BABYLON.Light|null} the light or null if none found.
  15673. */
  15674. Scene.prototype.getLightByName = function (name) {
  15675. for (var index = 0; index < this.lights.length; index++) {
  15676. if (this.lights[index].name === name) {
  15677. return this.lights[index];
  15678. }
  15679. }
  15680. return null;
  15681. };
  15682. /**
  15683. * get a light node using its ID
  15684. * @param {string} the light's id
  15685. * @return {BABYLON.Light|null} the light or null if none found.
  15686. */
  15687. Scene.prototype.getLightByID = function (id) {
  15688. for (var index = 0; index < this.lights.length; index++) {
  15689. if (this.lights[index].id === id) {
  15690. return this.lights[index];
  15691. }
  15692. }
  15693. return null;
  15694. };
  15695. /**
  15696. * get a light node using its scene-generated unique ID
  15697. * @param {number} the light's unique id
  15698. * @return {BABYLON.Light|null} the light or null if none found.
  15699. */
  15700. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15701. for (var index = 0; index < this.lights.length; index++) {
  15702. if (this.lights[index].uniqueId === uniqueId) {
  15703. return this.lights[index];
  15704. }
  15705. }
  15706. return null;
  15707. };
  15708. /**
  15709. * get a particle system by id
  15710. * @param id {number} the particle system id
  15711. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15712. */
  15713. Scene.prototype.getParticleSystemByID = function (id) {
  15714. for (var index = 0; index < this.particleSystems.length; index++) {
  15715. if (this.particleSystems[index].id === id) {
  15716. return this.particleSystems[index];
  15717. }
  15718. }
  15719. return null;
  15720. };
  15721. /**
  15722. * get a geometry using its ID
  15723. * @param {string} the geometry's id
  15724. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15725. */
  15726. Scene.prototype.getGeometryByID = function (id) {
  15727. for (var index = 0; index < this._geometries.length; index++) {
  15728. if (this._geometries[index].id === id) {
  15729. return this._geometries[index];
  15730. }
  15731. }
  15732. return null;
  15733. };
  15734. /**
  15735. * add a new geometry to this scene.
  15736. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15737. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15738. * @return {boolean} was the geometry added or not
  15739. */
  15740. Scene.prototype.pushGeometry = function (geometry, force) {
  15741. if (!force && this.getGeometryByID(geometry.id)) {
  15742. return false;
  15743. }
  15744. this._geometries.push(geometry);
  15745. //notify the collision coordinator
  15746. this.collisionCoordinator.onGeometryAdded(geometry);
  15747. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15748. return true;
  15749. };
  15750. /**
  15751. * Removes an existing geometry
  15752. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15753. * @return {boolean} was the geometry removed or not
  15754. */
  15755. Scene.prototype.removeGeometry = function (geometry) {
  15756. var index = this._geometries.indexOf(geometry);
  15757. if (index > -1) {
  15758. this._geometries.splice(index, 1);
  15759. //notify the collision coordinator
  15760. this.collisionCoordinator.onGeometryDeleted(geometry);
  15761. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15762. return true;
  15763. }
  15764. return false;
  15765. };
  15766. Scene.prototype.getGeometries = function () {
  15767. return this._geometries;
  15768. };
  15769. /**
  15770. * Get the first added mesh found of a given ID
  15771. * @param {string} id - the id to search for
  15772. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15773. */
  15774. Scene.prototype.getMeshByID = function (id) {
  15775. for (var index = 0; index < this.meshes.length; index++) {
  15776. if (this.meshes[index].id === id) {
  15777. return this.meshes[index];
  15778. }
  15779. }
  15780. return null;
  15781. };
  15782. Scene.prototype.getMeshesByID = function (id) {
  15783. return this.meshes.filter(function (m) {
  15784. return m.id === id;
  15785. });
  15786. };
  15787. /**
  15788. * Get a mesh with its auto-generated unique id
  15789. * @param {number} uniqueId - the unique id to search for
  15790. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15791. */
  15792. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15793. for (var index = 0; index < this.meshes.length; index++) {
  15794. if (this.meshes[index].uniqueId === uniqueId) {
  15795. return this.meshes[index];
  15796. }
  15797. }
  15798. return null;
  15799. };
  15800. /**
  15801. * Get a the last added mesh found of a given ID
  15802. * @param {string} id - the id to search for
  15803. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15804. */
  15805. Scene.prototype.getLastMeshByID = function (id) {
  15806. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15807. if (this.meshes[index].id === id) {
  15808. return this.meshes[index];
  15809. }
  15810. }
  15811. return null;
  15812. };
  15813. /**
  15814. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15815. * @param {string} id - the id to search for
  15816. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15817. */
  15818. Scene.prototype.getLastEntryByID = function (id) {
  15819. var index;
  15820. for (index = this.meshes.length - 1; index >= 0; index--) {
  15821. if (this.meshes[index].id === id) {
  15822. return this.meshes[index];
  15823. }
  15824. }
  15825. for (index = this.cameras.length - 1; index >= 0; index--) {
  15826. if (this.cameras[index].id === id) {
  15827. return this.cameras[index];
  15828. }
  15829. }
  15830. for (index = this.lights.length - 1; index >= 0; index--) {
  15831. if (this.lights[index].id === id) {
  15832. return this.lights[index];
  15833. }
  15834. }
  15835. return null;
  15836. };
  15837. Scene.prototype.getNodeByID = function (id) {
  15838. var mesh = this.getMeshByID(id);
  15839. if (mesh) {
  15840. return mesh;
  15841. }
  15842. var light = this.getLightByID(id);
  15843. if (light) {
  15844. return light;
  15845. }
  15846. var camera = this.getCameraByID(id);
  15847. if (camera) {
  15848. return camera;
  15849. }
  15850. var bone = this.getBoneByID(id);
  15851. return bone;
  15852. };
  15853. Scene.prototype.getNodeByName = function (name) {
  15854. var mesh = this.getMeshByName(name);
  15855. if (mesh) {
  15856. return mesh;
  15857. }
  15858. var light = this.getLightByName(name);
  15859. if (light) {
  15860. return light;
  15861. }
  15862. var camera = this.getCameraByName(name);
  15863. if (camera) {
  15864. return camera;
  15865. }
  15866. var bone = this.getBoneByName(name);
  15867. return bone;
  15868. };
  15869. Scene.prototype.getMeshByName = function (name) {
  15870. for (var index = 0; index < this.meshes.length; index++) {
  15871. if (this.meshes[index].name === name) {
  15872. return this.meshes[index];
  15873. }
  15874. }
  15875. return null;
  15876. };
  15877. Scene.prototype.getSoundByName = function (name) {
  15878. var index;
  15879. if (BABYLON.AudioEngine) {
  15880. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15881. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15882. return this.mainSoundTrack.soundCollection[index];
  15883. }
  15884. }
  15885. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15886. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15887. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15888. return this.soundTracks[sdIndex].soundCollection[index];
  15889. }
  15890. }
  15891. }
  15892. }
  15893. return null;
  15894. };
  15895. Scene.prototype.getLastSkeletonByID = function (id) {
  15896. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15897. if (this.skeletons[index].id === id) {
  15898. return this.skeletons[index];
  15899. }
  15900. }
  15901. return null;
  15902. };
  15903. Scene.prototype.getSkeletonById = function (id) {
  15904. for (var index = 0; index < this.skeletons.length; index++) {
  15905. if (this.skeletons[index].id === id) {
  15906. return this.skeletons[index];
  15907. }
  15908. }
  15909. return null;
  15910. };
  15911. Scene.prototype.getSkeletonByName = function (name) {
  15912. for (var index = 0; index < this.skeletons.length; index++) {
  15913. if (this.skeletons[index].name === name) {
  15914. return this.skeletons[index];
  15915. }
  15916. }
  15917. return null;
  15918. };
  15919. Scene.prototype.isActiveMesh = function (mesh) {
  15920. return (this._activeMeshes.indexOf(mesh) !== -1);
  15921. };
  15922. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15923. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15924. var material = subMesh.getMaterial();
  15925. if (mesh.showSubMeshesBoundingBox) {
  15926. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15927. }
  15928. if (material) {
  15929. // Render targets
  15930. if (material.getRenderTargetTextures) {
  15931. if (this._processedMaterials.indexOf(material) === -1) {
  15932. this._processedMaterials.push(material);
  15933. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15934. }
  15935. }
  15936. // Dispatch
  15937. this._activeIndices += subMesh.indexCount;
  15938. this._renderingManager.dispatch(subMesh);
  15939. }
  15940. }
  15941. };
  15942. Scene.prototype._isInIntermediateRendering = function () {
  15943. return this._intermediateRendering;
  15944. };
  15945. Scene.prototype._evaluateActiveMeshes = function () {
  15946. this.activeCamera._activeMeshes.reset();
  15947. this._activeMeshes.reset();
  15948. this._renderingManager.reset();
  15949. this._processedMaterials.reset();
  15950. this._activeParticleSystems.reset();
  15951. this._activeSkeletons.reset();
  15952. this._softwareSkinnedMeshes.reset();
  15953. this._boundingBoxRenderer.reset();
  15954. this._edgesRenderers.reset();
  15955. if (!this._frustumPlanes) {
  15956. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15957. }
  15958. else {
  15959. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15960. }
  15961. // Meshes
  15962. var meshes;
  15963. var len;
  15964. if (this._selectionOctree) {
  15965. var selection = this._selectionOctree.select(this._frustumPlanes);
  15966. meshes = selection.data;
  15967. len = selection.length;
  15968. }
  15969. else {
  15970. len = this.meshes.length;
  15971. meshes = this.meshes;
  15972. }
  15973. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15974. var mesh = meshes[meshIndex];
  15975. if (mesh.isBlocked) {
  15976. continue;
  15977. }
  15978. this._totalVertices += mesh.getTotalVertices();
  15979. if (!mesh.isReady() || !mesh.isEnabled()) {
  15980. continue;
  15981. }
  15982. mesh.computeWorldMatrix();
  15983. // Intersections
  15984. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15985. this._meshesForIntersections.pushNoDuplicate(mesh);
  15986. }
  15987. // Switch to current LOD
  15988. var meshLOD = mesh.getLOD(this.activeCamera);
  15989. if (!meshLOD) {
  15990. continue;
  15991. }
  15992. mesh._preActivate();
  15993. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15994. this._activeMeshes.push(mesh);
  15995. this.activeCamera._activeMeshes.push(mesh);
  15996. mesh._activate(this._renderId);
  15997. this._activeMesh(meshLOD);
  15998. }
  15999. }
  16000. // Particle systems
  16001. var beforeParticlesDate = BABYLON.Tools.Now;
  16002. if (this.particlesEnabled) {
  16003. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16004. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16005. var particleSystem = this.particleSystems[particleIndex];
  16006. if (!particleSystem.isStarted()) {
  16007. continue;
  16008. }
  16009. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16010. this._activeParticleSystems.push(particleSystem);
  16011. particleSystem.animate();
  16012. }
  16013. }
  16014. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16015. }
  16016. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  16017. };
  16018. Scene.prototype._activeMesh = function (mesh) {
  16019. if (mesh.skeleton && this.skeletonsEnabled) {
  16020. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  16021. if (!mesh.computeBonesUsingShaders) {
  16022. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16023. }
  16024. }
  16025. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16026. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  16027. }
  16028. if (mesh._edgesRenderer) {
  16029. this._edgesRenderers.push(mesh._edgesRenderer);
  16030. }
  16031. if (mesh && mesh.subMeshes) {
  16032. // Submeshes Octrees
  16033. var len;
  16034. var subMeshes;
  16035. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16036. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16037. len = intersections.length;
  16038. subMeshes = intersections.data;
  16039. }
  16040. else {
  16041. subMeshes = mesh.subMeshes;
  16042. len = subMeshes.length;
  16043. }
  16044. for (var subIndex = 0; subIndex < len; subIndex++) {
  16045. var subMesh = subMeshes[subIndex];
  16046. this._evaluateSubMesh(subMesh, mesh);
  16047. }
  16048. }
  16049. };
  16050. Scene.prototype.updateTransformMatrix = function (force) {
  16051. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16052. };
  16053. Scene.prototype._renderForCamera = function (camera) {
  16054. var engine = this._engine;
  16055. this.activeCamera = camera;
  16056. if (!this.activeCamera)
  16057. throw new Error("Active camera not set");
  16058. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16059. // Viewport
  16060. engine.setViewport(this.activeCamera.viewport);
  16061. // Camera
  16062. this.resetCachedMaterial();
  16063. this._renderId++;
  16064. this.updateTransformMatrix();
  16065. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16066. // Meshes
  16067. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  16068. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16069. this._evaluateActiveMeshes();
  16070. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  16071. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16072. // Skeletons
  16073. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  16074. var skeleton = this._activeSkeletons.data[skeletonIndex];
  16075. skeleton.prepare();
  16076. }
  16077. // Software skinning
  16078. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16079. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16080. mesh.applySkeleton(mesh.skeleton);
  16081. }
  16082. // Render targets
  16083. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16084. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16085. this._intermediateRendering = true;
  16086. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16087. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16088. var renderTarget = this._renderTargets.data[renderIndex];
  16089. if (renderTarget._shouldRender()) {
  16090. this._renderId++;
  16091. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16092. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16093. }
  16094. }
  16095. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16096. this._intermediateRendering = false;
  16097. this._renderId++;
  16098. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16099. }
  16100. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  16101. // Prepare Frame
  16102. this.postProcessManager._prepareFrame();
  16103. var beforeRenderDate = BABYLON.Tools.Now;
  16104. // Backgrounds
  16105. var layerIndex;
  16106. var layer;
  16107. if (this.layers.length) {
  16108. engine.setDepthBuffer(false);
  16109. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16110. layer = this.layers[layerIndex];
  16111. if (layer.isBackground) {
  16112. layer.render();
  16113. }
  16114. }
  16115. engine.setDepthBuffer(true);
  16116. }
  16117. // Render
  16118. BABYLON.Tools.StartPerformanceCounter("Main render");
  16119. this._renderingManager.render(null, null, true, true);
  16120. BABYLON.Tools.EndPerformanceCounter("Main render");
  16121. // Bounding boxes
  16122. this._boundingBoxRenderer.render();
  16123. // Edges
  16124. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16125. this._edgesRenderers.data[edgesRendererIndex].render();
  16126. }
  16127. // Lens flares
  16128. if (this.lensFlaresEnabled) {
  16129. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16130. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16131. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16132. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16133. lensFlareSystem.render();
  16134. }
  16135. }
  16136. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16137. }
  16138. // Foregrounds
  16139. if (this.layers.length) {
  16140. engine.setDepthBuffer(false);
  16141. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16142. layer = this.layers[layerIndex];
  16143. if (!layer.isBackground) {
  16144. layer.render();
  16145. }
  16146. }
  16147. engine.setDepthBuffer(true);
  16148. }
  16149. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  16150. // Finalize frame
  16151. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16152. // Update camera
  16153. this.activeCamera._updateFromScene();
  16154. // Reset some special arrays
  16155. this._renderTargets.reset();
  16156. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16157. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16158. };
  16159. Scene.prototype._processSubCameras = function (camera) {
  16160. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16161. this._renderForCamera(camera);
  16162. return;
  16163. }
  16164. // rig cameras
  16165. for (var index = 0; index < camera._rigCameras.length; index++) {
  16166. this._renderForCamera(camera._rigCameras[index]);
  16167. }
  16168. this.activeCamera = camera;
  16169. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16170. // Update camera
  16171. this.activeCamera._updateFromScene();
  16172. };
  16173. Scene.prototype._checkIntersections = function () {
  16174. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16175. var sourceMesh = this._meshesForIntersections.data[index];
  16176. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16177. var action = sourceMesh.actionManager.actions[actionIndex];
  16178. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16179. var parameters = action.getTriggerParameter();
  16180. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16181. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16182. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16183. if (areIntersecting && currentIntersectionInProgress === -1) {
  16184. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16185. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16186. sourceMesh._intersectionsInProgress.push(otherMesh);
  16187. }
  16188. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16189. sourceMesh._intersectionsInProgress.push(otherMesh);
  16190. }
  16191. }
  16192. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16193. //They intersected, and now they don't.
  16194. //is this trigger an exit trigger? execute an event.
  16195. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16196. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16197. }
  16198. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16199. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16200. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16201. }
  16202. }
  16203. }
  16204. }
  16205. }
  16206. };
  16207. Scene.prototype.render = function () {
  16208. var startDate = BABYLON.Tools.Now;
  16209. this._particlesDuration = 0;
  16210. this._spritesDuration = 0;
  16211. this._activeParticles = 0;
  16212. this._renderDuration = 0;
  16213. this._renderTargetsDuration = 0;
  16214. this._evaluateActiveMeshesDuration = 0;
  16215. this._totalVertices = 0;
  16216. this._activeIndices = 0;
  16217. this._activeBones = 0;
  16218. this.getEngine().resetDrawCalls();
  16219. this._meshesForIntersections.reset();
  16220. this.resetCachedMaterial();
  16221. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16222. // Actions
  16223. if (this.actionManager) {
  16224. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16225. }
  16226. //Simplification Queue
  16227. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16228. this.simplificationQueue.executeNext();
  16229. }
  16230. // Animations
  16231. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16232. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16233. this._animate();
  16234. // Physics
  16235. if (this._physicsEngine) {
  16236. BABYLON.Tools.StartPerformanceCounter("Physics");
  16237. this._physicsEngine._step(deltaTime / 1000.0);
  16238. BABYLON.Tools.EndPerformanceCounter("Physics");
  16239. }
  16240. // Before render
  16241. this.onBeforeRenderObservable.notifyObservers(this);
  16242. // Customs render targets
  16243. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16244. var engine = this.getEngine();
  16245. var currentActiveCamera = this.activeCamera;
  16246. if (this.renderTargetsEnabled) {
  16247. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16248. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16249. var renderTarget = this.customRenderTargets[customIndex];
  16250. if (renderTarget._shouldRender()) {
  16251. this._renderId++;
  16252. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16253. if (!this.activeCamera)
  16254. throw new Error("Active camera not set");
  16255. // Viewport
  16256. engine.setViewport(this.activeCamera.viewport);
  16257. // Camera
  16258. this.updateTransformMatrix();
  16259. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16260. }
  16261. }
  16262. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16263. this._renderId++;
  16264. }
  16265. if (this.customRenderTargets.length > 0) {
  16266. engine.restoreDefaultFramebuffer();
  16267. }
  16268. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  16269. this.activeCamera = currentActiveCamera;
  16270. // Procedural textures
  16271. if (this.proceduralTexturesEnabled) {
  16272. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16273. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16274. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16275. if (proceduralTexture._shouldRender()) {
  16276. proceduralTexture.render();
  16277. }
  16278. }
  16279. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16280. }
  16281. // Clear
  16282. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16283. // Shadows
  16284. if (this.shadowsEnabled) {
  16285. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16286. var light = this.lights[lightIndex];
  16287. var shadowGenerator = light.getShadowGenerator();
  16288. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16289. this._renderTargets.push(shadowGenerator.getShadowMap());
  16290. }
  16291. }
  16292. }
  16293. // Depth renderer
  16294. if (this._depthRenderer) {
  16295. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16296. }
  16297. // RenderPipeline
  16298. this.postProcessRenderPipelineManager.update();
  16299. // Multi-cameras?
  16300. if (this.activeCameras.length > 0) {
  16301. var currentRenderId = this._renderId;
  16302. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16303. this._renderId = currentRenderId;
  16304. if (cameraIndex > 0) {
  16305. this._engine.clear(0, false, true);
  16306. }
  16307. this._processSubCameras(this.activeCameras[cameraIndex]);
  16308. }
  16309. }
  16310. else {
  16311. if (!this.activeCamera) {
  16312. throw new Error("No camera defined");
  16313. }
  16314. this._processSubCameras(this.activeCamera);
  16315. }
  16316. // Intersection checks
  16317. this._checkIntersections();
  16318. // Update the audio listener attached to the camera
  16319. if (BABYLON.AudioEngine) {
  16320. this._updateAudioParameters();
  16321. }
  16322. // After render
  16323. if (this.afterRender) {
  16324. this.afterRender();
  16325. }
  16326. this.onAfterRenderObservable.notifyObservers(this);
  16327. // Cleaning
  16328. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16329. this._toBeDisposed.data[index].dispose();
  16330. this._toBeDisposed[index] = null;
  16331. }
  16332. this._toBeDisposed.reset();
  16333. if (this.dumpNextRenderTargets) {
  16334. this.dumpNextRenderTargets = false;
  16335. }
  16336. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16337. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  16338. };
  16339. Scene.prototype._updateAudioParameters = function () {
  16340. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16341. return;
  16342. }
  16343. var listeningCamera;
  16344. var audioEngine = BABYLON.Engine.audioEngine;
  16345. if (this.activeCameras.length > 0) {
  16346. listeningCamera = this.activeCameras[0];
  16347. }
  16348. else {
  16349. listeningCamera = this.activeCamera;
  16350. }
  16351. if (listeningCamera && audioEngine.canUseWebAudio) {
  16352. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16353. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16354. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16355. cameraDirection.normalize();
  16356. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16357. var i;
  16358. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16359. var sound = this.mainSoundTrack.soundCollection[i];
  16360. if (sound.useCustomAttenuation) {
  16361. sound.updateDistanceFromListener();
  16362. }
  16363. }
  16364. for (i = 0; i < this.soundTracks.length; i++) {
  16365. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16366. sound = this.soundTracks[i].soundCollection[j];
  16367. if (sound.useCustomAttenuation) {
  16368. sound.updateDistanceFromListener();
  16369. }
  16370. }
  16371. }
  16372. }
  16373. };
  16374. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16375. // Audio
  16376. get: function () {
  16377. return this._audioEnabled;
  16378. },
  16379. set: function (value) {
  16380. this._audioEnabled = value;
  16381. if (BABYLON.AudioEngine) {
  16382. if (this._audioEnabled) {
  16383. this._enableAudio();
  16384. }
  16385. else {
  16386. this._disableAudio();
  16387. }
  16388. }
  16389. },
  16390. enumerable: true,
  16391. configurable: true
  16392. });
  16393. Scene.prototype._disableAudio = function () {
  16394. var i;
  16395. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16396. this.mainSoundTrack.soundCollection[i].pause();
  16397. }
  16398. for (i = 0; i < this.soundTracks.length; i++) {
  16399. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16400. this.soundTracks[i].soundCollection[j].pause();
  16401. }
  16402. }
  16403. };
  16404. Scene.prototype._enableAudio = function () {
  16405. var i;
  16406. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16407. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16408. this.mainSoundTrack.soundCollection[i].play();
  16409. }
  16410. }
  16411. for (i = 0; i < this.soundTracks.length; i++) {
  16412. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16413. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16414. this.soundTracks[i].soundCollection[j].play();
  16415. }
  16416. }
  16417. }
  16418. };
  16419. Object.defineProperty(Scene.prototype, "headphone", {
  16420. get: function () {
  16421. return this._headphone;
  16422. },
  16423. set: function (value) {
  16424. this._headphone = value;
  16425. if (BABYLON.AudioEngine) {
  16426. if (this._headphone) {
  16427. this._switchAudioModeForHeadphones();
  16428. }
  16429. else {
  16430. this._switchAudioModeForNormalSpeakers();
  16431. }
  16432. }
  16433. },
  16434. enumerable: true,
  16435. configurable: true
  16436. });
  16437. Scene.prototype._switchAudioModeForHeadphones = function () {
  16438. this.mainSoundTrack.switchPanningModelToHRTF();
  16439. for (var i = 0; i < this.soundTracks.length; i++) {
  16440. this.soundTracks[i].switchPanningModelToHRTF();
  16441. }
  16442. };
  16443. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16444. this.mainSoundTrack.switchPanningModelToEqualPower();
  16445. for (var i = 0; i < this.soundTracks.length; i++) {
  16446. this.soundTracks[i].switchPanningModelToEqualPower();
  16447. }
  16448. };
  16449. Scene.prototype.enableDepthRenderer = function () {
  16450. if (this._depthRenderer) {
  16451. return this._depthRenderer;
  16452. }
  16453. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16454. return this._depthRenderer;
  16455. };
  16456. Scene.prototype.disableDepthRenderer = function () {
  16457. if (!this._depthRenderer) {
  16458. return;
  16459. }
  16460. this._depthRenderer.dispose();
  16461. this._depthRenderer = null;
  16462. };
  16463. Scene.prototype.freezeMaterials = function () {
  16464. for (var i = 0; i < this.materials.length; i++) {
  16465. this.materials[i].freeze();
  16466. }
  16467. };
  16468. Scene.prototype.unfreezeMaterials = function () {
  16469. for (var i = 0; i < this.materials.length; i++) {
  16470. this.materials[i].unfreeze();
  16471. }
  16472. };
  16473. Scene.prototype.dispose = function () {
  16474. this.beforeRender = null;
  16475. this.afterRender = null;
  16476. this.skeletons = [];
  16477. this._boundingBoxRenderer.dispose();
  16478. if (this._depthRenderer) {
  16479. this._depthRenderer.dispose();
  16480. }
  16481. // Debug layer
  16482. if (this._debugLayer) {
  16483. this._debugLayer.hide();
  16484. }
  16485. // Events
  16486. this.onDisposeObservable.notifyObservers(this);
  16487. this.onDisposeObservable.clear();
  16488. this.onBeforeRenderObservable.clear();
  16489. this.onAfterRenderObservable.clear();
  16490. this.detachControl();
  16491. // Release sounds & sounds tracks
  16492. if (BABYLON.AudioEngine) {
  16493. this.disposeSounds();
  16494. }
  16495. // Detach cameras
  16496. var canvas = this._engine.getRenderingCanvas();
  16497. var index;
  16498. for (index = 0; index < this.cameras.length; index++) {
  16499. this.cameras[index].detachControl(canvas);
  16500. }
  16501. // Release lights
  16502. while (this.lights.length) {
  16503. this.lights[0].dispose();
  16504. }
  16505. // Release meshes
  16506. while (this.meshes.length) {
  16507. this.meshes[0].dispose(true);
  16508. }
  16509. // Release cameras
  16510. while (this.cameras.length) {
  16511. this.cameras[0].dispose();
  16512. }
  16513. // Release materials
  16514. while (this.materials.length) {
  16515. this.materials[0].dispose();
  16516. }
  16517. // Release particles
  16518. while (this.particleSystems.length) {
  16519. this.particleSystems[0].dispose();
  16520. }
  16521. // Release sprites
  16522. while (this.spriteManagers.length) {
  16523. this.spriteManagers[0].dispose();
  16524. }
  16525. // Release layers
  16526. while (this.layers.length) {
  16527. this.layers[0].dispose();
  16528. }
  16529. // Release textures
  16530. while (this.textures.length) {
  16531. this.textures[0].dispose();
  16532. }
  16533. // Post-processes
  16534. this.postProcessManager.dispose();
  16535. // Physics
  16536. if (this._physicsEngine) {
  16537. this.disablePhysicsEngine();
  16538. }
  16539. // Remove from engine
  16540. index = this._engine.scenes.indexOf(this);
  16541. if (index > -1) {
  16542. this._engine.scenes.splice(index, 1);
  16543. }
  16544. this._engine.wipeCaches();
  16545. };
  16546. // Release sounds & sounds tracks
  16547. Scene.prototype.disposeSounds = function () {
  16548. this.mainSoundTrack.dispose();
  16549. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16550. this.soundTracks[scIndex].dispose();
  16551. }
  16552. };
  16553. // Octrees
  16554. Scene.prototype.getWorldExtends = function () {
  16555. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16556. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16557. for (var index = 0; index < this.meshes.length; index++) {
  16558. var mesh = this.meshes[index];
  16559. mesh.computeWorldMatrix(true);
  16560. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16561. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16562. BABYLON.Tools.CheckExtends(minBox, min, max);
  16563. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16564. }
  16565. return {
  16566. min: min,
  16567. max: max
  16568. };
  16569. };
  16570. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16571. if (maxCapacity === void 0) { maxCapacity = 64; }
  16572. if (maxDepth === void 0) { maxDepth = 2; }
  16573. if (!this._selectionOctree) {
  16574. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16575. }
  16576. var worldExtends = this.getWorldExtends();
  16577. // Update octree
  16578. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16579. return this._selectionOctree;
  16580. };
  16581. // Picking
  16582. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16583. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16584. var engine = this._engine;
  16585. if (!camera) {
  16586. if (!this.activeCamera)
  16587. throw new Error("Active camera not set");
  16588. camera = this.activeCamera;
  16589. }
  16590. var cameraViewport = camera.viewport;
  16591. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16592. // Moving coordinates to local viewport world
  16593. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16594. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16595. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16596. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16597. };
  16598. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16599. var engine = this._engine;
  16600. if (!camera) {
  16601. if (!this.activeCamera)
  16602. throw new Error("Active camera not set");
  16603. camera = this.activeCamera;
  16604. }
  16605. var cameraViewport = camera.viewport;
  16606. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16607. var identity = BABYLON.Matrix.Identity();
  16608. // Moving coordinates to local viewport world
  16609. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16610. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16611. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16612. };
  16613. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16614. var pickingInfo = null;
  16615. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16616. var mesh = this.meshes[meshIndex];
  16617. if (predicate) {
  16618. if (!predicate(mesh)) {
  16619. continue;
  16620. }
  16621. }
  16622. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16623. continue;
  16624. }
  16625. var world = mesh.getWorldMatrix();
  16626. var ray = rayFunction(world);
  16627. var result = mesh.intersects(ray, fastCheck);
  16628. if (!result || !result.hit)
  16629. continue;
  16630. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16631. continue;
  16632. pickingInfo = result;
  16633. if (fastCheck) {
  16634. break;
  16635. }
  16636. }
  16637. return pickingInfo || new BABYLON.PickingInfo();
  16638. };
  16639. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16640. var pickingInfo = null;
  16641. camera = camera || this.activeCamera;
  16642. if (this.spriteManagers.length > 0) {
  16643. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16644. var spriteManager = this.spriteManagers[spriteIndex];
  16645. if (!spriteManager.isPickable) {
  16646. continue;
  16647. }
  16648. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16649. if (!result || !result.hit)
  16650. continue;
  16651. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16652. continue;
  16653. pickingInfo = result;
  16654. if (fastCheck) {
  16655. break;
  16656. }
  16657. }
  16658. }
  16659. return pickingInfo || new BABYLON.PickingInfo();
  16660. };
  16661. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16662. var _this = this;
  16663. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16664. /// <param name="x">X position on screen</param>
  16665. /// <param name="y">Y position on screen</param>
  16666. /// <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>
  16667. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16668. /// <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>
  16669. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16670. };
  16671. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16672. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16673. /// <param name="x">X position on screen</param>
  16674. /// <param name="y">Y position on screen</param>
  16675. /// <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>
  16676. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16677. /// <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>
  16678. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16679. };
  16680. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16681. var _this = this;
  16682. return this._internalPick(function (world) {
  16683. if (!_this._pickWithRayInverseMatrix) {
  16684. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16685. }
  16686. world.invertToRef(_this._pickWithRayInverseMatrix);
  16687. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16688. }, predicate, fastCheck);
  16689. };
  16690. Scene.prototype.setPointerOverMesh = function (mesh) {
  16691. if (this._pointerOverMesh === mesh) {
  16692. return;
  16693. }
  16694. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16695. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16696. }
  16697. this._pointerOverMesh = mesh;
  16698. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16699. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16700. }
  16701. };
  16702. Scene.prototype.getPointerOverMesh = function () {
  16703. return this._pointerOverMesh;
  16704. };
  16705. Scene.prototype.setPointerOverSprite = function (sprite) {
  16706. if (this._pointerOverSprite === sprite) {
  16707. return;
  16708. }
  16709. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16710. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16711. }
  16712. this._pointerOverSprite = sprite;
  16713. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16714. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16715. }
  16716. };
  16717. Scene.prototype.getPointerOverSprite = function () {
  16718. return this._pointerOverSprite;
  16719. };
  16720. // Physics
  16721. Scene.prototype.getPhysicsEngine = function () {
  16722. return this._physicsEngine;
  16723. };
  16724. /**
  16725. * Enables physics to the current scene
  16726. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16727. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16728. * @return {boolean} was the physics engine initialized
  16729. */
  16730. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16731. if (this._physicsEngine) {
  16732. return true;
  16733. }
  16734. try {
  16735. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16736. return true;
  16737. }
  16738. catch (e) {
  16739. BABYLON.Tools.Error(e.message);
  16740. return false;
  16741. }
  16742. };
  16743. Scene.prototype.disablePhysicsEngine = function () {
  16744. if (!this._physicsEngine) {
  16745. return;
  16746. }
  16747. this._physicsEngine.dispose();
  16748. this._physicsEngine = undefined;
  16749. };
  16750. Scene.prototype.isPhysicsEnabled = function () {
  16751. return this._physicsEngine !== undefined;
  16752. };
  16753. /**
  16754. *
  16755. * Sets the gravity of the physics engine (and NOT of the scene)
  16756. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16757. */
  16758. Scene.prototype.setGravity = function (gravity) {
  16759. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16760. if (!this._physicsEngine) {
  16761. return;
  16762. }
  16763. this._physicsEngine.setGravity(gravity);
  16764. };
  16765. /**
  16766. * Legacy support, using the new API
  16767. * @Deprecated
  16768. */
  16769. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16770. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16771. if (parts.parts) {
  16772. options = parts;
  16773. parts = parts.parts;
  16774. }
  16775. var mainMesh = parts[0].mesh;
  16776. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16777. for (var index = 1; index < parts.length; index++) {
  16778. var mesh = parts[index].mesh;
  16779. if (mesh.parent !== mainMesh) {
  16780. mesh.position = mesh.position.subtract(mainMesh.position);
  16781. mesh.parent = mainMesh;
  16782. }
  16783. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16784. }
  16785. mainMesh.physicsImpostor.forceUpdate();
  16786. };
  16787. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16788. var mesh = compound.parts[0].mesh;
  16789. mesh.physicsImpostor.dispose();
  16790. mesh.physicsImpostor = null;
  16791. };
  16792. // Misc.
  16793. Scene.prototype.createDefaultCameraOrLight = function () {
  16794. // Light
  16795. if (this.lights.length === 0) {
  16796. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16797. }
  16798. // Camera
  16799. if (!this.activeCamera) {
  16800. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16801. // Compute position
  16802. var worldExtends = this.getWorldExtends();
  16803. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16804. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16805. camera.setTarget(worldCenter);
  16806. this.activeCamera = camera;
  16807. }
  16808. };
  16809. // Tags
  16810. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16811. if (tagsQuery === undefined) {
  16812. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16813. return list;
  16814. }
  16815. var listByTags = [];
  16816. forEach = forEach || (function (item) { return; });
  16817. for (var i in list) {
  16818. var item = list[i];
  16819. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16820. listByTags.push(item);
  16821. forEach(item);
  16822. }
  16823. }
  16824. return listByTags;
  16825. };
  16826. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16827. return this._getByTags(this.meshes, tagsQuery, forEach);
  16828. };
  16829. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16830. return this._getByTags(this.cameras, tagsQuery, forEach);
  16831. };
  16832. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16833. return this._getByTags(this.lights, tagsQuery, forEach);
  16834. };
  16835. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16836. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16837. };
  16838. // Statics
  16839. Scene._FOGMODE_NONE = 0;
  16840. Scene._FOGMODE_EXP = 1;
  16841. Scene._FOGMODE_EXP2 = 2;
  16842. Scene._FOGMODE_LINEAR = 3;
  16843. Scene.MinDeltaTime = 1.0;
  16844. Scene.MaxDeltaTime = 1000.0;
  16845. return Scene;
  16846. })();
  16847. BABYLON.Scene = Scene;
  16848. })(BABYLON || (BABYLON = {}));
  16849. var BABYLON;
  16850. (function (BABYLON) {
  16851. var VertexBuffer = (function () {
  16852. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16853. if (engine instanceof BABYLON.Mesh) {
  16854. this._engine = engine.getScene().getEngine();
  16855. }
  16856. else {
  16857. this._engine = engine;
  16858. }
  16859. this._updatable = updatable;
  16860. this._data = data;
  16861. if (!postponeInternalCreation) {
  16862. this.create();
  16863. }
  16864. this._kind = kind;
  16865. if (stride) {
  16866. this._strideSize = stride;
  16867. return;
  16868. }
  16869. // Deduce stride from kind
  16870. switch (kind) {
  16871. case VertexBuffer.PositionKind:
  16872. this._strideSize = 3;
  16873. break;
  16874. case VertexBuffer.NormalKind:
  16875. this._strideSize = 3;
  16876. break;
  16877. case VertexBuffer.UVKind:
  16878. case VertexBuffer.UV2Kind:
  16879. case VertexBuffer.UV3Kind:
  16880. case VertexBuffer.UV4Kind:
  16881. case VertexBuffer.UV5Kind:
  16882. case VertexBuffer.UV6Kind:
  16883. this._strideSize = 2;
  16884. break;
  16885. case VertexBuffer.ColorKind:
  16886. this._strideSize = 4;
  16887. break;
  16888. case VertexBuffer.MatricesIndicesKind:
  16889. case VertexBuffer.MatricesIndicesExtraKind:
  16890. this._strideSize = 4;
  16891. break;
  16892. case VertexBuffer.MatricesWeightsKind:
  16893. case VertexBuffer.MatricesWeightsExtraKind:
  16894. this._strideSize = 4;
  16895. break;
  16896. }
  16897. }
  16898. // Properties
  16899. VertexBuffer.prototype.isUpdatable = function () {
  16900. return this._updatable;
  16901. };
  16902. VertexBuffer.prototype.getData = function () {
  16903. return this._data;
  16904. };
  16905. VertexBuffer.prototype.getBuffer = function () {
  16906. return this._buffer;
  16907. };
  16908. VertexBuffer.prototype.getStrideSize = function () {
  16909. return this._strideSize;
  16910. };
  16911. // Methods
  16912. VertexBuffer.prototype.create = function (data) {
  16913. if (!data && this._buffer) {
  16914. return; // nothing to do
  16915. }
  16916. data = data || this._data;
  16917. if (!this._buffer) {
  16918. if (this._updatable) {
  16919. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16920. }
  16921. else {
  16922. this._buffer = this._engine.createVertexBuffer(data);
  16923. }
  16924. }
  16925. if (this._updatable) {
  16926. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16927. this._data = data;
  16928. }
  16929. };
  16930. VertexBuffer.prototype.update = function (data) {
  16931. this.create(data);
  16932. };
  16933. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16934. if (!this._buffer) {
  16935. return;
  16936. }
  16937. if (this._updatable) {
  16938. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16939. this._data = null;
  16940. }
  16941. };
  16942. VertexBuffer.prototype.dispose = function () {
  16943. if (!this._buffer) {
  16944. return;
  16945. }
  16946. if (this._engine._releaseBuffer(this._buffer)) {
  16947. this._buffer = null;
  16948. }
  16949. };
  16950. Object.defineProperty(VertexBuffer, "PositionKind", {
  16951. get: function () {
  16952. return VertexBuffer._PositionKind;
  16953. },
  16954. enumerable: true,
  16955. configurable: true
  16956. });
  16957. Object.defineProperty(VertexBuffer, "NormalKind", {
  16958. get: function () {
  16959. return VertexBuffer._NormalKind;
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(VertexBuffer, "UVKind", {
  16965. get: function () {
  16966. return VertexBuffer._UVKind;
  16967. },
  16968. enumerable: true,
  16969. configurable: true
  16970. });
  16971. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16972. get: function () {
  16973. return VertexBuffer._UV2Kind;
  16974. },
  16975. enumerable: true,
  16976. configurable: true
  16977. });
  16978. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16979. get: function () {
  16980. return VertexBuffer._UV3Kind;
  16981. },
  16982. enumerable: true,
  16983. configurable: true
  16984. });
  16985. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16986. get: function () {
  16987. return VertexBuffer._UV4Kind;
  16988. },
  16989. enumerable: true,
  16990. configurable: true
  16991. });
  16992. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16993. get: function () {
  16994. return VertexBuffer._UV5Kind;
  16995. },
  16996. enumerable: true,
  16997. configurable: true
  16998. });
  16999. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17000. get: function () {
  17001. return VertexBuffer._UV6Kind;
  17002. },
  17003. enumerable: true,
  17004. configurable: true
  17005. });
  17006. Object.defineProperty(VertexBuffer, "ColorKind", {
  17007. get: function () {
  17008. return VertexBuffer._ColorKind;
  17009. },
  17010. enumerable: true,
  17011. configurable: true
  17012. });
  17013. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17014. get: function () {
  17015. return VertexBuffer._MatricesIndicesKind;
  17016. },
  17017. enumerable: true,
  17018. configurable: true
  17019. });
  17020. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17021. get: function () {
  17022. return VertexBuffer._MatricesWeightsKind;
  17023. },
  17024. enumerable: true,
  17025. configurable: true
  17026. });
  17027. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17028. get: function () {
  17029. return VertexBuffer._MatricesIndicesExtraKind;
  17030. },
  17031. enumerable: true,
  17032. configurable: true
  17033. });
  17034. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17035. get: function () {
  17036. return VertexBuffer._MatricesWeightsExtraKind;
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. // Enums
  17042. VertexBuffer._PositionKind = "position";
  17043. VertexBuffer._NormalKind = "normal";
  17044. VertexBuffer._UVKind = "uv";
  17045. VertexBuffer._UV2Kind = "uv2";
  17046. VertexBuffer._UV3Kind = "uv3";
  17047. VertexBuffer._UV4Kind = "uv4";
  17048. VertexBuffer._UV5Kind = "uv5";
  17049. VertexBuffer._UV6Kind = "uv6";
  17050. VertexBuffer._ColorKind = "color";
  17051. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17052. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17053. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17054. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17055. return VertexBuffer;
  17056. })();
  17057. BABYLON.VertexBuffer = VertexBuffer;
  17058. })(BABYLON || (BABYLON = {}));
  17059. var BABYLON;
  17060. (function (BABYLON) {
  17061. /**
  17062. * Creates an instance based on a source mesh.
  17063. */
  17064. var InstancedMesh = (function (_super) {
  17065. __extends(InstancedMesh, _super);
  17066. function InstancedMesh(name, source) {
  17067. _super.call(this, name, source.getScene());
  17068. source.instances.push(this);
  17069. this._sourceMesh = source;
  17070. this.position.copyFrom(source.position);
  17071. this.rotation.copyFrom(source.rotation);
  17072. this.scaling.copyFrom(source.scaling);
  17073. if (source.rotationQuaternion) {
  17074. this.rotationQuaternion = source.rotationQuaternion.clone();
  17075. }
  17076. this.infiniteDistance = source.infiniteDistance;
  17077. this.setPivotMatrix(source.getPivotMatrix());
  17078. this.refreshBoundingInfo();
  17079. this._syncSubMeshes();
  17080. }
  17081. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  17082. // Methods
  17083. get: function () {
  17084. return this._sourceMesh.receiveShadows;
  17085. },
  17086. enumerable: true,
  17087. configurable: true
  17088. });
  17089. Object.defineProperty(InstancedMesh.prototype, "material", {
  17090. get: function () {
  17091. return this._sourceMesh.material;
  17092. },
  17093. enumerable: true,
  17094. configurable: true
  17095. });
  17096. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  17097. get: function () {
  17098. return this._sourceMesh.visibility;
  17099. },
  17100. enumerable: true,
  17101. configurable: true
  17102. });
  17103. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  17104. get: function () {
  17105. return this._sourceMesh.skeleton;
  17106. },
  17107. enumerable: true,
  17108. configurable: true
  17109. });
  17110. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  17111. get: function () {
  17112. return this._sourceMesh.renderingGroupId;
  17113. },
  17114. enumerable: true,
  17115. configurable: true
  17116. });
  17117. InstancedMesh.prototype.getTotalVertices = function () {
  17118. return this._sourceMesh.getTotalVertices();
  17119. };
  17120. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  17121. get: function () {
  17122. return this._sourceMesh;
  17123. },
  17124. enumerable: true,
  17125. configurable: true
  17126. });
  17127. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17128. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  17129. };
  17130. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  17131. return this._sourceMesh.isVerticesDataPresent(kind);
  17132. };
  17133. InstancedMesh.prototype.getIndices = function () {
  17134. return this._sourceMesh.getIndices();
  17135. };
  17136. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  17137. get: function () {
  17138. return this._sourceMesh._positions;
  17139. },
  17140. enumerable: true,
  17141. configurable: true
  17142. });
  17143. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17144. var meshBB = this._sourceMesh.getBoundingInfo();
  17145. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17146. this._updateBoundingInfo();
  17147. };
  17148. InstancedMesh.prototype._preActivate = function () {
  17149. if (this._currentLOD) {
  17150. this._currentLOD._preActivate();
  17151. }
  17152. };
  17153. InstancedMesh.prototype._activate = function (renderId) {
  17154. if (this._currentLOD) {
  17155. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17156. }
  17157. };
  17158. InstancedMesh.prototype.getLOD = function (camera) {
  17159. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17160. if (this._currentLOD === this.sourceMesh) {
  17161. return this;
  17162. }
  17163. return this._currentLOD;
  17164. };
  17165. InstancedMesh.prototype._syncSubMeshes = function () {
  17166. this.releaseSubMeshes();
  17167. if (this._sourceMesh.subMeshes) {
  17168. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17169. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17170. }
  17171. }
  17172. };
  17173. InstancedMesh.prototype._generatePointsArray = function () {
  17174. return this._sourceMesh._generatePointsArray();
  17175. };
  17176. // Clone
  17177. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17178. var result = this._sourceMesh.createInstance(name);
  17179. // Deep copy
  17180. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17181. // Bounding info
  17182. this.refreshBoundingInfo();
  17183. // Parent
  17184. if (newParent) {
  17185. result.parent = newParent;
  17186. }
  17187. if (!doNotCloneChildren) {
  17188. // Children
  17189. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17190. var mesh = this.getScene().meshes[index];
  17191. if (mesh.parent === this) {
  17192. mesh.clone(mesh.name, result);
  17193. }
  17194. }
  17195. }
  17196. result.computeWorldMatrix(true);
  17197. return result;
  17198. };
  17199. // Dispoe
  17200. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17201. // Remove from mesh
  17202. var index = this._sourceMesh.instances.indexOf(this);
  17203. this._sourceMesh.instances.splice(index, 1);
  17204. _super.prototype.dispose.call(this, doNotRecurse);
  17205. };
  17206. return InstancedMesh;
  17207. })(BABYLON.AbstractMesh);
  17208. BABYLON.InstancedMesh = InstancedMesh;
  17209. })(BABYLON || (BABYLON = {}));
  17210. var BABYLON;
  17211. (function (BABYLON) {
  17212. var _InstancesBatch = (function () {
  17213. function _InstancesBatch() {
  17214. this.mustReturn = false;
  17215. this.visibleInstances = new Array();
  17216. this.renderSelf = new Array();
  17217. }
  17218. return _InstancesBatch;
  17219. })();
  17220. BABYLON._InstancesBatch = _InstancesBatch;
  17221. var Mesh = (function (_super) {
  17222. __extends(Mesh, _super);
  17223. /**
  17224. * @constructor
  17225. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  17226. * @param {Scene} scene - The scene to add this mesh to.
  17227. * @param {Node} parent - The parent of this mesh, if it has one
  17228. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  17229. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  17230. * When false, achieved by calling a clone(), also passing False.
  17231. * This will make creation of children, recursive.
  17232. */
  17233. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17234. if (parent === void 0) { parent = null; }
  17235. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17236. _super.call(this, name, scene);
  17237. // Events
  17238. /**
  17239. * An event triggered before rendering the mesh
  17240. * @type {BABYLON.Observable}
  17241. */
  17242. this.onBeforeRenderObservable = new BABYLON.Observable();
  17243. /**
  17244. * An event triggered after rendering the mesh
  17245. * @type {BABYLON.Observable}
  17246. */
  17247. this.onAfterRenderObservable = new BABYLON.Observable();
  17248. /**
  17249. * An event triggered before drawing the mesh
  17250. * @type {BABYLON.Observable}
  17251. */
  17252. this.onBeforeDrawObservable = new BABYLON.Observable();
  17253. // Members
  17254. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17255. this.instances = new Array();
  17256. this._LODLevels = new Array();
  17257. this._visibleInstances = {};
  17258. this._renderIdForInstances = new Array();
  17259. this._batchCache = new _InstancesBatch();
  17260. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17261. this._sideOrientation = Mesh._DEFAULTSIDE;
  17262. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17263. if (source) {
  17264. // Geometry
  17265. if (source._geometry) {
  17266. source._geometry.applyToMesh(this);
  17267. }
  17268. // Deep copy
  17269. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17270. // Pivot
  17271. this.setPivotMatrix(source.getPivotMatrix());
  17272. this.id = name + "." + source.id;
  17273. // Material
  17274. this.material = source.material;
  17275. var index;
  17276. if (!doNotCloneChildren) {
  17277. // Children
  17278. for (index = 0; index < scene.meshes.length; index++) {
  17279. var mesh = scene.meshes[index];
  17280. if (mesh.parent === source) {
  17281. // doNotCloneChildren is always going to be False
  17282. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17283. }
  17284. }
  17285. }
  17286. // Physics clone
  17287. var physicsEngine = this.getScene().getPhysicsEngine();
  17288. if (clonePhysicsImpostor && physicsEngine) {
  17289. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17290. if (impostor) {
  17291. this.physicsImpostor = impostor.clone(this);
  17292. }
  17293. }
  17294. // Particles
  17295. for (index = 0; index < scene.particleSystems.length; index++) {
  17296. var system = scene.particleSystems[index];
  17297. if (system.emitter === source) {
  17298. system.clone(system.name, this);
  17299. }
  17300. }
  17301. this.computeWorldMatrix(true);
  17302. }
  17303. // Parent
  17304. if (parent !== null) {
  17305. this.parent = parent;
  17306. }
  17307. }
  17308. Object.defineProperty(Mesh, "FRONTSIDE", {
  17309. /**
  17310. * Mesh side orientation : usually the external or front surface
  17311. */
  17312. get: function () {
  17313. return Mesh._FRONTSIDE;
  17314. },
  17315. enumerable: true,
  17316. configurable: true
  17317. });
  17318. Object.defineProperty(Mesh, "BACKSIDE", {
  17319. /**
  17320. * Mesh side orientation : usually the internal or back surface
  17321. */
  17322. get: function () {
  17323. return Mesh._BACKSIDE;
  17324. },
  17325. enumerable: true,
  17326. configurable: true
  17327. });
  17328. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17329. /**
  17330. * Mesh side orientation : both internal and external or front and back surfaces
  17331. */
  17332. get: function () {
  17333. return Mesh._DOUBLESIDE;
  17334. },
  17335. enumerable: true,
  17336. configurable: true
  17337. });
  17338. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17339. /**
  17340. * Mesh side orientation : by default, `FRONTSIDE`
  17341. */
  17342. get: function () {
  17343. return Mesh._DEFAULTSIDE;
  17344. },
  17345. enumerable: true,
  17346. configurable: true
  17347. });
  17348. Object.defineProperty(Mesh, "NO_CAP", {
  17349. /**
  17350. * Mesh cap setting : no cap
  17351. */
  17352. get: function () {
  17353. return Mesh._NO_CAP;
  17354. },
  17355. enumerable: true,
  17356. configurable: true
  17357. });
  17358. Object.defineProperty(Mesh, "CAP_START", {
  17359. /**
  17360. * Mesh cap setting : one cap at the beginning of the mesh
  17361. */
  17362. get: function () {
  17363. return Mesh._CAP_START;
  17364. },
  17365. enumerable: true,
  17366. configurable: true
  17367. });
  17368. Object.defineProperty(Mesh, "CAP_END", {
  17369. /**
  17370. * Mesh cap setting : one cap at the end of the mesh
  17371. */
  17372. get: function () {
  17373. return Mesh._CAP_END;
  17374. },
  17375. enumerable: true,
  17376. configurable: true
  17377. });
  17378. Object.defineProperty(Mesh, "CAP_ALL", {
  17379. /**
  17380. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  17381. */
  17382. get: function () {
  17383. return Mesh._CAP_ALL;
  17384. },
  17385. enumerable: true,
  17386. configurable: true
  17387. });
  17388. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  17389. set: function (callback) {
  17390. if (this._onBeforeDrawObserver) {
  17391. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  17392. }
  17393. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  17394. },
  17395. enumerable: true,
  17396. configurable: true
  17397. });
  17398. // Methods
  17399. /**
  17400. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17401. */
  17402. Mesh.prototype.toString = function (fullDetails) {
  17403. var ret = _super.prototype.toString.call(this, fullDetails);
  17404. ret += ", n vertices: " + this.getTotalVertices();
  17405. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  17406. if (this.animations) {
  17407. for (var i = 0; i < this.animations.length; i++) {
  17408. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17409. }
  17410. }
  17411. if (fullDetails) {
  17412. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  17413. }
  17414. return ret;
  17415. };
  17416. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  17417. get: function () {
  17418. return this._LODLevels.length > 0;
  17419. },
  17420. enumerable: true,
  17421. configurable: true
  17422. });
  17423. Mesh.prototype._sortLODLevels = function () {
  17424. this._LODLevels.sort(function (a, b) {
  17425. if (a.distance < b.distance) {
  17426. return 1;
  17427. }
  17428. if (a.distance > b.distance) {
  17429. return -1;
  17430. }
  17431. return 0;
  17432. });
  17433. };
  17434. /**
  17435. * Add a mesh as LOD level triggered at the given distance.
  17436. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17437. * @param {number} distance - the distance from the center of the object to show this level
  17438. * @param {Mesh} mesh - the mesh to be added as LOD level
  17439. * @return {Mesh} this mesh (for chaining)
  17440. */
  17441. Mesh.prototype.addLODLevel = function (distance, mesh) {
  17442. if (mesh && mesh._masterMesh) {
  17443. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  17444. return this;
  17445. }
  17446. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  17447. this._LODLevels.push(level);
  17448. if (mesh) {
  17449. mesh._masterMesh = this;
  17450. }
  17451. this._sortLODLevels();
  17452. return this;
  17453. };
  17454. /**
  17455. * Returns the LOD level mesh at the passed distance or null if not found.
  17456. * It is related to the method `addLODLevel(distance, mesh)`.
  17457. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17458. */
  17459. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  17460. for (var index = 0; index < this._LODLevels.length; index++) {
  17461. var level = this._LODLevels[index];
  17462. if (level.distance === distance) {
  17463. return level.mesh;
  17464. }
  17465. }
  17466. return null;
  17467. };
  17468. /**
  17469. * Remove a mesh from the LOD array
  17470. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17471. * @param {Mesh} mesh - the mesh to be removed.
  17472. * @return {Mesh} this mesh (for chaining)
  17473. */
  17474. Mesh.prototype.removeLODLevel = function (mesh) {
  17475. for (var index = 0; index < this._LODLevels.length; index++) {
  17476. if (this._LODLevels[index].mesh === mesh) {
  17477. this._LODLevels.splice(index, 1);
  17478. if (mesh) {
  17479. mesh._masterMesh = null;
  17480. }
  17481. }
  17482. }
  17483. this._sortLODLevels();
  17484. return this;
  17485. };
  17486. /**
  17487. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17488. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17489. */
  17490. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17491. if (!this._LODLevels || this._LODLevels.length === 0) {
  17492. return this;
  17493. }
  17494. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  17495. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  17496. if (this.onLODLevelSelection) {
  17497. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  17498. }
  17499. return this;
  17500. }
  17501. for (var index = 0; index < this._LODLevels.length; index++) {
  17502. var level = this._LODLevels[index];
  17503. if (level.distance < distanceToCamera) {
  17504. if (level.mesh) {
  17505. level.mesh._preActivate();
  17506. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17507. }
  17508. if (this.onLODLevelSelection) {
  17509. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  17510. }
  17511. return level.mesh;
  17512. }
  17513. }
  17514. if (this.onLODLevelSelection) {
  17515. this.onLODLevelSelection(distanceToCamera, this, this);
  17516. }
  17517. return this;
  17518. };
  17519. Object.defineProperty(Mesh.prototype, "geometry", {
  17520. /**
  17521. * Returns the mesh internal `Geometry` object.
  17522. */
  17523. get: function () {
  17524. return this._geometry;
  17525. },
  17526. enumerable: true,
  17527. configurable: true
  17528. });
  17529. /**
  17530. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17531. */
  17532. Mesh.prototype.getTotalVertices = function () {
  17533. if (!this._geometry) {
  17534. return 0;
  17535. }
  17536. return this._geometry.getTotalVertices();
  17537. };
  17538. /**
  17539. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17540. * 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.
  17541. * Returns null if the mesh has no geometry or no vertex buffer.
  17542. * Possible `kind` values :
  17543. * - BABYLON.VertexBuffer.PositionKind
  17544. * - BABYLON.VertexBuffer.UVKind
  17545. * - BABYLON.VertexBuffer.UV2Kind
  17546. * - BABYLON.VertexBuffer.UV3Kind
  17547. * - BABYLON.VertexBuffer.UV4Kind
  17548. * - BABYLON.VertexBuffer.UV5Kind
  17549. * - BABYLON.VertexBuffer.UV6Kind
  17550. * - BABYLON.VertexBuffer.ColorKind
  17551. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17552. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17553. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17554. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17555. */
  17556. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17557. if (!this._geometry) {
  17558. return null;
  17559. }
  17560. return this._geometry.getVerticesData(kind, copyWhenShared);
  17561. };
  17562. /**
  17563. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  17564. * Returns `undefined` if the mesh has no geometry.
  17565. * Possible `kind` values :
  17566. * - BABYLON.VertexBuffer.PositionKind
  17567. * - BABYLON.VertexBuffer.UVKind
  17568. * - BABYLON.VertexBuffer.UV2Kind
  17569. * - BABYLON.VertexBuffer.UV3Kind
  17570. * - BABYLON.VertexBuffer.UV4Kind
  17571. * - BABYLON.VertexBuffer.UV5Kind
  17572. * - BABYLON.VertexBuffer.UV6Kind
  17573. * - BABYLON.VertexBuffer.ColorKind
  17574. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17575. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17576. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17577. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17578. */
  17579. Mesh.prototype.getVertexBuffer = function (kind) {
  17580. if (!this._geometry) {
  17581. return undefined;
  17582. }
  17583. return this._geometry.getVertexBuffer(kind);
  17584. };
  17585. /**
  17586. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17587. * Possible `kind` values :
  17588. * - BABYLON.VertexBuffer.PositionKind
  17589. * - BABYLON.VertexBuffer.UVKind
  17590. * - BABYLON.VertexBuffer.UV2Kind
  17591. * - BABYLON.VertexBuffer.UV3Kind
  17592. * - BABYLON.VertexBuffer.UV4Kind
  17593. * - BABYLON.VertexBuffer.UV5Kind
  17594. * - BABYLON.VertexBuffer.UV6Kind
  17595. * - BABYLON.VertexBuffer.ColorKind
  17596. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17597. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17598. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17599. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17600. */
  17601. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17602. if (!this._geometry) {
  17603. if (this._delayInfo) {
  17604. return this._delayInfo.indexOf(kind) !== -1;
  17605. }
  17606. return false;
  17607. }
  17608. return this._geometry.isVerticesDataPresent(kind);
  17609. };
  17610. /**
  17611. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17612. * Possible `kind` values :
  17613. * - BABYLON.VertexBuffer.PositionKind
  17614. * - BABYLON.VertexBuffer.UVKind
  17615. * - BABYLON.VertexBuffer.UV2Kind
  17616. * - BABYLON.VertexBuffer.UV3Kind
  17617. * - BABYLON.VertexBuffer.UV4Kind
  17618. * - BABYLON.VertexBuffer.UV5Kind
  17619. * - BABYLON.VertexBuffer.UV6Kind
  17620. * - BABYLON.VertexBuffer.ColorKind
  17621. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17622. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17623. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17624. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17625. */
  17626. Mesh.prototype.getVerticesDataKinds = function () {
  17627. if (!this._geometry) {
  17628. var result = [];
  17629. if (this._delayInfo) {
  17630. for (var kind in this._delayInfo) {
  17631. result.push(kind);
  17632. }
  17633. }
  17634. return result;
  17635. }
  17636. return this._geometry.getVerticesDataKinds();
  17637. };
  17638. /**
  17639. * Returns a positive integer : the total number of indices in this mesh geometry.
  17640. * Returns zero if the mesh has no geometry.
  17641. */
  17642. Mesh.prototype.getTotalIndices = function () {
  17643. if (!this._geometry) {
  17644. return 0;
  17645. }
  17646. return this._geometry.getTotalIndices();
  17647. };
  17648. /**
  17649. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17650. * 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.
  17651. * Returns an empty array if the mesh has no geometry.
  17652. */
  17653. Mesh.prototype.getIndices = function (copyWhenShared) {
  17654. if (!this._geometry) {
  17655. return [];
  17656. }
  17657. return this._geometry.getIndices(copyWhenShared);
  17658. };
  17659. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17660. get: function () {
  17661. return this._masterMesh !== null && this._masterMesh !== undefined;
  17662. },
  17663. enumerable: true,
  17664. configurable: true
  17665. });
  17666. /**
  17667. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17668. */
  17669. Mesh.prototype.isReady = function () {
  17670. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17671. return false;
  17672. }
  17673. return _super.prototype.isReady.call(this);
  17674. };
  17675. /**
  17676. * Boolean : true if the mesh has been disposed.
  17677. */
  17678. Mesh.prototype.isDisposed = function () {
  17679. return this._isDisposed;
  17680. };
  17681. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17682. get: function () {
  17683. return this._sideOrientation;
  17684. },
  17685. /**
  17686. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17687. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17688. */
  17689. set: function (sideO) {
  17690. this._sideOrientation = sideO;
  17691. },
  17692. enumerable: true,
  17693. configurable: true
  17694. });
  17695. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17696. /**
  17697. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17698. * This property is pertinent only for updatable parametric shapes.
  17699. */
  17700. get: function () {
  17701. return this._areNormalsFrozen;
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. /**
  17707. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17708. * It has no effect at all on other shapes.
  17709. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17710. */
  17711. Mesh.prototype.freezeNormals = function () {
  17712. this._areNormalsFrozen = true;
  17713. };
  17714. /**
  17715. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17716. * It has no effect at all on other shapes.
  17717. * It reactivates the mesh normals computation if it was previously frozen.
  17718. */
  17719. Mesh.prototype.unfreezeNormals = function () {
  17720. this._areNormalsFrozen = false;
  17721. };
  17722. // Methods
  17723. Mesh.prototype._preActivate = function () {
  17724. var sceneRenderId = this.getScene().getRenderId();
  17725. if (this._preActivateId === sceneRenderId) {
  17726. return;
  17727. }
  17728. this._preActivateId = sceneRenderId;
  17729. this._visibleInstances = null;
  17730. };
  17731. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17732. if (this._visibleInstances) {
  17733. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17734. }
  17735. };
  17736. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17737. if (!this._visibleInstances) {
  17738. this._visibleInstances = {};
  17739. this._visibleInstances.defaultRenderId = renderId;
  17740. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17741. }
  17742. if (!this._visibleInstances[renderId]) {
  17743. this._visibleInstances[renderId] = new Array();
  17744. }
  17745. this._visibleInstances[renderId].push(instance);
  17746. };
  17747. /**
  17748. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17749. * This means the mesh underlying bounding box and sphere are recomputed.
  17750. */
  17751. Mesh.prototype.refreshBoundingInfo = function () {
  17752. if (this._boundingInfo.isLocked) {
  17753. return;
  17754. }
  17755. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17756. if (data) {
  17757. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17758. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17759. }
  17760. if (this.subMeshes) {
  17761. for (var index = 0; index < this.subMeshes.length; index++) {
  17762. this.subMeshes[index].refreshBoundingInfo();
  17763. }
  17764. }
  17765. this._updateBoundingInfo();
  17766. };
  17767. Mesh.prototype._createGlobalSubMesh = function () {
  17768. var totalVertices = this.getTotalVertices();
  17769. if (!totalVertices || !this.getIndices()) {
  17770. return null;
  17771. }
  17772. this.releaseSubMeshes();
  17773. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17774. };
  17775. Mesh.prototype.subdivide = function (count) {
  17776. if (count < 1) {
  17777. return;
  17778. }
  17779. var totalIndices = this.getTotalIndices();
  17780. var subdivisionSize = (totalIndices / count) | 0;
  17781. var offset = 0;
  17782. // Ensure that subdivisionSize is a multiple of 3
  17783. while (subdivisionSize % 3 !== 0) {
  17784. subdivisionSize++;
  17785. }
  17786. this.releaseSubMeshes();
  17787. for (var index = 0; index < count; index++) {
  17788. if (offset >= totalIndices) {
  17789. break;
  17790. }
  17791. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17792. offset += subdivisionSize;
  17793. }
  17794. this.synchronizeInstances();
  17795. };
  17796. /**
  17797. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17798. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17799. * The `data` are either a numeric array either a Float32Array.
  17800. * The parameter `updatable` is passed as is to the underlying `Geometry` object constructor (if initianilly none) or updater.
  17801. * 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).
  17802. * Note that a new underlying `VertexBuffer` object is created each call.
  17803. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17804. *
  17805. * Possible `kind` values :
  17806. * - BABYLON.VertexBuffer.PositionKind
  17807. * - BABYLON.VertexBuffer.UVKind
  17808. * - BABYLON.VertexBuffer.UV2Kind
  17809. * - BABYLON.VertexBuffer.UV3Kind
  17810. * - BABYLON.VertexBuffer.UV4Kind
  17811. * - BABYLON.VertexBuffer.UV5Kind
  17812. * - BABYLON.VertexBuffer.UV6Kind
  17813. * - BABYLON.VertexBuffer.ColorKind
  17814. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17815. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17816. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17817. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17818. */
  17819. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17820. if (!this._geometry) {
  17821. var vertexData = new BABYLON.VertexData();
  17822. vertexData.set(data, kind);
  17823. var scene = this.getScene();
  17824. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17825. }
  17826. else {
  17827. this._geometry.setVerticesData(kind, data, updatable, stride);
  17828. }
  17829. };
  17830. /**
  17831. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17832. * If the mesh has no geometry, it is simply returned as it is.
  17833. * The `data` are either a numeric array either a Float32Array.
  17834. * No new underlying `VertexBuffer` object is created.
  17835. * 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.
  17836. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17837. *
  17838. * Possible `kind` values :
  17839. * - BABYLON.VertexBuffer.PositionKind
  17840. * - BABYLON.VertexBuffer.UVKind
  17841. * - BABYLON.VertexBuffer.UV2Kind
  17842. * - BABYLON.VertexBuffer.UV3Kind
  17843. * - BABYLON.VertexBuffer.UV4Kind
  17844. * - BABYLON.VertexBuffer.UV5Kind
  17845. * - BABYLON.VertexBuffer.UV6Kind
  17846. * - BABYLON.VertexBuffer.ColorKind
  17847. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17848. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17849. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17850. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17851. */
  17852. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17853. if (!this._geometry) {
  17854. return;
  17855. }
  17856. if (!makeItUnique) {
  17857. this._geometry.updateVerticesData(kind, data, updateExtends);
  17858. }
  17859. else {
  17860. this.makeGeometryUnique();
  17861. this.updateVerticesData(kind, data, updateExtends, false);
  17862. }
  17863. };
  17864. /**
  17865. * Deprecated since BabylonJS v2.3
  17866. */
  17867. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17868. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17869. if (!this._geometry) {
  17870. return;
  17871. }
  17872. if (!makeItUnique) {
  17873. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17874. }
  17875. else {
  17876. this.makeGeometryUnique();
  17877. this.updateVerticesDataDirectly(kind, data, offset, false);
  17878. }
  17879. };
  17880. /**
  17881. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17882. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17883. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17884. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17885. */
  17886. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17887. if (computeNormals === void 0) { computeNormals = true; }
  17888. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17889. positionFunction(positions);
  17890. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17891. if (computeNormals) {
  17892. var indices = this.getIndices();
  17893. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17894. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17895. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17896. }
  17897. };
  17898. Mesh.prototype.makeGeometryUnique = function () {
  17899. if (!this._geometry) {
  17900. return;
  17901. }
  17902. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17903. geometry.applyToMesh(this);
  17904. };
  17905. /**
  17906. * Sets the mesh indices.
  17907. * Expects an array populated with integers or a Int32Array.
  17908. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17909. * This method creates a new index buffer each call.
  17910. */
  17911. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17912. if (!this._geometry) {
  17913. var vertexData = new BABYLON.VertexData();
  17914. vertexData.indices = indices;
  17915. var scene = this.getScene();
  17916. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17917. }
  17918. else {
  17919. this._geometry.setIndices(indices, totalVertices);
  17920. }
  17921. };
  17922. /**
  17923. * Invert the geometry to move from a right handed system to a left handed one.
  17924. */
  17925. Mesh.prototype.toLeftHanded = function () {
  17926. if (!this._geometry) {
  17927. return;
  17928. }
  17929. this._geometry.toLeftHanded();
  17930. };
  17931. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17932. var engine = this.getScene().getEngine();
  17933. // Wireframe
  17934. var indexToBind;
  17935. if (this._unIndexed) {
  17936. indexToBind = null;
  17937. }
  17938. else {
  17939. switch (fillMode) {
  17940. case BABYLON.Material.PointFillMode:
  17941. indexToBind = null;
  17942. break;
  17943. case BABYLON.Material.WireFrameFillMode:
  17944. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17945. break;
  17946. default:
  17947. case BABYLON.Material.TriangleFillMode:
  17948. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17949. break;
  17950. }
  17951. }
  17952. // VBOs
  17953. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17954. };
  17955. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17956. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17957. return;
  17958. }
  17959. this.onBeforeDrawObservable.notifyObservers(this);
  17960. var engine = this.getScene().getEngine();
  17961. // Draw order
  17962. switch (fillMode) {
  17963. case BABYLON.Material.PointFillMode:
  17964. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17965. break;
  17966. case BABYLON.Material.WireFrameFillMode:
  17967. if (this._unIndexed) {
  17968. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17969. }
  17970. else {
  17971. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17972. }
  17973. break;
  17974. default:
  17975. if (this._unIndexed) {
  17976. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17977. }
  17978. else {
  17979. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17980. }
  17981. }
  17982. };
  17983. /**
  17984. * Registers for this mesh a javascript function called just before the rendering process.
  17985. * This function is passed the current mesh and doesn't return anything.
  17986. */
  17987. Mesh.prototype.registerBeforeRender = function (func) {
  17988. this.onBeforeRenderObservable.add(func);
  17989. };
  17990. /**
  17991. * Disposes a previously registered javascript function called before the rendering.
  17992. * This function is passed the current mesh and doesn't return anything.
  17993. */
  17994. Mesh.prototype.unregisterBeforeRender = function (func) {
  17995. this.onBeforeRenderObservable.removeCallback(func);
  17996. };
  17997. /**
  17998. * Registers for this mesh a javascript function called just after the rendering is complete.
  17999. * This function is passed the current mesh and doesn't return anything.
  18000. */
  18001. Mesh.prototype.registerAfterRender = function (func) {
  18002. this.onAfterRenderObservable.add(func);
  18003. };
  18004. /**
  18005. * Disposes a previously registered javascript function called after the rendering.
  18006. * This function is passed the current mesh and doesn't return anything.
  18007. */
  18008. Mesh.prototype.unregisterAfterRender = function (func) {
  18009. this.onAfterRenderObservable.removeCallback(func);
  18010. };
  18011. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  18012. var scene = this.getScene();
  18013. this._batchCache.mustReturn = false;
  18014. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  18015. this._batchCache.visibleInstances[subMeshId] = null;
  18016. if (this._visibleInstances) {
  18017. var currentRenderId = scene.getRenderId();
  18018. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  18019. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  18020. var selfRenderId = this._renderId;
  18021. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  18022. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  18023. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  18024. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  18025. }
  18026. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  18027. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  18028. this._batchCache.mustReturn = true;
  18029. return this._batchCache;
  18030. }
  18031. if (currentRenderId !== selfRenderId) {
  18032. this._batchCache.renderSelf[subMeshId] = false;
  18033. }
  18034. }
  18035. this._renderIdForInstances[subMeshId] = currentRenderId;
  18036. }
  18037. return this._batchCache;
  18038. };
  18039. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  18040. var visibleInstances = batch.visibleInstances[subMesh._id];
  18041. var matricesCount = visibleInstances.length + 1;
  18042. var bufferSize = matricesCount * 16 * 4;
  18043. while (this._instancesBufferSize < bufferSize) {
  18044. this._instancesBufferSize *= 2;
  18045. }
  18046. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  18047. if (this._worldMatricesInstancesBuffer) {
  18048. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  18049. }
  18050. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  18051. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  18052. }
  18053. var offset = 0;
  18054. var instancesCount = 0;
  18055. var world = this.getWorldMatrix();
  18056. if (batch.renderSelf[subMesh._id]) {
  18057. world.copyToArray(this._worldMatricesInstancesArray, offset);
  18058. offset += 16;
  18059. instancesCount++;
  18060. }
  18061. if (visibleInstances) {
  18062. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  18063. var instance = visibleInstances[instanceIndex];
  18064. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  18065. offset += 16;
  18066. instancesCount++;
  18067. }
  18068. }
  18069. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  18070. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  18071. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  18072. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  18073. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  18074. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  18075. this._draw(subMesh, fillMode, instancesCount);
  18076. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  18077. };
  18078. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  18079. var scene = this.getScene();
  18080. var engine = scene.getEngine();
  18081. if (hardwareInstancedRendering) {
  18082. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  18083. }
  18084. else {
  18085. if (batch.renderSelf[subMesh._id]) {
  18086. // Draw
  18087. if (onBeforeDraw) {
  18088. onBeforeDraw(false, this.getWorldMatrix());
  18089. }
  18090. this._draw(subMesh, fillMode);
  18091. }
  18092. if (batch.visibleInstances[subMesh._id]) {
  18093. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  18094. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  18095. // World
  18096. var world = instance.getWorldMatrix();
  18097. if (onBeforeDraw) {
  18098. onBeforeDraw(true, world);
  18099. }
  18100. // Draw
  18101. this._draw(subMesh, fillMode);
  18102. }
  18103. }
  18104. }
  18105. };
  18106. /**
  18107. * Triggers the draw call for the mesh.
  18108. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  18109. */
  18110. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  18111. var scene = this.getScene();
  18112. // Managing instances
  18113. var batch = this._getInstancesRenderList(subMesh._id);
  18114. if (batch.mustReturn) {
  18115. return;
  18116. }
  18117. // Checking geometry state
  18118. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18119. return;
  18120. }
  18121. var callbackIndex;
  18122. this.onBeforeRenderObservable.notifyObservers(this);
  18123. var engine = scene.getEngine();
  18124. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  18125. // Material
  18126. var effectiveMaterial = subMesh.getMaterial();
  18127. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  18128. return;
  18129. }
  18130. // Outline - step 1
  18131. var savedDepthWrite = engine.getDepthWrite();
  18132. if (this.renderOutline) {
  18133. engine.setDepthWrite(false);
  18134. scene.getOutlineRenderer().render(subMesh, batch);
  18135. engine.setDepthWrite(savedDepthWrite);
  18136. }
  18137. effectiveMaterial._preBind();
  18138. var effect = effectiveMaterial.getEffect();
  18139. // Bind
  18140. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  18141. this._bind(subMesh, effect, fillMode);
  18142. var world = this.getWorldMatrix();
  18143. effectiveMaterial.bind(world, this);
  18144. // Alpha mode
  18145. if (enableAlphaMode) {
  18146. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18147. }
  18148. // Draw
  18149. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  18150. if (isInstance) {
  18151. effectiveMaterial.bindOnlyWorldMatrix(world);
  18152. }
  18153. });
  18154. // Unbind
  18155. effectiveMaterial.unbind();
  18156. // Outline - step 2
  18157. if (this.renderOutline && savedDepthWrite) {
  18158. engine.setDepthWrite(true);
  18159. engine.setColorWrite(false);
  18160. scene.getOutlineRenderer().render(subMesh, batch);
  18161. engine.setColorWrite(true);
  18162. }
  18163. // Overlay
  18164. if (this.renderOverlay) {
  18165. var currentMode = engine.getAlphaMode();
  18166. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18167. scene.getOutlineRenderer().render(subMesh, batch, true);
  18168. engine.setAlphaMode(currentMode);
  18169. }
  18170. this.onAfterRenderObservable.notifyObservers(this);
  18171. };
  18172. /**
  18173. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  18174. */
  18175. Mesh.prototype.getEmittedParticleSystems = function () {
  18176. var results = new Array();
  18177. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18178. var particleSystem = this.getScene().particleSystems[index];
  18179. if (particleSystem.emitter === this) {
  18180. results.push(particleSystem);
  18181. }
  18182. }
  18183. return results;
  18184. };
  18185. /**
  18186. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  18187. */
  18188. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18189. var results = new Array();
  18190. var descendants = this.getDescendants();
  18191. descendants.push(this);
  18192. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18193. var particleSystem = this.getScene().particleSystems[index];
  18194. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18195. results.push(particleSystem);
  18196. }
  18197. }
  18198. return results;
  18199. };
  18200. Mesh.prototype._checkDelayState = function () {
  18201. var _this = this;
  18202. var that = this;
  18203. var scene = this.getScene();
  18204. if (this._geometry) {
  18205. this._geometry.load(scene);
  18206. }
  18207. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18208. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18209. scene._addPendingData(that);
  18210. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18211. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18212. if (data instanceof ArrayBuffer) {
  18213. _this._delayLoadingFunction(data, _this);
  18214. }
  18215. else {
  18216. _this._delayLoadingFunction(JSON.parse(data), _this);
  18217. }
  18218. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18219. scene._removePendingData(_this);
  18220. }, function () { }, scene.database, getBinaryData);
  18221. }
  18222. };
  18223. /**
  18224. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  18225. */
  18226. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18227. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18228. return false;
  18229. }
  18230. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18231. return false;
  18232. }
  18233. this._checkDelayState();
  18234. return true;
  18235. };
  18236. /**
  18237. * Sets the mesh material by the material or multiMaterial `id` property.
  18238. * The material `id` is a string identifying the material or the multiMaterial.
  18239. * This method returns nothing.
  18240. */
  18241. Mesh.prototype.setMaterialByID = function (id) {
  18242. var materials = this.getScene().materials;
  18243. var index;
  18244. for (index = 0; index < materials.length; index++) {
  18245. if (materials[index].id === id) {
  18246. this.material = materials[index];
  18247. return;
  18248. }
  18249. }
  18250. // Multi
  18251. var multiMaterials = this.getScene().multiMaterials;
  18252. for (index = 0; index < multiMaterials.length; index++) {
  18253. if (multiMaterials[index].id === id) {
  18254. this.material = multiMaterials[index];
  18255. return;
  18256. }
  18257. }
  18258. };
  18259. /**
  18260. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18261. */
  18262. Mesh.prototype.getAnimatables = function () {
  18263. var results = [];
  18264. if (this.material) {
  18265. results.push(this.material);
  18266. }
  18267. if (this.skeleton) {
  18268. results.push(this.skeleton);
  18269. }
  18270. return results;
  18271. };
  18272. /**
  18273. * Modifies the mesh geometry according to the passed transformation matrix.
  18274. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18275. * The mesh normals are modified accordingly the same transformation.
  18276. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18277. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18278. */
  18279. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18280. // Position
  18281. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18282. return;
  18283. }
  18284. var submeshes = this.subMeshes.splice(0);
  18285. this._resetPointsArrayCache();
  18286. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18287. var temp = [];
  18288. var index;
  18289. for (index = 0; index < data.length; index += 3) {
  18290. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18291. }
  18292. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18293. // Normals
  18294. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18295. return;
  18296. }
  18297. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18298. temp = [];
  18299. for (index = 0; index < data.length; index += 3) {
  18300. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18301. }
  18302. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18303. // flip faces?
  18304. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18305. this.flipFaces();
  18306. }
  18307. // Restore submeshes
  18308. this.releaseSubMeshes();
  18309. this.subMeshes = submeshes;
  18310. };
  18311. /**
  18312. * Modifies the mesh geometry according to its own current World Matrix.
  18313. * The mesh World Matrix is then reset.
  18314. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18315. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18316. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18317. */
  18318. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18319. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18320. this.scaling.copyFromFloats(1, 1, 1);
  18321. this.position.copyFromFloats(0, 0, 0);
  18322. this.rotation.copyFromFloats(0, 0, 0);
  18323. //only if quaternion is already set
  18324. if (this.rotationQuaternion) {
  18325. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18326. }
  18327. this._worldMatrix = BABYLON.Matrix.Identity();
  18328. };
  18329. // Cache
  18330. Mesh.prototype._resetPointsArrayCache = function () {
  18331. this._positions = null;
  18332. };
  18333. Mesh.prototype._generatePointsArray = function () {
  18334. if (this._positions)
  18335. return true;
  18336. this._positions = [];
  18337. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18338. if (!data) {
  18339. return false;
  18340. }
  18341. for (var index = 0; index < data.length; index += 3) {
  18342. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18343. }
  18344. return true;
  18345. };
  18346. /**
  18347. * Returns a new `Mesh` object generated from the current mesh properties.
  18348. * This method must not get confused with createInstance().
  18349. * The parameter `name` is a string, the name given to the new mesh.
  18350. * The optional parameter `newParent` can be any `Node` object (default `null`).
  18351. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  18352. * 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.
  18353. */
  18354. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  18355. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18356. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  18357. };
  18358. /**
  18359. * Disposes the mesh.
  18360. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  18361. */
  18362. Mesh.prototype.dispose = function (doNotRecurse) {
  18363. if (this._geometry) {
  18364. this._geometry.releaseForMesh(this, true);
  18365. }
  18366. // Instances
  18367. if (this._worldMatricesInstancesBuffer) {
  18368. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  18369. this._worldMatricesInstancesBuffer = null;
  18370. }
  18371. while (this.instances.length) {
  18372. this.instances[0].dispose();
  18373. }
  18374. _super.prototype.dispose.call(this, doNotRecurse);
  18375. };
  18376. /**
  18377. * Modifies the mesh geometry according to a displacement map.
  18378. * 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.
  18379. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18380. * This method returns nothing.
  18381. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  18382. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18383. * 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.
  18384. */
  18385. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  18386. var _this = this;
  18387. var scene = this.getScene();
  18388. var onload = function (img) {
  18389. // Getting height map data
  18390. var canvas = document.createElement("canvas");
  18391. var context = canvas.getContext("2d");
  18392. var heightMapWidth = img.width;
  18393. var heightMapHeight = img.height;
  18394. canvas.width = heightMapWidth;
  18395. canvas.height = heightMapHeight;
  18396. context.drawImage(img, 0, 0);
  18397. // Create VertexData from map data
  18398. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18399. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  18400. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  18401. //execute success callback, if set
  18402. if (onSuccess) {
  18403. onSuccess(_this);
  18404. }
  18405. };
  18406. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18407. };
  18408. /**
  18409. * Modifies the mesh geometry according to a displacementMap buffer.
  18410. * 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.
  18411. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18412. * This method returns nothing.
  18413. * 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.
  18414. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  18415. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18416. */
  18417. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  18418. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  18419. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  18420. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18421. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  18422. return;
  18423. }
  18424. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18425. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18426. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18427. var position = BABYLON.Vector3.Zero();
  18428. var normal = BABYLON.Vector3.Zero();
  18429. var uv = BABYLON.Vector2.Zero();
  18430. for (var index = 0; index < positions.length; index += 3) {
  18431. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  18432. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  18433. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  18434. // Compute height
  18435. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  18436. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  18437. var pos = (u + v * heightMapWidth) * 4;
  18438. var r = buffer[pos] / 255.0;
  18439. var g = buffer[pos + 1] / 255.0;
  18440. var b = buffer[pos + 2] / 255.0;
  18441. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18442. normal.normalize();
  18443. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  18444. position = position.add(normal);
  18445. position.toArray(positions, index);
  18446. }
  18447. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  18448. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  18449. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18450. };
  18451. /**
  18452. * Modify the mesh to get a flat shading rendering.
  18453. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  18454. * This method returns nothing.
  18455. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  18456. */
  18457. Mesh.prototype.convertToFlatShadedMesh = function () {
  18458. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  18459. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18460. var kinds = this.getVerticesDataKinds();
  18461. var vbs = [];
  18462. var data = [];
  18463. var newdata = [];
  18464. var updatableNormals = false;
  18465. var kindIndex;
  18466. var kind;
  18467. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18468. kind = kinds[kindIndex];
  18469. var vertexBuffer = this.getVertexBuffer(kind);
  18470. if (kind === BABYLON.VertexBuffer.NormalKind) {
  18471. updatableNormals = vertexBuffer.isUpdatable();
  18472. kinds.splice(kindIndex, 1);
  18473. kindIndex--;
  18474. continue;
  18475. }
  18476. vbs[kind] = vertexBuffer;
  18477. data[kind] = vbs[kind].getData();
  18478. newdata[kind] = [];
  18479. }
  18480. // Save previous submeshes
  18481. var previousSubmeshes = this.subMeshes.slice(0);
  18482. var indices = this.getIndices();
  18483. var totalIndices = this.getTotalIndices();
  18484. // Generating unique vertices per face
  18485. var index;
  18486. for (index = 0; index < totalIndices; index++) {
  18487. var vertexIndex = indices[index];
  18488. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18489. kind = kinds[kindIndex];
  18490. var stride = vbs[kind].getStrideSize();
  18491. for (var offset = 0; offset < stride; offset++) {
  18492. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18493. }
  18494. }
  18495. }
  18496. // Updating faces & normal
  18497. var normals = [];
  18498. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  18499. for (index = 0; index < totalIndices; index += 3) {
  18500. indices[index] = index;
  18501. indices[index + 1] = index + 1;
  18502. indices[index + 2] = index + 2;
  18503. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  18504. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  18505. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  18506. var p1p2 = p1.subtract(p2);
  18507. var p3p2 = p3.subtract(p2);
  18508. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18509. // Store same normals for every vertex
  18510. for (var localIndex = 0; localIndex < 3; localIndex++) {
  18511. normals.push(normal.x);
  18512. normals.push(normal.y);
  18513. normals.push(normal.z);
  18514. }
  18515. }
  18516. this.setIndices(indices);
  18517. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  18518. // Updating vertex buffers
  18519. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18520. kind = kinds[kindIndex];
  18521. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18522. }
  18523. // Updating submeshes
  18524. this.releaseSubMeshes();
  18525. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18526. var previousOne = previousSubmeshes[submeshIndex];
  18527. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18528. }
  18529. this.synchronizeInstances();
  18530. };
  18531. /**
  18532. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  18533. * In other words, more vertices, no more indices and a single bigger VBO.
  18534. * This method returns nothing.
  18535. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  18536. *
  18537. */
  18538. Mesh.prototype.convertToUnIndexedMesh = function () {
  18539. /// <summary>Remove indices by unfolding faces into buffers</summary>
  18540. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18541. var kinds = this.getVerticesDataKinds();
  18542. var vbs = [];
  18543. var data = [];
  18544. var newdata = [];
  18545. var updatableNormals = false;
  18546. var kindIndex;
  18547. var kind;
  18548. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18549. kind = kinds[kindIndex];
  18550. var vertexBuffer = this.getVertexBuffer(kind);
  18551. vbs[kind] = vertexBuffer;
  18552. data[kind] = vbs[kind].getData();
  18553. newdata[kind] = [];
  18554. }
  18555. // Save previous submeshes
  18556. var previousSubmeshes = this.subMeshes.slice(0);
  18557. var indices = this.getIndices();
  18558. var totalIndices = this.getTotalIndices();
  18559. // Generating unique vertices per face
  18560. var index;
  18561. for (index = 0; index < totalIndices; index++) {
  18562. var vertexIndex = indices[index];
  18563. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18564. kind = kinds[kindIndex];
  18565. var stride = vbs[kind].getStrideSize();
  18566. for (var offset = 0; offset < stride; offset++) {
  18567. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18568. }
  18569. }
  18570. }
  18571. // Updating indices
  18572. for (index = 0; index < totalIndices; index += 3) {
  18573. indices[index] = index;
  18574. indices[index + 1] = index + 1;
  18575. indices[index + 2] = index + 2;
  18576. }
  18577. this.setIndices(indices);
  18578. // Updating vertex buffers
  18579. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18580. kind = kinds[kindIndex];
  18581. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18582. }
  18583. // Updating submeshes
  18584. this.releaseSubMeshes();
  18585. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18586. var previousOne = previousSubmeshes[submeshIndex];
  18587. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18588. }
  18589. this._unIndexed = true;
  18590. this.synchronizeInstances();
  18591. };
  18592. /**
  18593. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  18594. * This method returns nothing.
  18595. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  18596. */
  18597. Mesh.prototype.flipFaces = function (flipNormals) {
  18598. if (flipNormals === void 0) { flipNormals = false; }
  18599. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18600. var i;
  18601. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18602. for (i = 0; i < vertex_data.normals.length; i++) {
  18603. vertex_data.normals[i] *= -1;
  18604. }
  18605. }
  18606. var temp;
  18607. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18608. // reassign indices
  18609. temp = vertex_data.indices[i + 1];
  18610. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18611. vertex_data.indices[i + 2] = temp;
  18612. }
  18613. vertex_data.applyToMesh(this);
  18614. };
  18615. // Instances
  18616. /**
  18617. * Creates a new `InstancedMesh` object from the mesh model.
  18618. * An instance shares the same properties and the same material than its model.
  18619. * Only these properties of each instance can then be set individually :
  18620. * - position
  18621. * - rotation
  18622. * - rotationQuaternion
  18623. * - setPivotMatrix
  18624. * - scaling
  18625. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  18626. * Warning : this method is not supported for `Line` mesh and `LineSystem`
  18627. */
  18628. Mesh.prototype.createInstance = function (name) {
  18629. return new BABYLON.InstancedMesh(name, this);
  18630. };
  18631. /**
  18632. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  18633. * After this call, all the mesh instances have the same submeshes than the current mesh.
  18634. * This method returns nothing.
  18635. */
  18636. Mesh.prototype.synchronizeInstances = function () {
  18637. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18638. var instance = this.instances[instanceIndex];
  18639. instance._syncSubMeshes();
  18640. }
  18641. };
  18642. /**
  18643. * Simplify the mesh according to the given array of settings.
  18644. * Function will return immediately and will simplify async. It returns nothing.
  18645. * @param settings a collection of simplification settings.
  18646. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18647. * @param type the type of simplification to run.
  18648. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18649. */
  18650. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18651. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18652. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18653. this.getScene().simplificationQueue.addTask({
  18654. settings: settings,
  18655. parallelProcessing: parallelProcessing,
  18656. mesh: this,
  18657. simplificationType: simplificationType,
  18658. successCallback: successCallback
  18659. });
  18660. };
  18661. /**
  18662. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18663. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18664. * This should be used together with the simplification to avoid disappearing triangles.
  18665. * @param successCallback an optional success callback to be called after the optimization finished.
  18666. */
  18667. Mesh.prototype.optimizeIndices = function (successCallback) {
  18668. var _this = this;
  18669. var indices = this.getIndices();
  18670. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18671. var vectorPositions = [];
  18672. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18673. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18674. }
  18675. var dupes = [];
  18676. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18677. var realPos = vectorPositions.length - 1 - iteration;
  18678. var testedPosition = vectorPositions[realPos];
  18679. for (var j = 0; j < realPos; ++j) {
  18680. var againstPosition = vectorPositions[j];
  18681. if (testedPosition.equals(againstPosition)) {
  18682. dupes[realPos] = j;
  18683. break;
  18684. }
  18685. }
  18686. }, function () {
  18687. for (var i = 0; i < indices.length; ++i) {
  18688. indices[i] = dupes[indices[i]] || indices[i];
  18689. }
  18690. //indices are now reordered
  18691. var originalSubMeshes = _this.subMeshes.slice(0);
  18692. _this.setIndices(indices);
  18693. _this.subMeshes = originalSubMeshes;
  18694. if (successCallback) {
  18695. successCallback(_this);
  18696. }
  18697. });
  18698. };
  18699. // Statics
  18700. /**
  18701. * Returns a new `Mesh` object what is a deep copy of the passed mesh.
  18702. * The parameter `parsedMesh` is the mesh to be copied.
  18703. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18704. */
  18705. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18706. var mesh = new Mesh(parsedMesh.name, scene);
  18707. mesh.id = parsedMesh.id;
  18708. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18709. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18710. if (parsedMesh.rotationQuaternion) {
  18711. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18712. }
  18713. else if (parsedMesh.rotation) {
  18714. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18715. }
  18716. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18717. if (parsedMesh.localMatrix) {
  18718. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18719. }
  18720. else if (parsedMesh.pivotMatrix) {
  18721. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18722. }
  18723. mesh.setEnabled(parsedMesh.isEnabled);
  18724. mesh.isVisible = parsedMesh.isVisible;
  18725. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18726. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18727. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18728. if (parsedMesh.applyFog !== undefined) {
  18729. mesh.applyFog = parsedMesh.applyFog;
  18730. }
  18731. if (parsedMesh.pickable !== undefined) {
  18732. mesh.isPickable = parsedMesh.pickable;
  18733. }
  18734. if (parsedMesh.alphaIndex !== undefined) {
  18735. mesh.alphaIndex = parsedMesh.alphaIndex;
  18736. }
  18737. mesh.receiveShadows = parsedMesh.receiveShadows;
  18738. mesh.billboardMode = parsedMesh.billboardMode;
  18739. if (parsedMesh.visibility !== undefined) {
  18740. mesh.visibility = parsedMesh.visibility;
  18741. }
  18742. mesh.checkCollisions = parsedMesh.checkCollisions;
  18743. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18744. // freezeWorldMatrix
  18745. if (parsedMesh.freezeWorldMatrix) {
  18746. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18747. }
  18748. // Parent
  18749. if (parsedMesh.parentId) {
  18750. mesh._waitingParentId = parsedMesh.parentId;
  18751. }
  18752. // Actions
  18753. if (parsedMesh.actions !== undefined) {
  18754. mesh._waitingActions = parsedMesh.actions;
  18755. }
  18756. // Geometry
  18757. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18758. if (parsedMesh.delayLoadingFile) {
  18759. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18760. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18761. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18762. if (parsedMesh._binaryInfo) {
  18763. mesh._binaryInfo = parsedMesh._binaryInfo;
  18764. }
  18765. mesh._delayInfo = [];
  18766. if (parsedMesh.hasUVs) {
  18767. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18768. }
  18769. if (parsedMesh.hasUVs2) {
  18770. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18771. }
  18772. if (parsedMesh.hasUVs3) {
  18773. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18774. }
  18775. if (parsedMesh.hasUVs4) {
  18776. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18777. }
  18778. if (parsedMesh.hasUVs5) {
  18779. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18780. }
  18781. if (parsedMesh.hasUVs6) {
  18782. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18783. }
  18784. if (parsedMesh.hasColors) {
  18785. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18786. }
  18787. if (parsedMesh.hasMatricesIndices) {
  18788. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18789. }
  18790. if (parsedMesh.hasMatricesWeights) {
  18791. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18792. }
  18793. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18794. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18795. mesh._checkDelayState();
  18796. }
  18797. }
  18798. else {
  18799. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18800. }
  18801. // Material
  18802. if (parsedMesh.materialId) {
  18803. mesh.setMaterialByID(parsedMesh.materialId);
  18804. }
  18805. else {
  18806. mesh.material = null;
  18807. }
  18808. // Skeleton
  18809. if (parsedMesh.skeletonId > -1) {
  18810. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18811. if (parsedMesh.numBoneInfluencers) {
  18812. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18813. }
  18814. }
  18815. // Animations
  18816. if (parsedMesh.animations) {
  18817. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18818. var parsedAnimation = parsedMesh.animations[animationIndex];
  18819. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18820. }
  18821. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18822. }
  18823. if (parsedMesh.autoAnimate) {
  18824. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18825. }
  18826. // Layer Mask
  18827. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18828. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18829. }
  18830. else {
  18831. mesh.layerMask = 0x0FFFFFFF;
  18832. }
  18833. //(Deprecated) physics
  18834. if (parsedMesh.physicsImpostor) {
  18835. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18836. mass: parsedMesh.physicsMass,
  18837. friction: parsedMesh.physicsFriction,
  18838. restitution: parsedMesh.physicsRestitution
  18839. }, scene);
  18840. }
  18841. // Instances
  18842. if (parsedMesh.instances) {
  18843. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18844. var parsedInstance = parsedMesh.instances[index];
  18845. var instance = mesh.createInstance(parsedInstance.name);
  18846. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18847. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18848. if (parsedInstance.rotationQuaternion) {
  18849. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18850. }
  18851. else if (parsedInstance.rotation) {
  18852. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18853. }
  18854. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18855. instance.checkCollisions = mesh.checkCollisions;
  18856. if (parsedMesh.animations) {
  18857. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18858. parsedAnimation = parsedMesh.animations[animationIndex];
  18859. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18860. }
  18861. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18862. }
  18863. }
  18864. }
  18865. return mesh;
  18866. };
  18867. /**
  18868. * Creates a ribbon mesh.
  18869. * Please consider using the same method from the `MeshBuilder` class instead.
  18870. * 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.
  18871. *
  18872. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18873. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18874. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18875. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18876. * 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.
  18877. * 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.
  18878. * 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
  18879. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18880. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18881. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18882. */
  18883. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18884. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18885. pathArray: pathArray,
  18886. closeArray: closeArray,
  18887. closePath: closePath,
  18888. offset: offset,
  18889. updatable: updatable,
  18890. sideOrientation: sideOrientation,
  18891. instance: instance
  18892. }, scene);
  18893. };
  18894. /**
  18895. * Creates a plane polygonal mesh. By default, this is a disc.
  18896. * Please consider using the same method from the `MeshBuilder` class instead.
  18897. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18898. * 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.
  18899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18904. var options = {
  18905. radius: radius,
  18906. tessellation: tessellation,
  18907. sideOrientation: sideOrientation,
  18908. updatable: updatable
  18909. };
  18910. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18911. };
  18912. /**
  18913. * Creates a box mesh.
  18914. * Please consider using the same method from the `MeshBuilder` class instead.
  18915. * The parameter `size` sets the size (float) of each box side (default 1).
  18916. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18917. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18919. */
  18920. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18921. var options = {
  18922. size: size,
  18923. sideOrientation: sideOrientation,
  18924. updatable: updatable
  18925. };
  18926. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18927. };
  18928. /**
  18929. * Creates a sphere mesh.
  18930. * Please consider using the same method from the `MeshBuilder` class instead.
  18931. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18932. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18936. */
  18937. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18938. var options = {
  18939. segments: segments,
  18940. diameterX: diameter,
  18941. diameterY: diameter,
  18942. diameterZ: diameter,
  18943. sideOrientation: sideOrientation,
  18944. updatable: updatable
  18945. };
  18946. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18947. };
  18948. /**
  18949. * Creates a cylinder or a cone mesh.
  18950. * Please consider using the same method from the `MeshBuilder` class instead.
  18951. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18952. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18953. * 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.
  18954. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18955. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18957. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18959. */
  18960. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18961. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18962. if (scene !== undefined) {
  18963. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18964. updatable = scene;
  18965. }
  18966. scene = subdivisions;
  18967. subdivisions = 1;
  18968. }
  18969. var options = {
  18970. height: height,
  18971. diameterTop: diameterTop,
  18972. diameterBottom: diameterBottom,
  18973. tessellation: tessellation,
  18974. subdivisions: subdivisions,
  18975. sideOrientation: sideOrientation,
  18976. updatable: updatable
  18977. };
  18978. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18979. };
  18980. // Torus (Code from SharpDX.org)
  18981. /**
  18982. * Creates a torus mesh.
  18983. * Please consider using the same method from the `MeshBuilder` class instead.
  18984. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18985. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18986. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18987. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18988. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18990. */
  18991. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18992. var options = {
  18993. diameter: diameter,
  18994. thickness: thickness,
  18995. tessellation: tessellation,
  18996. sideOrientation: sideOrientation,
  18997. updatable: updatable
  18998. };
  18999. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  19000. };
  19001. /**
  19002. * Creates a torus knot mesh.
  19003. * Please consider using the same method from the `MeshBuilder` class instead.
  19004. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19005. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19006. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19007. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  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.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  19013. var options = {
  19014. radius: radius,
  19015. tube: tube,
  19016. radialSegments: radialSegments,
  19017. tubularSegments: tubularSegments,
  19018. p: p,
  19019. q: q,
  19020. sideOrientation: sideOrientation,
  19021. updatable: updatable
  19022. };
  19023. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  19024. };
  19025. /**
  19026. * Creates a line mesh.
  19027. * Please consider using the same method from the `MeshBuilder` class instead.
  19028. * 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.
  19029. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19030. * The parameter `points` is an array successive Vector3.
  19031. * 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
  19032. * When updating an instance, remember that only point positions can change, not the number of points.
  19033. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19034. */
  19035. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  19036. var options = {
  19037. points: points,
  19038. updatable: updatable,
  19039. instance: instance
  19040. };
  19041. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  19042. };
  19043. /**
  19044. * Creates a dashed line mesh.
  19045. * Please consider using the same method from the `MeshBuilder` class instead.
  19046. * 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.
  19047. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19048. * The parameter `points` is an array successive Vector3.
  19049. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19050. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19051. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19052. * 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
  19053. * When updating an instance, remember that only point positions can change, not the number of points.
  19054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19055. */
  19056. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  19057. var options = {
  19058. points: points,
  19059. dashSize: dashSize,
  19060. gapSize: gapSize,
  19061. dashNb: dashNb,
  19062. updatable: updatable
  19063. };
  19064. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  19065. };
  19066. /**
  19067. * Creates an extruded shape mesh.
  19068. * 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.
  19069. * Please consider using the same method from the `MeshBuilder` class instead.
  19070. *
  19071. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19072. * 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
  19073. * extruded along the Z axis.
  19074. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19075. * 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.
  19076. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19077. * 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
  19078. * 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
  19079. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19080. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19081. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19082. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19083. */
  19084. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  19085. var options = {
  19086. shape: shape,
  19087. path: path,
  19088. scale: scale,
  19089. rotation: rotation,
  19090. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19091. sideOrientation: sideOrientation,
  19092. instance: instance,
  19093. updatable: updatable
  19094. };
  19095. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  19096. };
  19097. /**
  19098. * Creates an custom extruded shape mesh.
  19099. * 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.
  19100. * Please consider using the same method from the `MeshBuilder` class instead.
  19101. *
  19102. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19103. * 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
  19104. * extruded along the Z axis.
  19105. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19106. * 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
  19107. * and the distance of this point from the begining of the path :
  19108. * ```rotationFunction = function(i, distance) {
  19109. * // do things
  19110. * return rotationValue; }```
  19111. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19112. * 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
  19113. * and the distance of this point from the begining of the path :
  19114. * ````scaleFunction = function(i, distance) {
  19115. * // do things
  19116. * return scaleValue;}```
  19117. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19118. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19119. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19120. * 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
  19121. * 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
  19122. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19123. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19126. */
  19127. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  19128. var options = {
  19129. shape: shape,
  19130. path: path,
  19131. scaleFunction: scaleFunction,
  19132. rotationFunction: rotationFunction,
  19133. ribbonCloseArray: ribbonCloseArray,
  19134. ribbonClosePath: ribbonClosePath,
  19135. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19136. sideOrientation: sideOrientation,
  19137. instance: instance,
  19138. updatable: updatable
  19139. };
  19140. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  19141. };
  19142. /**
  19143. * Creates lathe mesh.
  19144. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19145. * Please consider using the same method from the `MeshBuilder` class instead.
  19146. *
  19147. * 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
  19148. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19149. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19150. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19152. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19154. */
  19155. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19156. var options = {
  19157. shape: shape,
  19158. radius: radius,
  19159. tessellation: tessellation,
  19160. sideOrientation: sideOrientation,
  19161. updatable: updatable
  19162. };
  19163. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19164. };
  19165. /**
  19166. * Creates a plane mesh.
  19167. * Please consider using the same method from the `MeshBuilder` class instead.
  19168. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19169. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19170. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19171. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19172. */
  19173. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19174. var options = {
  19175. size: size,
  19176. width: size,
  19177. height: size,
  19178. sideOrientation: sideOrientation,
  19179. updatable: updatable
  19180. };
  19181. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19182. };
  19183. /**
  19184. * Creates a ground mesh.
  19185. * Please consider using the same method from the `MeshBuilder` class instead.
  19186. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19187. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19188. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19189. */
  19190. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19191. var options = {
  19192. width: width,
  19193. height: height,
  19194. subdivisions: subdivisions,
  19195. updatable: updatable
  19196. };
  19197. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19198. };
  19199. /**
  19200. * Creates a tiled ground mesh.
  19201. * Please consider using the same method from the `MeshBuilder` class instead.
  19202. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19203. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19204. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19205. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19206. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19207. * numbers of subdivisions on the ground width and height of each tile.
  19208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19209. */
  19210. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19211. var options = {
  19212. xmin: xmin,
  19213. zmin: zmin,
  19214. xmax: xmax,
  19215. zmax: zmax,
  19216. subdivisions: subdivisions,
  19217. precision: precision,
  19218. updatable: updatable
  19219. };
  19220. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19221. };
  19222. /**
  19223. * Creates a ground mesh from a height map.
  19224. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19225. * Please consider using the same method from the `MeshBuilder` class instead.
  19226. * The parameter `url` sets the URL of the height map image resource.
  19227. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19228. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19229. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19230. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19231. * 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).
  19232. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19233. * return; }```
  19234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19235. */
  19236. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19237. var options = {
  19238. width: width,
  19239. height: height,
  19240. subdivisions: subdivisions,
  19241. minHeight: minHeight,
  19242. maxHeight: maxHeight,
  19243. updatable: updatable,
  19244. onReady: onReady
  19245. };
  19246. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19247. };
  19248. /**
  19249. * Creates a tube mesh.
  19250. * 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.
  19251. *
  19252. * Please consider using the same method from the `MeshBuilder` class instead.
  19253. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19254. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19255. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19256. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19257. * 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.
  19258. * It must return a radius value (positive float) :
  19259. * ```var radiusFunction = function(i, distance) {
  19260. * // do things
  19261. * return radius; }```
  19262. * 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
  19263. * 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
  19264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19265. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19267. */
  19268. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19269. var options = {
  19270. path: path,
  19271. radius: radius,
  19272. tessellation: tessellation,
  19273. radiusFunction: radiusFunction,
  19274. arc: 1,
  19275. cap: cap,
  19276. updatable: updatable,
  19277. sideOrientation: sideOrientation,
  19278. instance: instance
  19279. };
  19280. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19281. };
  19282. /**
  19283. * Creates a polyhedron mesh.
  19284. *
  19285. * Please consider using the same method from the `MeshBuilder` class instead.
  19286. * 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
  19287. * to choose the wanted type.
  19288. * The parameter `size` (positive float, default 1) sets the polygon size.
  19289. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19290. * 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`.
  19291. * 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
  19292. * 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)`).
  19293. * 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
  19294. * 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.
  19295. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19296. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19297. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19298. */
  19299. Mesh.CreatePolyhedron = function (name, options, scene) {
  19300. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19301. };
  19302. /**
  19303. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19304. * Please consider using the same method from the `MeshBuilder` class instead.
  19305. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19306. * 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`).
  19307. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19308. * 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.
  19309. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19310. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19311. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19312. */
  19313. Mesh.CreateIcoSphere = function (name, options, scene) {
  19314. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19315. };
  19316. /**
  19317. * Creates a decal mesh.
  19318. * Please consider using the same method from the `MeshBuilder` class instead.
  19319. * 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.
  19320. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19321. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19322. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19323. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19324. */
  19325. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19326. var options = {
  19327. position: position,
  19328. normal: normal,
  19329. size: size,
  19330. angle: angle
  19331. };
  19332. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19333. };
  19334. // Skeletons
  19335. /**
  19336. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19337. */
  19338. Mesh.prototype.setPositionsForCPUSkinning = function () {
  19339. var source;
  19340. if (!this._sourcePositions) {
  19341. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19342. this._sourcePositions = new Float32Array(source);
  19343. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  19344. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  19345. }
  19346. }
  19347. return this._sourcePositions;
  19348. };
  19349. /**
  19350. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19351. */
  19352. Mesh.prototype.setNormalsForCPUSkinning = function () {
  19353. var source;
  19354. if (!this._sourceNormals) {
  19355. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19356. this._sourceNormals = new Float32Array(source);
  19357. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  19358. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  19359. }
  19360. }
  19361. return this._sourceNormals;
  19362. };
  19363. /**
  19364. * Update the vertex buffers by applying transformation from the bones
  19365. * @param {skeleton} skeleton to apply
  19366. */
  19367. Mesh.prototype.applySkeleton = function (skeleton) {
  19368. if (!this.geometry) {
  19369. return;
  19370. }
  19371. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  19372. return;
  19373. }
  19374. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  19375. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19376. return this;
  19377. }
  19378. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19379. return this;
  19380. }
  19381. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19382. return this;
  19383. }
  19384. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19385. return this;
  19386. }
  19387. if (!this._sourcePositions) {
  19388. this.setPositionsForCPUSkinning();
  19389. }
  19390. if (!this._sourceNormals) {
  19391. this.setNormalsForCPUSkinning();
  19392. }
  19393. // positionsData checks for not being Float32Array will only pass at most once
  19394. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19395. if (!(positionsData instanceof Float32Array)) {
  19396. positionsData = new Float32Array(positionsData);
  19397. }
  19398. // normalsData checks for not being Float32Array will only pass at most once
  19399. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19400. if (!(normalsData instanceof Float32Array)) {
  19401. normalsData = new Float32Array(normalsData);
  19402. }
  19403. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19404. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19405. var needExtras = this.numBoneInfluencers > 4;
  19406. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  19407. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  19408. var skeletonMatrices = skeleton.getTransformMatrices(this);
  19409. var tempVector3 = BABYLON.Vector3.Zero();
  19410. var finalMatrix = new BABYLON.Matrix();
  19411. var tempMatrix = new BABYLON.Matrix();
  19412. var matWeightIdx = 0;
  19413. var inf;
  19414. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  19415. var weight;
  19416. for (inf = 0; inf < 4; inf++) {
  19417. weight = matricesWeightsData[matWeightIdx + inf];
  19418. if (weight > 0) {
  19419. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19420. finalMatrix.addToSelf(tempMatrix);
  19421. }
  19422. else
  19423. break;
  19424. }
  19425. if (needExtras) {
  19426. for (inf = 0; inf < 4; inf++) {
  19427. weight = matricesWeightsExtraData[matWeightIdx + inf];
  19428. if (weight > 0) {
  19429. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19430. finalMatrix.addToSelf(tempMatrix);
  19431. }
  19432. else
  19433. break;
  19434. }
  19435. }
  19436. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  19437. tempVector3.toArray(positionsData, index);
  19438. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  19439. tempVector3.toArray(normalsData, index);
  19440. finalMatrix.reset();
  19441. }
  19442. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  19443. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  19444. return this;
  19445. };
  19446. // Tools
  19447. /**
  19448. * Returns an object `{min: Vector3, max: Vector3}`
  19449. * This min and max `Vector3` are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  19450. */
  19451. Mesh.MinMax = function (meshes) {
  19452. var minVector = null;
  19453. var maxVector = null;
  19454. for (var i in meshes) {
  19455. var mesh = meshes[i];
  19456. var boundingBox = mesh.getBoundingInfo().boundingBox;
  19457. if (!minVector) {
  19458. minVector = boundingBox.minimumWorld;
  19459. maxVector = boundingBox.maximumWorld;
  19460. continue;
  19461. }
  19462. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  19463. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  19464. }
  19465. return {
  19466. min: minVector,
  19467. max: maxVector
  19468. };
  19469. };
  19470. /**
  19471. * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
  19472. */
  19473. Mesh.Center = function (meshesOrMinMaxVector) {
  19474. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  19475. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  19476. };
  19477. /**
  19478. * Merge the array of meshes into a single mesh for performance reasons.
  19479. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  19480. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  19481. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  19482. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  19483. */
  19484. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  19485. if (disposeSource === void 0) { disposeSource = true; }
  19486. var index;
  19487. if (!allow32BitsIndices) {
  19488. var totalVertices = 0;
  19489. // Counting vertices
  19490. for (index = 0; index < meshes.length; index++) {
  19491. if (meshes[index]) {
  19492. totalVertices += meshes[index].getTotalVertices();
  19493. if (totalVertices > 65536) {
  19494. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  19495. return null;
  19496. }
  19497. }
  19498. }
  19499. }
  19500. // Merge
  19501. var vertexData;
  19502. var otherVertexData;
  19503. var source;
  19504. for (index = 0; index < meshes.length; index++) {
  19505. if (meshes[index]) {
  19506. meshes[index].computeWorldMatrix(true);
  19507. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  19508. otherVertexData.transform(meshes[index].getWorldMatrix());
  19509. if (vertexData) {
  19510. vertexData.merge(otherVertexData);
  19511. }
  19512. else {
  19513. vertexData = otherVertexData;
  19514. source = meshes[index];
  19515. }
  19516. }
  19517. }
  19518. if (!meshSubclass) {
  19519. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  19520. }
  19521. vertexData.applyToMesh(meshSubclass);
  19522. // Setting properties
  19523. meshSubclass.material = source.material;
  19524. meshSubclass.checkCollisions = source.checkCollisions;
  19525. // Cleaning
  19526. if (disposeSource) {
  19527. for (index = 0; index < meshes.length; index++) {
  19528. if (meshes[index]) {
  19529. meshes[index].dispose();
  19530. }
  19531. }
  19532. }
  19533. return meshSubclass;
  19534. };
  19535. // Consts
  19536. Mesh._FRONTSIDE = 0;
  19537. Mesh._BACKSIDE = 1;
  19538. Mesh._DOUBLESIDE = 2;
  19539. Mesh._DEFAULTSIDE = 0;
  19540. Mesh._NO_CAP = 0;
  19541. Mesh._CAP_START = 1;
  19542. Mesh._CAP_END = 2;
  19543. Mesh._CAP_ALL = 3;
  19544. return Mesh;
  19545. })(BABYLON.AbstractMesh);
  19546. BABYLON.Mesh = Mesh;
  19547. })(BABYLON || (BABYLON = {}));
  19548. var BABYLON;
  19549. (function (BABYLON) {
  19550. var SubMesh = (function () {
  19551. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  19552. if (createBoundingBox === void 0) { createBoundingBox = true; }
  19553. this.materialIndex = materialIndex;
  19554. this.verticesStart = verticesStart;
  19555. this.verticesCount = verticesCount;
  19556. this.indexStart = indexStart;
  19557. this.indexCount = indexCount;
  19558. this._renderId = 0;
  19559. this._mesh = mesh;
  19560. this._renderingMesh = renderingMesh || mesh;
  19561. mesh.subMeshes.push(this);
  19562. this._trianglePlanes = [];
  19563. this._id = mesh.subMeshes.length - 1;
  19564. if (createBoundingBox) {
  19565. this.refreshBoundingInfo();
  19566. mesh.computeWorldMatrix(true);
  19567. }
  19568. }
  19569. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  19570. get: function () {
  19571. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. SubMesh.prototype.getBoundingInfo = function () {
  19577. if (this.IsGlobal) {
  19578. return this._mesh.getBoundingInfo();
  19579. }
  19580. return this._boundingInfo;
  19581. };
  19582. SubMesh.prototype.getMesh = function () {
  19583. return this._mesh;
  19584. };
  19585. SubMesh.prototype.getRenderingMesh = function () {
  19586. return this._renderingMesh;
  19587. };
  19588. SubMesh.prototype.getMaterial = function () {
  19589. var rootMaterial = this._renderingMesh.material;
  19590. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  19591. var multiMaterial = rootMaterial;
  19592. return multiMaterial.getSubMaterial(this.materialIndex);
  19593. }
  19594. if (!rootMaterial) {
  19595. return this._mesh.getScene().defaultMaterial;
  19596. }
  19597. return rootMaterial;
  19598. };
  19599. // Methods
  19600. SubMesh.prototype.refreshBoundingInfo = function () {
  19601. this._lastColliderWorldVertices = null;
  19602. if (this.IsGlobal) {
  19603. return;
  19604. }
  19605. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19606. if (!data) {
  19607. this._boundingInfo = this._mesh._boundingInfo;
  19608. return;
  19609. }
  19610. var indices = this._renderingMesh.getIndices();
  19611. var extend;
  19612. //is this the only submesh?
  19613. if (this.indexStart === 0 && this.indexCount === indices.length) {
  19614. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  19615. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  19616. }
  19617. else {
  19618. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19619. }
  19620. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19621. };
  19622. SubMesh.prototype._checkCollision = function (collider) {
  19623. return this.getBoundingInfo()._checkCollision(collider);
  19624. };
  19625. SubMesh.prototype.updateBoundingInfo = function (world) {
  19626. if (!this.getBoundingInfo()) {
  19627. this.refreshBoundingInfo();
  19628. }
  19629. this.getBoundingInfo().update(world);
  19630. };
  19631. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19632. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19633. };
  19634. SubMesh.prototype.render = function (enableAlphaMode) {
  19635. this._renderingMesh.render(this, enableAlphaMode);
  19636. };
  19637. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19638. if (!this._linesIndexBuffer) {
  19639. var linesIndices = [];
  19640. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19641. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19642. }
  19643. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19644. this.linesIndexCount = linesIndices.length;
  19645. }
  19646. return this._linesIndexBuffer;
  19647. };
  19648. SubMesh.prototype.canIntersects = function (ray) {
  19649. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19650. };
  19651. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19652. var intersectInfo = null;
  19653. // LineMesh first as it's also a Mesh...
  19654. if (this._mesh instanceof BABYLON.LinesMesh) {
  19655. var lineMesh = this._mesh;
  19656. // Line test
  19657. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19658. var p0 = positions[indices[index]];
  19659. var p1 = positions[indices[index + 1]];
  19660. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19661. if (length < 0) {
  19662. continue;
  19663. }
  19664. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19665. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19666. if (fastCheck) {
  19667. break;
  19668. }
  19669. }
  19670. }
  19671. }
  19672. else {
  19673. // Triangles test
  19674. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19675. var p0 = positions[indices[index]];
  19676. var p1 = positions[indices[index + 1]];
  19677. var p2 = positions[indices[index + 2]];
  19678. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19679. if (currentIntersectInfo) {
  19680. if (currentIntersectInfo.distance < 0) {
  19681. continue;
  19682. }
  19683. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19684. intersectInfo = currentIntersectInfo;
  19685. intersectInfo.faceId = index / 3;
  19686. if (fastCheck) {
  19687. break;
  19688. }
  19689. }
  19690. }
  19691. }
  19692. }
  19693. return intersectInfo;
  19694. };
  19695. // Clone
  19696. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19697. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19698. if (!this.IsGlobal) {
  19699. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19700. }
  19701. return result;
  19702. };
  19703. // Dispose
  19704. SubMesh.prototype.dispose = function () {
  19705. if (this._linesIndexBuffer) {
  19706. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19707. this._linesIndexBuffer = null;
  19708. }
  19709. // Remove from mesh
  19710. var index = this._mesh.subMeshes.indexOf(this);
  19711. this._mesh.subMeshes.splice(index, 1);
  19712. };
  19713. // Statics
  19714. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19715. var minVertexIndex = Number.MAX_VALUE;
  19716. var maxVertexIndex = -Number.MAX_VALUE;
  19717. renderingMesh = renderingMesh || mesh;
  19718. var indices = renderingMesh.getIndices();
  19719. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19720. var vertexIndex = indices[index];
  19721. if (vertexIndex < minVertexIndex)
  19722. minVertexIndex = vertexIndex;
  19723. if (vertexIndex > maxVertexIndex)
  19724. maxVertexIndex = vertexIndex;
  19725. }
  19726. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19727. };
  19728. return SubMesh;
  19729. })();
  19730. BABYLON.SubMesh = SubMesh;
  19731. })(BABYLON || (BABYLON = {}));
  19732. var BABYLON;
  19733. (function (BABYLON) {
  19734. var MeshBuilder = (function () {
  19735. function MeshBuilder() {
  19736. }
  19737. /**
  19738. * Creates a box mesh.
  19739. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19740. * The parameter `size` sets the size (float) of each box side (default 1).
  19741. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19742. * 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).
  19743. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19744. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19745. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19747. */
  19748. MeshBuilder.CreateBox = function (name, options, scene) {
  19749. var box = new BABYLON.Mesh(name, scene);
  19750. var vertexData = BABYLON.VertexData.CreateBox(options);
  19751. vertexData.applyToMesh(box, options.updatable);
  19752. return box;
  19753. };
  19754. /**
  19755. * Creates a sphere mesh.
  19756. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19757. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19758. * 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`).
  19759. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19760. * 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
  19761. * 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).
  19762. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19763. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19765. */
  19766. MeshBuilder.CreateSphere = function (name, options, scene) {
  19767. var sphere = new BABYLON.Mesh(name, scene);
  19768. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19769. vertexData.applyToMesh(sphere, options.updatable);
  19770. return sphere;
  19771. };
  19772. /**
  19773. * Creates a plane polygonal mesh. By default, this is a disc.
  19774. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19775. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19776. * 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.
  19777. * 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
  19778. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19779. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19781. */
  19782. MeshBuilder.CreateDisc = function (name, options, scene) {
  19783. var disc = new BABYLON.Mesh(name, scene);
  19784. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19785. vertexData.applyToMesh(disc, options.updatable);
  19786. return disc;
  19787. };
  19788. /**
  19789. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19790. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19791. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19792. * 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`).
  19793. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19794. * 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.
  19795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19796. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19798. */
  19799. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19800. var sphere = new BABYLON.Mesh(name, scene);
  19801. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19802. vertexData.applyToMesh(sphere, options.updatable);
  19803. return sphere;
  19804. };
  19805. ;
  19806. /**
  19807. * Creates a ribbon mesh.
  19808. * 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.
  19809. *
  19810. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19811. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19812. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19813. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19814. * 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.
  19815. * 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.
  19816. * 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
  19817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19820. */
  19821. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19822. var pathArray = options.pathArray;
  19823. var closeArray = options.closeArray;
  19824. var closePath = options.closePath;
  19825. var offset = options.offset;
  19826. var sideOrientation = options.sideOrientation;
  19827. var instance = options.instance;
  19828. var updatable = options.updatable;
  19829. if (instance) {
  19830. // positionFunction : ribbon case
  19831. // only pathArray and sideOrientation parameters are taken into account for positions update
  19832. var positionFunction = function (positions) {
  19833. var minlg = pathArray[0].length;
  19834. var i = 0;
  19835. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19836. for (var si = 1; si <= ns; si++) {
  19837. for (var p = 0; p < pathArray.length; p++) {
  19838. var path = pathArray[p];
  19839. var l = path.length;
  19840. minlg = (minlg < l) ? minlg : l;
  19841. var j = 0;
  19842. while (j < minlg) {
  19843. positions[i] = path[j].x;
  19844. positions[i + 1] = path[j].y;
  19845. positions[i + 2] = path[j].z;
  19846. j++;
  19847. i += 3;
  19848. }
  19849. if (instance._closePath) {
  19850. positions[i] = path[0].x;
  19851. positions[i + 1] = path[0].y;
  19852. positions[i + 2] = path[0].z;
  19853. i += 3;
  19854. }
  19855. }
  19856. }
  19857. };
  19858. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19859. positionFunction(positions);
  19860. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19861. if (!(instance.areNormalsFrozen)) {
  19862. var indices = instance.getIndices();
  19863. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19864. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19865. if (instance._closePath) {
  19866. var indexFirst = 0;
  19867. var indexLast = 0;
  19868. for (var p = 0; p < pathArray.length; p++) {
  19869. indexFirst = instance._idx[p] * 3;
  19870. if (p + 1 < pathArray.length) {
  19871. indexLast = (instance._idx[p + 1] - 1) * 3;
  19872. }
  19873. else {
  19874. indexLast = normals.length - 3;
  19875. }
  19876. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19877. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19878. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19879. normals[indexLast] = normals[indexFirst];
  19880. normals[indexLast + 1] = normals[indexFirst + 1];
  19881. normals[indexLast + 2] = normals[indexFirst + 2];
  19882. }
  19883. }
  19884. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19885. }
  19886. return instance;
  19887. }
  19888. else {
  19889. var ribbon = new BABYLON.Mesh(name, scene);
  19890. ribbon.sideOrientation = sideOrientation;
  19891. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19892. if (closePath) {
  19893. ribbon._idx = vertexData._idx;
  19894. }
  19895. ribbon._closePath = closePath;
  19896. ribbon._closeArray = closeArray;
  19897. vertexData.applyToMesh(ribbon, updatable);
  19898. return ribbon;
  19899. }
  19900. };
  19901. /**
  19902. * Creates a cylinder or a cone mesh.
  19903. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19904. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19905. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19906. * 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.
  19907. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19908. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19909. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19910. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19911. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19912. * 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).
  19913. * 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
  19914. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19915. * 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
  19916. * 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.
  19917. * If `enclose` is false, a ring surface is one element.
  19918. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19919. * 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
  19920. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19921. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19923. */
  19924. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19925. var cylinder = new BABYLON.Mesh(name, scene);
  19926. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19927. vertexData.applyToMesh(cylinder, options.updatable);
  19928. return cylinder;
  19929. };
  19930. /**
  19931. * Creates a torus mesh.
  19932. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19933. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19934. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19935. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19936. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19937. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19939. */
  19940. MeshBuilder.CreateTorus = function (name, options, scene) {
  19941. var torus = new BABYLON.Mesh(name, scene);
  19942. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19943. vertexData.applyToMesh(torus, options.updatable);
  19944. return torus;
  19945. };
  19946. /**
  19947. * Creates a torus knot mesh.
  19948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19949. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19950. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19951. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19952. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19956. */
  19957. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19958. var torusKnot = new BABYLON.Mesh(name, scene);
  19959. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19960. vertexData.applyToMesh(torusKnot, options.updatable);
  19961. return torusKnot;
  19962. };
  19963. /**
  19964. * Creates a line system mesh.
  19965. * A line system is a pool of many lines gathered in a single mesh.
  19966. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19967. * 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.
  19968. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19969. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19970. * 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
  19971. * 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
  19972. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19974. */
  19975. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19976. var instance = options.instance;
  19977. var lines = options.lines;
  19978. if (instance) {
  19979. var positionFunction = function (positions) {
  19980. var i = 0;
  19981. for (var l = 0; l < lines.length; l++) {
  19982. var points = lines[l];
  19983. for (var p = 0; p < points.length; p++) {
  19984. positions[i] = points[p].x;
  19985. positions[i + 1] = points[p].y;
  19986. positions[i + 2] = points[p].z;
  19987. i += 3;
  19988. }
  19989. }
  19990. };
  19991. instance.updateMeshPositions(positionFunction, false);
  19992. return instance;
  19993. }
  19994. // line system creation
  19995. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19996. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19997. vertexData.applyToMesh(lineSystem, options.updatable);
  19998. return lineSystem;
  19999. };
  20000. /**
  20001. * Creates a line mesh.
  20002. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  20003. * 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.
  20004. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20005. * The parameter `points` is an array successive Vector3.
  20006. * 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
  20007. * When updating an instance, remember that only point positions can change, not the number of points.
  20008. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20009. */
  20010. MeshBuilder.CreateLines = function (name, options, scene) {
  20011. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  20012. return lines;
  20013. };
  20014. /**
  20015. * Creates a dashed line mesh.
  20016. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  20017. * 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.
  20018. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20019. * The parameter `points` is an array successive Vector3.
  20020. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20021. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20022. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20023. * 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
  20024. * When updating an instance, remember that only point positions can change, not the number of points.
  20025. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20026. */
  20027. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  20028. var points = options.points;
  20029. var instance = options.instance;
  20030. var gapSize = options.gapSize;
  20031. var dashNb = options.dashNb;
  20032. var dashSize = options.dashSize;
  20033. if (instance) {
  20034. var positionFunction = function (positions) {
  20035. var curvect = BABYLON.Vector3.Zero();
  20036. var nbSeg = positions.length / 6;
  20037. var lg = 0;
  20038. var nb = 0;
  20039. var shft = 0;
  20040. var dashshft = 0;
  20041. var curshft = 0;
  20042. var p = 0;
  20043. var i = 0;
  20044. var j = 0;
  20045. for (i = 0; i < points.length - 1; i++) {
  20046. points[i + 1].subtractToRef(points[i], curvect);
  20047. lg += curvect.length();
  20048. }
  20049. shft = lg / nbSeg;
  20050. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  20051. for (i = 0; i < points.length - 1; i++) {
  20052. points[i + 1].subtractToRef(points[i], curvect);
  20053. nb = Math.floor(curvect.length() / shft);
  20054. curvect.normalize();
  20055. j = 0;
  20056. while (j < nb && p < positions.length) {
  20057. curshft = shft * j;
  20058. positions[p] = points[i].x + curshft * curvect.x;
  20059. positions[p + 1] = points[i].y + curshft * curvect.y;
  20060. positions[p + 2] = points[i].z + curshft * curvect.z;
  20061. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  20062. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  20063. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  20064. p += 6;
  20065. j++;
  20066. }
  20067. }
  20068. while (p < positions.length) {
  20069. positions[p] = points[i].x;
  20070. positions[p + 1] = points[i].y;
  20071. positions[p + 2] = points[i].z;
  20072. p += 3;
  20073. }
  20074. };
  20075. instance.updateMeshPositions(positionFunction, false);
  20076. return instance;
  20077. }
  20078. // dashed lines creation
  20079. var dashedLines = new BABYLON.LinesMesh(name, scene);
  20080. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  20081. vertexData.applyToMesh(dashedLines, options.updatable);
  20082. dashedLines.dashSize = dashSize;
  20083. dashedLines.gapSize = gapSize;
  20084. return dashedLines;
  20085. };
  20086. /**
  20087. * Creates an extruded shape mesh.
  20088. * 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.
  20089. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  20090. *
  20091. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20092. * 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
  20093. * extruded along the Z axis.
  20094. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20095. * 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.
  20096. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20097. * 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
  20098. * 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
  20099. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20100. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20101. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20103. */
  20104. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  20105. var path = options.path;
  20106. var shape = options.shape;
  20107. var scale = options.scale || 1;
  20108. var rotation = options.rotation || 0;
  20109. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20110. var updatable = options.updatable;
  20111. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20112. var instance = options.instance;
  20113. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  20114. };
  20115. /**
  20116. * Creates an custom extruded shape mesh.
  20117. * 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.
  20118. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  20119. *
  20120. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20121. * 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
  20122. * extruded along the Z axis.
  20123. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20124. * 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
  20125. * and the distance of this point from the begining of the path :
  20126. * ```rotationFunction = function(i, distance) {
  20127. * // do things
  20128. * return rotationValue; }```
  20129. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20130. * 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
  20131. * and the distance of this point from the begining of the path :
  20132. * ````scaleFunction = function(i, distance) {
  20133. * // do things
  20134. * return scaleValue;}```
  20135. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20136. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20137. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20138. * 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
  20139. * 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
  20140. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20141. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20142. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20143. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20144. */
  20145. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  20146. var path = options.path;
  20147. var shape = options.shape;
  20148. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20149. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20150. var ribbonCloseArray = options.ribbonCloseArray || false;
  20151. var ribbonClosePath = options.ribbonClosePath || false;
  20152. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20153. var updatable = options.updatable;
  20154. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20155. var instance = options.instance;
  20156. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  20157. };
  20158. /**
  20159. * Creates lathe mesh.
  20160. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20161. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20162. *
  20163. * 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
  20164. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20165. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20166. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20167. * 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.
  20168. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20169. * 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
  20170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20173. */
  20174. MeshBuilder.CreateLathe = function (name, options, scene) {
  20175. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20176. var closed = (options.closed === undefined) ? true : options.closed;
  20177. var shape = options.shape;
  20178. var radius = options.radius || 1;
  20179. var tessellation = options.tessellation || 64;
  20180. var updatable = options.updatable;
  20181. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20182. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20183. var pi2 = Math.PI * 2;
  20184. var paths = new Array();
  20185. var i = 0;
  20186. var p = 0;
  20187. var step = pi2 / tessellation * arc;
  20188. var rotated;
  20189. var path = new Array();
  20190. ;
  20191. for (i = 0; i <= tessellation; i++) {
  20192. var path = [];
  20193. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20194. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20195. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20196. }
  20197. for (p = 0; p < shape.length; p++) {
  20198. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20199. path.push(rotated);
  20200. }
  20201. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20202. 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));
  20203. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20204. }
  20205. paths.push(path);
  20206. }
  20207. // lathe ribbon
  20208. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  20209. return lathe;
  20210. };
  20211. /**
  20212. * Creates a plane mesh.
  20213. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20214. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20215. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20216. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  20217. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20218. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20219. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20220. */
  20221. MeshBuilder.CreatePlane = function (name, options, scene) {
  20222. var plane = new BABYLON.Mesh(name, scene);
  20223. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20224. vertexData.applyToMesh(plane, options.updatable);
  20225. if (options.sourcePlane) {
  20226. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20227. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20228. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20229. plane.rotate(vectorProduct, product);
  20230. }
  20231. return plane;
  20232. };
  20233. /**
  20234. * Creates a ground mesh.
  20235. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20236. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20237. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20238. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20239. */
  20240. MeshBuilder.CreateGround = function (name, options, scene) {
  20241. var ground = new BABYLON.GroundMesh(name, scene);
  20242. ground._setReady(false);
  20243. ground._subdivisions = options.subdivisions || 1;
  20244. ground._width = options.width || 1;
  20245. ground._height = options.height || 1;
  20246. ground._maxX = ground._width / 2;
  20247. ground._maxZ = ground._height / 2;
  20248. ground._minX = -ground._maxX;
  20249. ground._minZ = -ground._maxZ;
  20250. var vertexData = BABYLON.VertexData.CreateGround(options);
  20251. vertexData.applyToMesh(ground, options.updatable);
  20252. ground._setReady(true);
  20253. return ground;
  20254. };
  20255. /**
  20256. * Creates a tiled ground mesh.
  20257. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  20258. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20259. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20260. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20261. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20262. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20263. * numbers of subdivisions on the ground width and height of each tile.
  20264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20265. */
  20266. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  20267. var tiledGround = new BABYLON.Mesh(name, scene);
  20268. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  20269. vertexData.applyToMesh(tiledGround, options.updatable);
  20270. return tiledGround;
  20271. };
  20272. /**
  20273. * Creates a ground mesh from a height map.
  20274. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20275. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  20276. * The parameter `url` sets the URL of the height map image resource.
  20277. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20278. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20279. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20280. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20281. * 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).
  20282. * This function is passed the newly built mesh : ```function(mesh) { // do things
  20283. * return; }```
  20284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20285. */
  20286. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20287. var width = options.width || 10;
  20288. var height = options.height || 10;
  20289. var subdivisions = options.subdivisions || 1;
  20290. var minHeight = options.minHeight;
  20291. var maxHeight = options.maxHeight || 10;
  20292. var updatable = options.updatable;
  20293. var onReady = options.onReady;
  20294. var ground = new BABYLON.GroundMesh(name, scene);
  20295. ground._subdivisions = subdivisions;
  20296. ground._width = width;
  20297. ground._height = height;
  20298. ground._maxX = ground._width / 2;
  20299. ground._maxZ = ground._height / 2;
  20300. ground._minX = -ground._maxX;
  20301. ground._minZ = -ground._maxZ;
  20302. ground._setReady(false);
  20303. var onload = function (img) {
  20304. // Getting height map data
  20305. var canvas = document.createElement("canvas");
  20306. var context = canvas.getContext("2d");
  20307. var bufferWidth = img.width;
  20308. var bufferHeight = img.height;
  20309. canvas.width = bufferWidth;
  20310. canvas.height = bufferHeight;
  20311. context.drawImage(img, 0, 0);
  20312. // Create VertexData from map data
  20313. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20314. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  20315. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  20316. width: width, height: height,
  20317. subdivisions: subdivisions,
  20318. minHeight: minHeight, maxHeight: maxHeight,
  20319. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  20320. });
  20321. vertexData.applyToMesh(ground, updatable);
  20322. ground._setReady(true);
  20323. //execute ready callback, if set
  20324. if (onReady) {
  20325. onReady(ground);
  20326. }
  20327. };
  20328. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20329. return ground;
  20330. };
  20331. /**
  20332. * Creates a tube mesh.
  20333. * 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.
  20334. *
  20335. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  20336. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  20337. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20338. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20339. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20340. * 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.
  20341. * It must return a radius value (positive float) :
  20342. * ```var radiusFunction = function(i, distance) {
  20343. * // do things
  20344. * return radius; }```
  20345. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  20346. * 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
  20347. * 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
  20348. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20349. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20350. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20351. */
  20352. MeshBuilder.CreateTube = function (name, options, scene) {
  20353. var path = options.path;
  20354. var radius = options.radius || 1;
  20355. var tessellation = options.tessellation || 64;
  20356. var radiusFunction = options.radiusFunction;
  20357. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20358. var updatable = options.updatable;
  20359. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20360. var instance = options.instance;
  20361. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  20362. // tube geometry
  20363. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  20364. var tangents = path3D.getTangents();
  20365. var normals = path3D.getNormals();
  20366. var distances = path3D.getDistances();
  20367. var pi2 = Math.PI * 2;
  20368. var step = pi2 / tessellation * arc;
  20369. var returnRadius = function () { return radius; };
  20370. var radiusFunctionFinal = radiusFunction || returnRadius;
  20371. var circlePath;
  20372. var rad;
  20373. var normal;
  20374. var rotated;
  20375. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20376. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20377. for (var i = 0; i < path.length; i++) {
  20378. rad = radiusFunctionFinal(i, distances[i]); // current radius
  20379. circlePath = Array(); // current circle array
  20380. normal = normals[i]; // current normal
  20381. for (var t = 0; t < tessellation; t++) {
  20382. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  20383. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  20384. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  20385. rotated.scaleInPlace(rad).addInPlace(path[i]);
  20386. circlePath[t] = rotated;
  20387. }
  20388. circlePaths[index] = circlePath;
  20389. index++;
  20390. }
  20391. // cap
  20392. var capPath = function (nbPoints, pathIndex) {
  20393. var pointCap = Array();
  20394. for (var i = 0; i < nbPoints; i++) {
  20395. pointCap.push(path[pathIndex]);
  20396. }
  20397. return pointCap;
  20398. };
  20399. switch (cap) {
  20400. case BABYLON.Mesh.NO_CAP:
  20401. break;
  20402. case BABYLON.Mesh.CAP_START:
  20403. circlePaths[0] = capPath(tessellation, 0);
  20404. circlePaths[1] = circlePaths[2].slice(0);
  20405. break;
  20406. case BABYLON.Mesh.CAP_END:
  20407. circlePaths[index] = circlePaths[index - 1].slice(0);
  20408. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20409. break;
  20410. case BABYLON.Mesh.CAP_ALL:
  20411. circlePaths[0] = capPath(tessellation, 0);
  20412. circlePaths[1] = circlePaths[2].slice(0);
  20413. circlePaths[index] = circlePaths[index - 1].slice(0);
  20414. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20415. break;
  20416. default:
  20417. break;
  20418. }
  20419. return circlePaths;
  20420. };
  20421. var path3D;
  20422. var pathArray;
  20423. if (instance) {
  20424. var arc = options.arc || instance.arc;
  20425. path3D = (instance.path3D).update(path);
  20426. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  20427. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  20428. instance.path3D = path3D;
  20429. instance.pathArray = pathArray;
  20430. instance.arc = arc;
  20431. return instance;
  20432. }
  20433. // tube creation
  20434. path3D = new BABYLON.Path3D(path);
  20435. var newPathArray = new Array();
  20436. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20437. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  20438. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  20439. tube.pathArray = pathArray;
  20440. tube.path3D = path3D;
  20441. tube.tessellation = tessellation;
  20442. tube.cap = cap;
  20443. tube.arc = options.arc;
  20444. return tube;
  20445. };
  20446. /**
  20447. * Creates a polyhedron mesh.
  20448. *
  20449. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  20450. * 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
  20451. * to choose the wanted type.
  20452. * The parameter `size` (positive float, default 1) sets the polygon size.
  20453. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20454. * 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`.
  20455. * 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
  20456. * 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)`).
  20457. * 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
  20458. * 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.
  20459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20460. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20462. */
  20463. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  20464. var polyhedron = new BABYLON.Mesh(name, scene);
  20465. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  20466. vertexData.applyToMesh(polyhedron, options.updatable);
  20467. return polyhedron;
  20468. };
  20469. /**
  20470. * Creates a decal mesh.
  20471. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  20472. * 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.
  20473. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20474. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20475. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  20476. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20477. */
  20478. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  20479. var indices = sourceMesh.getIndices();
  20480. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20481. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20482. var position = options.position || BABYLON.Vector3.Zero();
  20483. var normal = options.normal || BABYLON.Vector3.Up();
  20484. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  20485. var angle = options.angle || 0;
  20486. // Getting correct rotation
  20487. if (!normal) {
  20488. var target = new BABYLON.Vector3(0, 0, 1);
  20489. var camera = sourceMesh.getScene().activeCamera;
  20490. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  20491. normal = camera.globalPosition.subtract(cameraWorldTarget);
  20492. }
  20493. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  20494. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  20495. var pitch = Math.atan2(normal.y, len);
  20496. // Matrix
  20497. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  20498. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  20499. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  20500. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  20501. var vertexData = new BABYLON.VertexData();
  20502. vertexData.indices = [];
  20503. vertexData.positions = [];
  20504. vertexData.normals = [];
  20505. vertexData.uvs = [];
  20506. var currentVertexDataIndex = 0;
  20507. var extractDecalVector3 = function (indexId) {
  20508. var vertexId = indices[indexId];
  20509. var result = new BABYLON.PositionNormalVertex();
  20510. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  20511. // Send vector to decal local world
  20512. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  20513. // Get normal
  20514. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  20515. return result;
  20516. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  20517. var clip = function (vertices, axis) {
  20518. if (vertices.length === 0) {
  20519. return vertices;
  20520. }
  20521. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  20522. var clipVertices = function (v0, v1) {
  20523. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  20524. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  20525. };
  20526. var result = new Array();
  20527. for (var index = 0; index < vertices.length; index += 3) {
  20528. var v1Out;
  20529. var v2Out;
  20530. var v3Out;
  20531. var total = 0;
  20532. var nV1, nV2, nV3, nV4;
  20533. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  20534. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  20535. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  20536. v1Out = d1 > 0;
  20537. v2Out = d2 > 0;
  20538. v3Out = d3 > 0;
  20539. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  20540. switch (total) {
  20541. case 0:
  20542. result.push(vertices[index]);
  20543. result.push(vertices[index + 1]);
  20544. result.push(vertices[index + 2]);
  20545. break;
  20546. case 1:
  20547. if (v1Out) {
  20548. nV1 = vertices[index + 1];
  20549. nV2 = vertices[index + 2];
  20550. nV3 = clipVertices(vertices[index], nV1);
  20551. nV4 = clipVertices(vertices[index], nV2);
  20552. }
  20553. if (v2Out) {
  20554. nV1 = vertices[index];
  20555. nV2 = vertices[index + 2];
  20556. nV3 = clipVertices(vertices[index + 1], nV1);
  20557. nV4 = clipVertices(vertices[index + 1], nV2);
  20558. result.push(nV3);
  20559. result.push(nV2.clone());
  20560. result.push(nV1.clone());
  20561. result.push(nV2.clone());
  20562. result.push(nV3.clone());
  20563. result.push(nV4);
  20564. break;
  20565. }
  20566. if (v3Out) {
  20567. nV1 = vertices[index];
  20568. nV2 = vertices[index + 1];
  20569. nV3 = clipVertices(vertices[index + 2], nV1);
  20570. nV4 = clipVertices(vertices[index + 2], nV2);
  20571. }
  20572. result.push(nV1.clone());
  20573. result.push(nV2.clone());
  20574. result.push(nV3);
  20575. result.push(nV4);
  20576. result.push(nV3.clone());
  20577. result.push(nV2.clone());
  20578. break;
  20579. case 2:
  20580. if (!v1Out) {
  20581. nV1 = vertices[index].clone();
  20582. nV2 = clipVertices(nV1, vertices[index + 1]);
  20583. nV3 = clipVertices(nV1, vertices[index + 2]);
  20584. result.push(nV1);
  20585. result.push(nV2);
  20586. result.push(nV3);
  20587. }
  20588. if (!v2Out) {
  20589. nV1 = vertices[index + 1].clone();
  20590. nV2 = clipVertices(nV1, vertices[index + 2]);
  20591. nV3 = clipVertices(nV1, vertices[index]);
  20592. result.push(nV1);
  20593. result.push(nV2);
  20594. result.push(nV3);
  20595. }
  20596. if (!v3Out) {
  20597. nV1 = vertices[index + 2].clone();
  20598. nV2 = clipVertices(nV1, vertices[index]);
  20599. nV3 = clipVertices(nV1, vertices[index + 1]);
  20600. result.push(nV1);
  20601. result.push(nV2);
  20602. result.push(nV3);
  20603. }
  20604. break;
  20605. case 3:
  20606. break;
  20607. }
  20608. }
  20609. return result;
  20610. };
  20611. for (var index = 0; index < indices.length; index += 3) {
  20612. var faceVertices = new Array();
  20613. faceVertices.push(extractDecalVector3(index));
  20614. faceVertices.push(extractDecalVector3(index + 1));
  20615. faceVertices.push(extractDecalVector3(index + 2));
  20616. // Clip
  20617. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20618. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20619. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20620. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20621. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20622. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20623. if (faceVertices.length === 0) {
  20624. continue;
  20625. }
  20626. // Add UVs and get back to world
  20627. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20628. var vertex = faceVertices[vIndex];
  20629. //TODO check for Int32Array
  20630. vertexData.indices.push(currentVertexDataIndex);
  20631. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20632. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20633. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20634. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20635. currentVertexDataIndex++;
  20636. }
  20637. }
  20638. // Return mesh
  20639. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20640. vertexData.applyToMesh(decal);
  20641. decal.position = position.clone();
  20642. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20643. return decal;
  20644. };
  20645. // Privates
  20646. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20647. // extrusion geometry
  20648. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20649. var tangents = path3D.getTangents();
  20650. var normals = path3D.getNormals();
  20651. var binormals = path3D.getBinormals();
  20652. var distances = path3D.getDistances();
  20653. var angle = 0;
  20654. var returnScale = function () { return scale; };
  20655. var returnRotation = function () { return rotation; };
  20656. var rotate = custom ? rotateFunction : returnRotation;
  20657. var scl = custom ? scaleFunction : returnScale;
  20658. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20659. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20660. for (var i = 0; i < curve.length; i++) {
  20661. var shapePath = new Array();
  20662. var angleStep = rotate(i, distances[i]);
  20663. var scaleRatio = scl(i, distances[i]);
  20664. for (var p = 0; p < shape.length; p++) {
  20665. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20666. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20667. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20668. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20669. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20670. shapePath[p] = rotated;
  20671. }
  20672. shapePaths[index] = shapePath;
  20673. angle += angleStep;
  20674. index++;
  20675. }
  20676. // cap
  20677. var capPath = function (shapePath) {
  20678. var pointCap = Array();
  20679. var barycenter = BABYLON.Vector3.Zero();
  20680. var i;
  20681. for (i = 0; i < shapePath.length; i++) {
  20682. barycenter.addInPlace(shapePath[i]);
  20683. }
  20684. barycenter.scaleInPlace(1 / shapePath.length);
  20685. for (i = 0; i < shapePath.length; i++) {
  20686. pointCap.push(barycenter);
  20687. }
  20688. return pointCap;
  20689. };
  20690. switch (cap) {
  20691. case BABYLON.Mesh.NO_CAP:
  20692. break;
  20693. case BABYLON.Mesh.CAP_START:
  20694. shapePaths[0] = capPath(shapePaths[2]);
  20695. shapePaths[1] = shapePaths[2].slice(0);
  20696. break;
  20697. case BABYLON.Mesh.CAP_END:
  20698. shapePaths[index] = shapePaths[index - 1];
  20699. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20700. break;
  20701. case BABYLON.Mesh.CAP_ALL:
  20702. shapePaths[0] = capPath(shapePaths[2]);
  20703. shapePaths[1] = shapePaths[2].slice(0);
  20704. shapePaths[index] = shapePaths[index - 1];
  20705. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20706. break;
  20707. default:
  20708. break;
  20709. }
  20710. return shapePaths;
  20711. };
  20712. var path3D;
  20713. var pathArray;
  20714. if (instance) {
  20715. path3D = (instance.path3D).update(curve);
  20716. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20717. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20718. return instance;
  20719. }
  20720. // extruded shape creation
  20721. path3D = new BABYLON.Path3D(curve);
  20722. var newShapePaths = new Array();
  20723. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20724. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20725. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20726. extrudedGeneric.pathArray = pathArray;
  20727. extrudedGeneric.path3D = path3D;
  20728. extrudedGeneric.cap = cap;
  20729. return extrudedGeneric;
  20730. };
  20731. return MeshBuilder;
  20732. })();
  20733. BABYLON.MeshBuilder = MeshBuilder;
  20734. })(BABYLON || (BABYLON = {}));
  20735. var BABYLON;
  20736. (function (BABYLON) {
  20737. var BaseTexture = (function () {
  20738. function BaseTexture(scene) {
  20739. this.hasAlpha = false;
  20740. this.getAlphaFromRGB = false;
  20741. this.level = 1;
  20742. this.coordinatesIndex = 0;
  20743. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20744. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20745. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20746. this.anisotropicFilteringLevel = 4;
  20747. this.isCube = false;
  20748. this.isRenderTarget = false;
  20749. this.animations = new Array();
  20750. /**
  20751. * An event triggered when the texture is disposed.
  20752. * @type {BABYLON.Observable}
  20753. */
  20754. this.onDisposeObservable = new BABYLON.Observable();
  20755. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20756. this._scene = scene;
  20757. this._scene.textures.push(this);
  20758. }
  20759. BaseTexture.prototype.toString = function () {
  20760. return this.name;
  20761. };
  20762. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20763. set: function (callback) {
  20764. if (this._onDisposeObserver) {
  20765. this.onDisposeObservable.remove(this._onDisposeObserver);
  20766. }
  20767. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20768. },
  20769. enumerable: true,
  20770. configurable: true
  20771. });
  20772. BaseTexture.prototype.getScene = function () {
  20773. return this._scene;
  20774. };
  20775. BaseTexture.prototype.getTextureMatrix = function () {
  20776. return null;
  20777. };
  20778. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20779. return null;
  20780. };
  20781. BaseTexture.prototype.getInternalTexture = function () {
  20782. return this._texture;
  20783. };
  20784. BaseTexture.prototype.isReady = function () {
  20785. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20786. return true;
  20787. }
  20788. if (this._texture) {
  20789. return this._texture.isReady;
  20790. }
  20791. return false;
  20792. };
  20793. BaseTexture.prototype.getSize = function () {
  20794. if (this._texture._width) {
  20795. return { width: this._texture._width, height: this._texture._height };
  20796. }
  20797. if (this._texture._size) {
  20798. return { width: this._texture._size, height: this._texture._size };
  20799. }
  20800. return { width: 0, height: 0 };
  20801. };
  20802. BaseTexture.prototype.getBaseSize = function () {
  20803. if (!this.isReady() || !this._texture)
  20804. return { width: 0, height: 0 };
  20805. if (this._texture._size) {
  20806. return { width: this._texture._size, height: this._texture._size };
  20807. }
  20808. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20809. };
  20810. BaseTexture.prototype.scale = function (ratio) {
  20811. };
  20812. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20813. get: function () {
  20814. return false;
  20815. },
  20816. enumerable: true,
  20817. configurable: true
  20818. });
  20819. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20820. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20821. for (var index = 0; index < texturesCache.length; index++) {
  20822. var texturesCacheEntry = texturesCache[index];
  20823. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20824. texturesCache.splice(index, 1);
  20825. return;
  20826. }
  20827. }
  20828. };
  20829. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20830. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20831. for (var index = 0; index < texturesCache.length; index++) {
  20832. var texturesCacheEntry = texturesCache[index];
  20833. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20834. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20835. texturesCacheEntry.references++;
  20836. return texturesCacheEntry;
  20837. }
  20838. }
  20839. }
  20840. return null;
  20841. };
  20842. BaseTexture.prototype.delayLoad = function () {
  20843. };
  20844. BaseTexture.prototype.clone = function () {
  20845. return null;
  20846. };
  20847. BaseTexture.prototype.releaseInternalTexture = function () {
  20848. if (this._texture) {
  20849. this._scene.getEngine().releaseInternalTexture(this._texture);
  20850. delete this._texture;
  20851. }
  20852. };
  20853. BaseTexture.prototype.dispose = function () {
  20854. // Animations
  20855. this.getScene().stopAnimation(this);
  20856. // Remove from scene
  20857. var index = this._scene.textures.indexOf(this);
  20858. if (index >= 0) {
  20859. this._scene.textures.splice(index, 1);
  20860. }
  20861. if (this._texture === undefined) {
  20862. return;
  20863. }
  20864. // Release
  20865. this.releaseInternalTexture();
  20866. // Callback
  20867. this.onDisposeObservable.notifyObservers(this);
  20868. this.onDisposeObservable.clear();
  20869. };
  20870. BaseTexture.prototype.serialize = function () {
  20871. if (!this.name) {
  20872. return null;
  20873. }
  20874. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20875. // Animations
  20876. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20877. return serializationObject;
  20878. };
  20879. __decorate([
  20880. BABYLON.serialize()
  20881. ], BaseTexture.prototype, "name", void 0);
  20882. __decorate([
  20883. BABYLON.serialize()
  20884. ], BaseTexture.prototype, "hasAlpha", void 0);
  20885. __decorate([
  20886. BABYLON.serialize()
  20887. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20888. __decorate([
  20889. BABYLON.serialize()
  20890. ], BaseTexture.prototype, "level", void 0);
  20891. __decorate([
  20892. BABYLON.serialize()
  20893. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20894. __decorate([
  20895. BABYLON.serialize()
  20896. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20897. __decorate([
  20898. BABYLON.serialize()
  20899. ], BaseTexture.prototype, "wrapU", void 0);
  20900. __decorate([
  20901. BABYLON.serialize()
  20902. ], BaseTexture.prototype, "wrapV", void 0);
  20903. __decorate([
  20904. BABYLON.serialize()
  20905. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20906. __decorate([
  20907. BABYLON.serialize()
  20908. ], BaseTexture.prototype, "isCube", void 0);
  20909. __decorate([
  20910. BABYLON.serialize()
  20911. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20912. return BaseTexture;
  20913. })();
  20914. BABYLON.BaseTexture = BaseTexture;
  20915. })(BABYLON || (BABYLON = {}));
  20916. var BABYLON;
  20917. (function (BABYLON) {
  20918. var Texture = (function (_super) {
  20919. __extends(Texture, _super);
  20920. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20921. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20922. if (onLoad === void 0) { onLoad = null; }
  20923. if (onError === void 0) { onError = null; }
  20924. if (buffer === void 0) { buffer = null; }
  20925. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20926. _super.call(this, scene);
  20927. this.uOffset = 0;
  20928. this.vOffset = 0;
  20929. this.uScale = 1.0;
  20930. this.vScale = 1.0;
  20931. this.uAng = 0;
  20932. this.vAng = 0;
  20933. this.wAng = 0;
  20934. this.name = url;
  20935. this.url = url;
  20936. this._noMipmap = noMipmap;
  20937. this._invertY = invertY;
  20938. this._samplingMode = samplingMode;
  20939. this._buffer = buffer;
  20940. this._deleteBuffer = deleteBuffer;
  20941. if (!url) {
  20942. return;
  20943. }
  20944. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20945. if (!this._texture) {
  20946. if (!scene.useDelayedTextureLoading) {
  20947. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20948. if (deleteBuffer) {
  20949. delete this._buffer;
  20950. }
  20951. }
  20952. else {
  20953. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20954. this._delayedOnLoad = onLoad;
  20955. this._delayedOnError = onError;
  20956. }
  20957. }
  20958. else {
  20959. BABYLON.Tools.SetImmediate(function () {
  20960. if (onLoad) {
  20961. onLoad();
  20962. }
  20963. });
  20964. }
  20965. }
  20966. Object.defineProperty(Texture.prototype, "noMipmap", {
  20967. get: function () {
  20968. return this._noMipmap;
  20969. },
  20970. enumerable: true,
  20971. configurable: true
  20972. });
  20973. Texture.prototype.delayLoad = function () {
  20974. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20975. return;
  20976. }
  20977. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20978. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20979. if (!this._texture) {
  20980. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20981. if (this._deleteBuffer) {
  20982. delete this._buffer;
  20983. }
  20984. }
  20985. };
  20986. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20987. if (!this._texture) {
  20988. return;
  20989. }
  20990. this._samplingMode = samplingMode;
  20991. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20992. };
  20993. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20994. x *= this.uScale;
  20995. y *= this.vScale;
  20996. x -= 0.5 * this.uScale;
  20997. y -= 0.5 * this.vScale;
  20998. z -= 0.5;
  20999. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21000. t.x += 0.5 * this.uScale + this.uOffset;
  21001. t.y += 0.5 * this.vScale + this.vOffset;
  21002. t.z += 0.5;
  21003. };
  21004. Texture.prototype.getTextureMatrix = function () {
  21005. if (this.uOffset === this._cachedUOffset &&
  21006. this.vOffset === this._cachedVOffset &&
  21007. this.uScale === this._cachedUScale &&
  21008. this.vScale === this._cachedVScale &&
  21009. this.uAng === this._cachedUAng &&
  21010. this.vAng === this._cachedVAng &&
  21011. this.wAng === this._cachedWAng) {
  21012. return this._cachedTextureMatrix;
  21013. }
  21014. this._cachedUOffset = this.uOffset;
  21015. this._cachedVOffset = this.vOffset;
  21016. this._cachedUScale = this.uScale;
  21017. this._cachedVScale = this.vScale;
  21018. this._cachedUAng = this.uAng;
  21019. this._cachedVAng = this.vAng;
  21020. this._cachedWAng = this.wAng;
  21021. if (!this._cachedTextureMatrix) {
  21022. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21023. this._rowGenerationMatrix = new BABYLON.Matrix();
  21024. this._t0 = BABYLON.Vector3.Zero();
  21025. this._t1 = BABYLON.Vector3.Zero();
  21026. this._t2 = BABYLON.Vector3.Zero();
  21027. }
  21028. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21029. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21030. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21031. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21032. this._t1.subtractInPlace(this._t0);
  21033. this._t2.subtractInPlace(this._t0);
  21034. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21035. this._cachedTextureMatrix.m[0] = this._t1.x;
  21036. this._cachedTextureMatrix.m[1] = this._t1.y;
  21037. this._cachedTextureMatrix.m[2] = this._t1.z;
  21038. this._cachedTextureMatrix.m[4] = this._t2.x;
  21039. this._cachedTextureMatrix.m[5] = this._t2.y;
  21040. this._cachedTextureMatrix.m[6] = this._t2.z;
  21041. this._cachedTextureMatrix.m[8] = this._t0.x;
  21042. this._cachedTextureMatrix.m[9] = this._t0.y;
  21043. this._cachedTextureMatrix.m[10] = this._t0.z;
  21044. return this._cachedTextureMatrix;
  21045. };
  21046. Texture.prototype.getReflectionTextureMatrix = function () {
  21047. if (this.uOffset === this._cachedUOffset &&
  21048. this.vOffset === this._cachedVOffset &&
  21049. this.uScale === this._cachedUScale &&
  21050. this.vScale === this._cachedVScale &&
  21051. this.coordinatesMode === this._cachedCoordinatesMode) {
  21052. return this._cachedTextureMatrix;
  21053. }
  21054. if (!this._cachedTextureMatrix) {
  21055. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21056. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21057. }
  21058. this._cachedCoordinatesMode = this.coordinatesMode;
  21059. switch (this.coordinatesMode) {
  21060. case Texture.PLANAR_MODE:
  21061. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21062. this._cachedTextureMatrix[0] = this.uScale;
  21063. this._cachedTextureMatrix[5] = this.vScale;
  21064. this._cachedTextureMatrix[12] = this.uOffset;
  21065. this._cachedTextureMatrix[13] = this.vOffset;
  21066. break;
  21067. case Texture.PROJECTION_MODE:
  21068. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21069. this._projectionModeMatrix.m[0] = 0.5;
  21070. this._projectionModeMatrix.m[5] = -0.5;
  21071. this._projectionModeMatrix.m[10] = 0.0;
  21072. this._projectionModeMatrix.m[12] = 0.5;
  21073. this._projectionModeMatrix.m[13] = 0.5;
  21074. this._projectionModeMatrix.m[14] = 1.0;
  21075. this._projectionModeMatrix.m[15] = 1.0;
  21076. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21077. break;
  21078. default:
  21079. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21080. break;
  21081. }
  21082. return this._cachedTextureMatrix;
  21083. };
  21084. Texture.prototype.clone = function () {
  21085. var _this = this;
  21086. return BABYLON.SerializationHelper.Clone(function () {
  21087. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21088. }, this);
  21089. };
  21090. // Statics
  21091. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  21092. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21093. if (onLoad === void 0) { onLoad = null; }
  21094. if (onError === void 0) { onError = null; }
  21095. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  21096. };
  21097. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21098. if (parsedTexture.isCube) {
  21099. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21100. }
  21101. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21102. return null;
  21103. }
  21104. var texture = BABYLON.SerializationHelper.Parse(function () {
  21105. if (parsedTexture.mirrorPlane) {
  21106. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21107. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21108. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21109. return mirrorTexture;
  21110. }
  21111. else if (parsedTexture.isRenderTarget) {
  21112. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21113. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21114. return renderTargetTexture;
  21115. }
  21116. else {
  21117. var texture;
  21118. if (parsedTexture.base64String) {
  21119. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21120. }
  21121. else {
  21122. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21123. }
  21124. return texture;
  21125. }
  21126. }, parsedTexture, scene);
  21127. // Animations
  21128. if (parsedTexture.animations) {
  21129. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21130. var parsedAnimation = parsedTexture.animations[animationIndex];
  21131. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21132. }
  21133. }
  21134. return texture;
  21135. };
  21136. // Constants
  21137. Texture.NEAREST_SAMPLINGMODE = 1;
  21138. Texture.BILINEAR_SAMPLINGMODE = 2;
  21139. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21140. Texture.EXPLICIT_MODE = 0;
  21141. Texture.SPHERICAL_MODE = 1;
  21142. Texture.PLANAR_MODE = 2;
  21143. Texture.CUBIC_MODE = 3;
  21144. Texture.PROJECTION_MODE = 4;
  21145. Texture.SKYBOX_MODE = 5;
  21146. Texture.INVCUBIC_MODE = 6;
  21147. Texture.EQUIRECTANGULAR_MODE = 7;
  21148. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21149. Texture.CLAMP_ADDRESSMODE = 0;
  21150. Texture.WRAP_ADDRESSMODE = 1;
  21151. Texture.MIRROR_ADDRESSMODE = 2;
  21152. __decorate([
  21153. BABYLON.serialize()
  21154. ], Texture.prototype, "url", void 0);
  21155. __decorate([
  21156. BABYLON.serialize()
  21157. ], Texture.prototype, "uOffset", void 0);
  21158. __decorate([
  21159. BABYLON.serialize()
  21160. ], Texture.prototype, "vOffset", void 0);
  21161. __decorate([
  21162. BABYLON.serialize()
  21163. ], Texture.prototype, "uScale", void 0);
  21164. __decorate([
  21165. BABYLON.serialize()
  21166. ], Texture.prototype, "vScale", void 0);
  21167. __decorate([
  21168. BABYLON.serialize()
  21169. ], Texture.prototype, "uAng", void 0);
  21170. __decorate([
  21171. BABYLON.serialize()
  21172. ], Texture.prototype, "vAng", void 0);
  21173. __decorate([
  21174. BABYLON.serialize()
  21175. ], Texture.prototype, "wAng", void 0);
  21176. return Texture;
  21177. })(BABYLON.BaseTexture);
  21178. BABYLON.Texture = Texture;
  21179. })(BABYLON || (BABYLON = {}));
  21180. var BABYLON;
  21181. (function (BABYLON) {
  21182. var CubeTexture = (function (_super) {
  21183. __extends(CubeTexture, _super);
  21184. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21185. _super.call(this, scene);
  21186. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21187. this.name = rootUrl;
  21188. this.url = rootUrl;
  21189. this._noMipmap = noMipmap;
  21190. this.hasAlpha = false;
  21191. if (!rootUrl && !files) {
  21192. return;
  21193. }
  21194. this._texture = this._getFromCache(rootUrl, noMipmap);
  21195. if (!files) {
  21196. if (!extensions) {
  21197. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21198. }
  21199. files = [];
  21200. for (var index = 0; index < extensions.length; index++) {
  21201. files.push(rootUrl + extensions[index]);
  21202. }
  21203. this._extensions = extensions;
  21204. }
  21205. this._files = files;
  21206. if (!this._texture) {
  21207. if (!scene.useDelayedTextureLoading) {
  21208. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21209. }
  21210. else {
  21211. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21212. }
  21213. }
  21214. this.isCube = true;
  21215. this._textureMatrix = BABYLON.Matrix.Identity();
  21216. }
  21217. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21218. return new CubeTexture("", scene, null, noMipmap, files);
  21219. };
  21220. // Methods
  21221. CubeTexture.prototype.delayLoad = function () {
  21222. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21223. return;
  21224. }
  21225. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21226. this._texture = this._getFromCache(this.url, this._noMipmap);
  21227. if (!this._texture) {
  21228. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  21229. }
  21230. };
  21231. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  21232. return this._textureMatrix;
  21233. };
  21234. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  21235. var texture = BABYLON.SerializationHelper.Parse(function () {
  21236. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  21237. }, parsedTexture, scene);
  21238. // Animations
  21239. if (parsedTexture.animations) {
  21240. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21241. var parsedAnimation = parsedTexture.animations[animationIndex];
  21242. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21243. }
  21244. }
  21245. return texture;
  21246. };
  21247. CubeTexture.prototype.clone = function () {
  21248. var _this = this;
  21249. return BABYLON.SerializationHelper.Clone(function () {
  21250. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  21251. }, this);
  21252. };
  21253. return CubeTexture;
  21254. })(BABYLON.BaseTexture);
  21255. BABYLON.CubeTexture = CubeTexture;
  21256. })(BABYLON || (BABYLON = {}));
  21257. var BABYLON;
  21258. (function (BABYLON) {
  21259. var RenderTargetTexture = (function (_super) {
  21260. __extends(RenderTargetTexture, _super);
  21261. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  21262. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  21263. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21264. if (isCube === void 0) { isCube = false; }
  21265. _super.call(this, null, scene, !generateMipMaps);
  21266. this.isCube = isCube;
  21267. /**
  21268. * Use this list to define the list of mesh you want to render.
  21269. */
  21270. this.renderList = new Array();
  21271. this.renderParticles = true;
  21272. this.renderSprites = false;
  21273. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  21274. // Events
  21275. /**
  21276. * An event triggered when the texture is unbind.
  21277. * @type {BABYLON.Observable}
  21278. */
  21279. this.onAfterUnbindObservable = new BABYLON.Observable();
  21280. /**
  21281. * An event triggered before rendering the texture
  21282. * @type {BABYLON.Observable}
  21283. */
  21284. this.onBeforeRenderObservable = new BABYLON.Observable();
  21285. /**
  21286. * An event triggered after rendering the texture
  21287. * @type {BABYLON.Observable}
  21288. */
  21289. this.onAfterRenderObservable = new BABYLON.Observable();
  21290. /**
  21291. * An event triggered after the texture clear
  21292. * @type {BABYLON.Observable}
  21293. */
  21294. this.onClearObservable = new BABYLON.Observable();
  21295. this._currentRefreshId = -1;
  21296. this._refreshRate = 1;
  21297. this.name = name;
  21298. this.isRenderTarget = true;
  21299. this._size = size;
  21300. this._generateMipMaps = generateMipMaps;
  21301. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  21302. if (isCube) {
  21303. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21304. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  21305. this._textureMatrix = BABYLON.Matrix.Identity();
  21306. }
  21307. else {
  21308. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  21309. }
  21310. // Rendering groups
  21311. this._renderingManager = new BABYLON.RenderingManager(scene);
  21312. }
  21313. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  21314. get: function () {
  21315. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  21321. get: function () {
  21322. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  21328. get: function () {
  21329. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  21330. },
  21331. enumerable: true,
  21332. configurable: true
  21333. });
  21334. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  21335. set: function (callback) {
  21336. if (this._onAfterUnbindObserver) {
  21337. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  21338. }
  21339. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  21340. },
  21341. enumerable: true,
  21342. configurable: true
  21343. });
  21344. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  21345. set: function (callback) {
  21346. if (this._onBeforeRenderObserver) {
  21347. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21348. }
  21349. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21350. },
  21351. enumerable: true,
  21352. configurable: true
  21353. });
  21354. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  21355. set: function (callback) {
  21356. if (this._onAfterRenderObserver) {
  21357. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21358. }
  21359. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21360. },
  21361. enumerable: true,
  21362. configurable: true
  21363. });
  21364. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  21365. set: function (callback) {
  21366. if (this._onClearObserver) {
  21367. this.onClearObservable.remove(this._onClearObserver);
  21368. }
  21369. this._onClearObserver = this.onClearObservable.add(callback);
  21370. },
  21371. enumerable: true,
  21372. configurable: true
  21373. });
  21374. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  21375. this._currentRefreshId = -1;
  21376. };
  21377. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  21378. get: function () {
  21379. return this._refreshRate;
  21380. },
  21381. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21382. set: function (value) {
  21383. this._refreshRate = value;
  21384. this.resetRefreshCounter();
  21385. },
  21386. enumerable: true,
  21387. configurable: true
  21388. });
  21389. RenderTargetTexture.prototype._shouldRender = function () {
  21390. if (this._currentRefreshId === -1) {
  21391. this._currentRefreshId = 1;
  21392. return true;
  21393. }
  21394. if (this.refreshRate === this._currentRefreshId) {
  21395. this._currentRefreshId = 1;
  21396. return true;
  21397. }
  21398. this._currentRefreshId++;
  21399. return false;
  21400. };
  21401. RenderTargetTexture.prototype.isReady = function () {
  21402. if (!this.getScene().renderTargetsEnabled) {
  21403. return false;
  21404. }
  21405. return _super.prototype.isReady.call(this);
  21406. };
  21407. RenderTargetTexture.prototype.getRenderSize = function () {
  21408. return this._size;
  21409. };
  21410. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  21411. get: function () {
  21412. return true;
  21413. },
  21414. enumerable: true,
  21415. configurable: true
  21416. });
  21417. RenderTargetTexture.prototype.scale = function (ratio) {
  21418. var newSize = this._size * ratio;
  21419. this.resize(newSize, this._generateMipMaps);
  21420. };
  21421. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  21422. if (this.isCube) {
  21423. return this._textureMatrix;
  21424. }
  21425. return _super.prototype.getReflectionTextureMatrix.call(this);
  21426. };
  21427. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  21428. this.releaseInternalTexture();
  21429. if (this.isCube) {
  21430. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  21431. }
  21432. else {
  21433. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21434. }
  21435. };
  21436. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  21437. var scene = this.getScene();
  21438. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21439. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  21440. }
  21441. if (this._waitingRenderList) {
  21442. this.renderList = [];
  21443. for (var index = 0; index < this._waitingRenderList.length; index++) {
  21444. var id = this._waitingRenderList[index];
  21445. this.renderList.push(scene.getMeshByID(id));
  21446. }
  21447. delete this._waitingRenderList;
  21448. }
  21449. // Is predicate defined?
  21450. if (this.renderListPredicate) {
  21451. this.renderList.splice(0); // Clear previous renderList
  21452. var sceneMeshes = this.getScene().meshes;
  21453. for (var index = 0; index < sceneMeshes.length; index++) {
  21454. var mesh = sceneMeshes[index];
  21455. if (this.renderListPredicate(mesh)) {
  21456. this.renderList.push(mesh);
  21457. }
  21458. }
  21459. }
  21460. if (this.renderList && this.renderList.length === 0) {
  21461. return;
  21462. }
  21463. // Prepare renderingManager
  21464. this._renderingManager.reset();
  21465. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  21466. var sceneRenderId = scene.getRenderId();
  21467. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  21468. var mesh = currentRenderList[meshIndex];
  21469. if (mesh) {
  21470. if (!mesh.isReady()) {
  21471. // Reset _currentRefreshId
  21472. this.resetRefreshCounter();
  21473. continue;
  21474. }
  21475. mesh._preActivateForIntermediateRendering(sceneRenderId);
  21476. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  21477. mesh._activate(sceneRenderId);
  21478. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  21479. var subMesh = mesh.subMeshes[subIndex];
  21480. scene._activeIndices += subMesh.indexCount;
  21481. this._renderingManager.dispatch(subMesh);
  21482. }
  21483. }
  21484. }
  21485. }
  21486. if (this.isCube) {
  21487. for (var face = 0; face < 6; face++) {
  21488. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  21489. scene.incrementRenderId();
  21490. scene.resetCachedMaterial();
  21491. }
  21492. }
  21493. else {
  21494. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  21495. }
  21496. this.onAfterUnbindObservable.notifyObservers(this);
  21497. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21498. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  21499. }
  21500. scene.resetCachedMaterial();
  21501. };
  21502. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  21503. var scene = this.getScene();
  21504. var engine = scene.getEngine();
  21505. // Bind
  21506. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  21507. if (this.isCube) {
  21508. engine.bindFramebuffer(this._texture, faceIndex);
  21509. }
  21510. else {
  21511. engine.bindFramebuffer(this._texture);
  21512. }
  21513. }
  21514. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  21515. // Clear
  21516. if (this.onClearObservable.hasObservers()) {
  21517. this.onClearObservable.notifyObservers(engine);
  21518. }
  21519. else {
  21520. engine.clear(scene.clearColor, true, true);
  21521. }
  21522. if (!this._doNotChangeAspectRatio) {
  21523. scene.updateTransformMatrix(true);
  21524. }
  21525. // Render
  21526. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  21527. if (useCameraPostProcess) {
  21528. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  21529. }
  21530. if (!this._doNotChangeAspectRatio) {
  21531. scene.updateTransformMatrix(true);
  21532. }
  21533. this.onAfterRenderObservable.notifyObservers(faceIndex);
  21534. // Dump ?
  21535. if (dumpForDebug) {
  21536. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  21537. }
  21538. // Unbind
  21539. if (!this.isCube || faceIndex === 5) {
  21540. if (this.isCube) {
  21541. if (faceIndex === 5) {
  21542. engine.generateMipMapsForCubemap(this._texture);
  21543. }
  21544. }
  21545. engine.unBindFramebuffer(this._texture, this.isCube);
  21546. }
  21547. };
  21548. RenderTargetTexture.prototype.clone = function () {
  21549. var textureSize = this.getSize();
  21550. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21551. // Base texture
  21552. newTexture.hasAlpha = this.hasAlpha;
  21553. newTexture.level = this.level;
  21554. // RenderTarget Texture
  21555. newTexture.coordinatesMode = this.coordinatesMode;
  21556. newTexture.renderList = this.renderList.slice(0);
  21557. return newTexture;
  21558. };
  21559. RenderTargetTexture.prototype.serialize = function () {
  21560. if (!this.name) {
  21561. return null;
  21562. }
  21563. var serializationObject = _super.prototype.serialize.call(this);
  21564. serializationObject.renderTargetSize = this.getRenderSize();
  21565. serializationObject.renderList = [];
  21566. for (var index = 0; index < this.renderList.length; index++) {
  21567. serializationObject.renderList.push(this.renderList[index].id);
  21568. }
  21569. return serializationObject;
  21570. };
  21571. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  21572. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  21573. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  21574. return RenderTargetTexture;
  21575. })(BABYLON.Texture);
  21576. BABYLON.RenderTargetTexture = RenderTargetTexture;
  21577. })(BABYLON || (BABYLON = {}));
  21578. var BABYLON;
  21579. (function (BABYLON) {
  21580. var ProceduralTexture = (function (_super) {
  21581. __extends(ProceduralTexture, _super);
  21582. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  21583. if (generateMipMaps === void 0) { generateMipMaps = true; }
  21584. if (isCube === void 0) { isCube = false; }
  21585. _super.call(this, null, scene, !generateMipMaps);
  21586. this.isCube = isCube;
  21587. this.isEnabled = true;
  21588. this._currentRefreshId = -1;
  21589. this._refreshRate = 1;
  21590. this._vertexDeclaration = [2];
  21591. this._vertexStrideSize = 2 * 4;
  21592. this._uniforms = new Array();
  21593. this._samplers = new Array();
  21594. this._textures = new Array();
  21595. this._floats = new Array();
  21596. this._floatsArrays = {};
  21597. this._colors3 = new Array();
  21598. this._colors4 = new Array();
  21599. this._vectors2 = new Array();
  21600. this._vectors3 = new Array();
  21601. this._matrices = new Array();
  21602. this._fallbackTextureUsed = false;
  21603. scene._proceduralTextures.push(this);
  21604. this.name = name;
  21605. this.isRenderTarget = true;
  21606. this._size = size;
  21607. this._generateMipMaps = generateMipMaps;
  21608. this.setFragment(fragment);
  21609. this._fallbackTexture = fallbackTexture;
  21610. if (isCube) {
  21611. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21612. this.setFloat("face", 0);
  21613. }
  21614. else {
  21615. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  21616. }
  21617. // VBO
  21618. var vertices = [];
  21619. vertices.push(1, 1);
  21620. vertices.push(-1, 1);
  21621. vertices.push(-1, -1);
  21622. vertices.push(1, -1);
  21623. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21624. // Indices
  21625. var indices = [];
  21626. indices.push(0);
  21627. indices.push(1);
  21628. indices.push(2);
  21629. indices.push(0);
  21630. indices.push(2);
  21631. indices.push(3);
  21632. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21633. }
  21634. ProceduralTexture.prototype.reset = function () {
  21635. if (this._effect === undefined) {
  21636. return;
  21637. }
  21638. var engine = this.getScene().getEngine();
  21639. engine._releaseEffect(this._effect);
  21640. };
  21641. ProceduralTexture.prototype.isReady = function () {
  21642. var _this = this;
  21643. var engine = this.getScene().getEngine();
  21644. var shaders;
  21645. if (!this._fragment) {
  21646. return false;
  21647. }
  21648. if (this._fallbackTextureUsed) {
  21649. return true;
  21650. }
  21651. if (this._fragment.fragmentElement !== undefined) {
  21652. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  21653. }
  21654. else {
  21655. shaders = { vertex: "procedural", fragment: this._fragment };
  21656. }
  21657. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  21658. _this.releaseInternalTexture();
  21659. if (_this._fallbackTexture) {
  21660. _this._texture = _this._fallbackTexture._texture;
  21661. _this._texture.references++;
  21662. }
  21663. _this._fallbackTextureUsed = true;
  21664. });
  21665. return this._effect.isReady();
  21666. };
  21667. ProceduralTexture.prototype.resetRefreshCounter = function () {
  21668. this._currentRefreshId = -1;
  21669. };
  21670. ProceduralTexture.prototype.setFragment = function (fragment) {
  21671. this._fragment = fragment;
  21672. };
  21673. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  21674. get: function () {
  21675. return this._refreshRate;
  21676. },
  21677. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21678. set: function (value) {
  21679. this._refreshRate = value;
  21680. this.resetRefreshCounter();
  21681. },
  21682. enumerable: true,
  21683. configurable: true
  21684. });
  21685. ProceduralTexture.prototype._shouldRender = function () {
  21686. if (!this.isEnabled || !this.isReady() || !this._texture) {
  21687. return false;
  21688. }
  21689. if (this._fallbackTextureUsed) {
  21690. return false;
  21691. }
  21692. if (this._currentRefreshId === -1) {
  21693. this._currentRefreshId = 1;
  21694. return true;
  21695. }
  21696. if (this.refreshRate === this._currentRefreshId) {
  21697. this._currentRefreshId = 1;
  21698. return true;
  21699. }
  21700. this._currentRefreshId++;
  21701. return false;
  21702. };
  21703. ProceduralTexture.prototype.getRenderSize = function () {
  21704. return this._size;
  21705. };
  21706. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  21707. if (this._fallbackTextureUsed) {
  21708. return;
  21709. }
  21710. this.releaseInternalTexture();
  21711. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21712. };
  21713. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21714. if (this._uniforms.indexOf(uniformName) === -1) {
  21715. this._uniforms.push(uniformName);
  21716. }
  21717. };
  21718. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21719. if (this._samplers.indexOf(name) === -1) {
  21720. this._samplers.push(name);
  21721. }
  21722. this._textures[name] = texture;
  21723. return this;
  21724. };
  21725. ProceduralTexture.prototype.setFloat = function (name, value) {
  21726. this._checkUniform(name);
  21727. this._floats[name] = value;
  21728. return this;
  21729. };
  21730. ProceduralTexture.prototype.setFloats = function (name, value) {
  21731. this._checkUniform(name);
  21732. this._floatsArrays[name] = value;
  21733. return this;
  21734. };
  21735. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21736. this._checkUniform(name);
  21737. this._colors3[name] = value;
  21738. return this;
  21739. };
  21740. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21741. this._checkUniform(name);
  21742. this._colors4[name] = value;
  21743. return this;
  21744. };
  21745. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21746. this._checkUniform(name);
  21747. this._vectors2[name] = value;
  21748. return this;
  21749. };
  21750. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21751. this._checkUniform(name);
  21752. this._vectors3[name] = value;
  21753. return this;
  21754. };
  21755. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21756. this._checkUniform(name);
  21757. this._matrices[name] = value;
  21758. return this;
  21759. };
  21760. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21761. var scene = this.getScene();
  21762. var engine = scene.getEngine();
  21763. // Render
  21764. engine.enableEffect(this._effect);
  21765. engine.setState(false);
  21766. // Texture
  21767. for (var name in this._textures) {
  21768. this._effect.setTexture(name, this._textures[name]);
  21769. }
  21770. // Float
  21771. for (name in this._floats) {
  21772. this._effect.setFloat(name, this._floats[name]);
  21773. }
  21774. // Floats
  21775. for (name in this._floatsArrays) {
  21776. this._effect.setArray(name, this._floatsArrays[name]);
  21777. }
  21778. // Color3
  21779. for (name in this._colors3) {
  21780. this._effect.setColor3(name, this._colors3[name]);
  21781. }
  21782. // Color4
  21783. for (name in this._colors4) {
  21784. var color = this._colors4[name];
  21785. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21786. }
  21787. // Vector2
  21788. for (name in this._vectors2) {
  21789. this._effect.setVector2(name, this._vectors2[name]);
  21790. }
  21791. // Vector3
  21792. for (name in this._vectors3) {
  21793. this._effect.setVector3(name, this._vectors3[name]);
  21794. }
  21795. // Matrix
  21796. for (name in this._matrices) {
  21797. this._effect.setMatrix(name, this._matrices[name]);
  21798. }
  21799. // VBOs
  21800. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21801. if (this.isCube) {
  21802. for (var face = 0; face < 6; face++) {
  21803. engine.bindFramebuffer(this._texture, face);
  21804. this._effect.setFloat("face", face);
  21805. // Clear
  21806. engine.clear(scene.clearColor, true, true);
  21807. // Draw order
  21808. engine.draw(true, 0, 6);
  21809. // Mipmaps
  21810. if (face === 5) {
  21811. engine.generateMipMapsForCubemap(this._texture);
  21812. }
  21813. }
  21814. }
  21815. else {
  21816. engine.bindFramebuffer(this._texture);
  21817. // Clear
  21818. engine.clear(scene.clearColor, true, true);
  21819. // Draw order
  21820. engine.draw(true, 0, 6);
  21821. }
  21822. // Unbind
  21823. engine.unBindFramebuffer(this._texture, this.isCube);
  21824. if (this.onGenerated) {
  21825. this.onGenerated();
  21826. }
  21827. };
  21828. ProceduralTexture.prototype.clone = function () {
  21829. var textureSize = this.getSize();
  21830. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21831. // Base texture
  21832. newTexture.hasAlpha = this.hasAlpha;
  21833. newTexture.level = this.level;
  21834. // RenderTarget Texture
  21835. newTexture.coordinatesMode = this.coordinatesMode;
  21836. return newTexture;
  21837. };
  21838. ProceduralTexture.prototype.dispose = function () {
  21839. var index = this.getScene()._proceduralTextures.indexOf(this);
  21840. if (index >= 0) {
  21841. this.getScene()._proceduralTextures.splice(index, 1);
  21842. }
  21843. _super.prototype.dispose.call(this);
  21844. };
  21845. return ProceduralTexture;
  21846. })(BABYLON.Texture);
  21847. BABYLON.ProceduralTexture = ProceduralTexture;
  21848. })(BABYLON || (BABYLON = {}));
  21849. var BABYLON;
  21850. (function (BABYLON) {
  21851. var MirrorTexture = (function (_super) {
  21852. __extends(MirrorTexture, _super);
  21853. function MirrorTexture(name, size, scene, generateMipMaps) {
  21854. var _this = this;
  21855. _super.call(this, name, size, scene, generateMipMaps, true);
  21856. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21857. this._transformMatrix = BABYLON.Matrix.Zero();
  21858. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21859. this.onBeforeRenderObservable.add(function () {
  21860. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21861. _this._savedViewMatrix = scene.getViewMatrix();
  21862. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21863. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21864. scene.clipPlane = _this.mirrorPlane;
  21865. scene.getEngine().cullBackFaces = false;
  21866. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21867. });
  21868. this.onAfterRenderObservable.add(function () {
  21869. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21870. scene.getEngine().cullBackFaces = true;
  21871. scene._mirroredCameraPosition = null;
  21872. delete scene.clipPlane;
  21873. });
  21874. }
  21875. MirrorTexture.prototype.clone = function () {
  21876. var textureSize = this.getSize();
  21877. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21878. // Base texture
  21879. newTexture.hasAlpha = this.hasAlpha;
  21880. newTexture.level = this.level;
  21881. // Mirror Texture
  21882. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21883. newTexture.renderList = this.renderList.slice(0);
  21884. return newTexture;
  21885. };
  21886. MirrorTexture.prototype.serialize = function () {
  21887. if (!this.name) {
  21888. return null;
  21889. }
  21890. var serializationObject = _super.prototype.serialize.call(this);
  21891. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21892. return serializationObject;
  21893. };
  21894. return MirrorTexture;
  21895. })(BABYLON.RenderTargetTexture);
  21896. BABYLON.MirrorTexture = MirrorTexture;
  21897. })(BABYLON || (BABYLON = {}));
  21898. var BABYLON;
  21899. (function (BABYLON) {
  21900. /**
  21901. * Creates a refraction texture used by refraction channel of the standard material.
  21902. * @param name the texture name
  21903. * @param size size of the underlying texture
  21904. * @param scene root scene
  21905. */
  21906. var RefractionTexture = (function (_super) {
  21907. __extends(RefractionTexture, _super);
  21908. function RefractionTexture(name, size, scene, generateMipMaps) {
  21909. var _this = this;
  21910. _super.call(this, name, size, scene, generateMipMaps, true);
  21911. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21912. this.depth = 2.0;
  21913. this.onBeforeRenderObservable.add(function () {
  21914. scene.clipPlane = _this.refractionPlane;
  21915. });
  21916. this.onAfterRenderObservable.add(function () {
  21917. delete scene.clipPlane;
  21918. });
  21919. }
  21920. RefractionTexture.prototype.clone = function () {
  21921. var textureSize = this.getSize();
  21922. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21923. // Base texture
  21924. newTexture.hasAlpha = this.hasAlpha;
  21925. newTexture.level = this.level;
  21926. // Refraction Texture
  21927. newTexture.refractionPlane = this.refractionPlane.clone();
  21928. newTexture.renderList = this.renderList.slice(0);
  21929. newTexture.depth = this.depth;
  21930. return newTexture;
  21931. };
  21932. RefractionTexture.prototype.serialize = function () {
  21933. if (!this.name) {
  21934. return null;
  21935. }
  21936. var serializationObject = _super.prototype.serialize.call(this);
  21937. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21938. serializationObject.depth = this.depth;
  21939. return serializationObject;
  21940. };
  21941. return RefractionTexture;
  21942. })(BABYLON.RenderTargetTexture);
  21943. BABYLON.RefractionTexture = RefractionTexture;
  21944. })(BABYLON || (BABYLON = {}));
  21945. var BABYLON;
  21946. (function (BABYLON) {
  21947. var DynamicTexture = (function (_super) {
  21948. __extends(DynamicTexture, _super);
  21949. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21951. _super.call(this, null, scene, !generateMipMaps);
  21952. this.name = name;
  21953. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21954. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21955. this._generateMipMaps = generateMipMaps;
  21956. if (options.getContext) {
  21957. this._canvas = options;
  21958. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21959. }
  21960. else {
  21961. this._canvas = document.createElement("canvas");
  21962. if (options.width) {
  21963. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21964. }
  21965. else {
  21966. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21967. }
  21968. }
  21969. var textureSize = this.getSize();
  21970. this._canvas.width = textureSize.width;
  21971. this._canvas.height = textureSize.height;
  21972. this._context = this._canvas.getContext("2d");
  21973. }
  21974. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21975. get: function () {
  21976. return true;
  21977. },
  21978. enumerable: true,
  21979. configurable: true
  21980. });
  21981. DynamicTexture.prototype.scale = function (ratio) {
  21982. var textureSize = this.getSize();
  21983. textureSize.width *= ratio;
  21984. textureSize.height *= ratio;
  21985. this._canvas.width = textureSize.width;
  21986. this._canvas.height = textureSize.height;
  21987. this.releaseInternalTexture();
  21988. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21989. };
  21990. DynamicTexture.prototype.getContext = function () {
  21991. return this._context;
  21992. };
  21993. DynamicTexture.prototype.clear = function () {
  21994. var size = this.getSize();
  21995. this._context.fillRect(0, 0, size.width, size.height);
  21996. };
  21997. DynamicTexture.prototype.update = function (invertY) {
  21998. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21999. };
  22000. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  22001. if (update === void 0) { update = true; }
  22002. var size = this.getSize();
  22003. if (clearColor) {
  22004. this._context.fillStyle = clearColor;
  22005. this._context.fillRect(0, 0, size.width, size.height);
  22006. }
  22007. this._context.font = font;
  22008. if (x === null) {
  22009. var textSize = this._context.measureText(text);
  22010. x = (size.width - textSize.width) / 2;
  22011. }
  22012. this._context.fillStyle = color;
  22013. this._context.fillText(text, x, y);
  22014. if (update) {
  22015. this.update(invertY);
  22016. }
  22017. };
  22018. DynamicTexture.prototype.clone = function () {
  22019. var textureSize = this.getSize();
  22020. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22021. // Base texture
  22022. newTexture.hasAlpha = this.hasAlpha;
  22023. newTexture.level = this.level;
  22024. // Dynamic Texture
  22025. newTexture.wrapU = this.wrapU;
  22026. newTexture.wrapV = this.wrapV;
  22027. return newTexture;
  22028. };
  22029. return DynamicTexture;
  22030. })(BABYLON.Texture);
  22031. BABYLON.DynamicTexture = DynamicTexture;
  22032. })(BABYLON || (BABYLON = {}));
  22033. var BABYLON;
  22034. (function (BABYLON) {
  22035. var VideoTexture = (function (_super) {
  22036. __extends(VideoTexture, _super);
  22037. /**
  22038. * Creates a video texture.
  22039. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  22040. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  22041. * @param {BABYLON.Scene} scene is obviously the current scene.
  22042. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  22043. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  22044. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  22045. */
  22046. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  22047. var _this = this;
  22048. if (generateMipMaps === void 0) { generateMipMaps = false; }
  22049. if (invertY === void 0) { invertY = false; }
  22050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22051. _super.call(this, null, scene, !generateMipMaps, invertY);
  22052. this._autoLaunch = true;
  22053. var urls;
  22054. this.name = name;
  22055. if (urlsOrVideo instanceof HTMLVideoElement) {
  22056. this.video = urlsOrVideo;
  22057. }
  22058. else {
  22059. urls = urlsOrVideo;
  22060. this.video = document.createElement("video");
  22061. this.video.autoplay = false;
  22062. this.video.loop = true;
  22063. }
  22064. this._generateMipMaps = generateMipMaps;
  22065. this._samplingMode = samplingMode;
  22066. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  22067. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22068. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22069. }
  22070. else {
  22071. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22072. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22073. this._generateMipMaps = false;
  22074. }
  22075. if (urls) {
  22076. this.video.addEventListener("canplaythrough", function () {
  22077. _this._createTexture();
  22078. });
  22079. urls.forEach(function (url) {
  22080. var source = document.createElement("source");
  22081. source.src = url;
  22082. _this.video.appendChild(source);
  22083. });
  22084. }
  22085. else {
  22086. this._createTexture();
  22087. }
  22088. this._lastUpdate = BABYLON.Tools.Now;
  22089. }
  22090. VideoTexture.prototype._createTexture = function () {
  22091. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  22092. this._texture.isReady = true;
  22093. };
  22094. VideoTexture.prototype.update = function () {
  22095. if (this._autoLaunch) {
  22096. this._autoLaunch = false;
  22097. this.video.play();
  22098. }
  22099. var now = BABYLON.Tools.Now;
  22100. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  22101. return false;
  22102. }
  22103. this._lastUpdate = now;
  22104. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  22105. return true;
  22106. };
  22107. return VideoTexture;
  22108. })(BABYLON.Texture);
  22109. BABYLON.VideoTexture = VideoTexture;
  22110. })(BABYLON || (BABYLON = {}));
  22111. var BABYLON;
  22112. (function (BABYLON) {
  22113. var CustomProceduralTexture = (function (_super) {
  22114. __extends(CustomProceduralTexture, _super);
  22115. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  22116. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  22117. this._animate = true;
  22118. this._time = 0;
  22119. this._texturePath = texturePath;
  22120. //Try to load json
  22121. this.loadJson(texturePath);
  22122. this.refreshRate = 1;
  22123. }
  22124. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  22125. var _this = this;
  22126. var that = this;
  22127. function noConfigFile() {
  22128. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  22129. try {
  22130. that.setFragment(that._texturePath);
  22131. }
  22132. catch (ex) {
  22133. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  22134. }
  22135. }
  22136. var configFileUrl = jsonUrl + "/config.json";
  22137. var xhr = new XMLHttpRequest();
  22138. xhr.open("GET", configFileUrl, true);
  22139. xhr.addEventListener("load", function () {
  22140. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  22141. try {
  22142. _this._config = JSON.parse(xhr.response);
  22143. _this.updateShaderUniforms();
  22144. _this.updateTextures();
  22145. _this.setFragment(_this._texturePath + "/custom");
  22146. _this._animate = _this._config.animate;
  22147. _this.refreshRate = _this._config.refreshrate;
  22148. }
  22149. catch (ex) {
  22150. noConfigFile();
  22151. }
  22152. }
  22153. else {
  22154. noConfigFile();
  22155. }
  22156. }, false);
  22157. xhr.addEventListener("error", function () {
  22158. noConfigFile();
  22159. }, false);
  22160. try {
  22161. xhr.send();
  22162. }
  22163. catch (ex) {
  22164. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22165. }
  22166. };
  22167. CustomProceduralTexture.prototype.isReady = function () {
  22168. if (!_super.prototype.isReady.call(this)) {
  22169. return false;
  22170. }
  22171. for (var name in this._textures) {
  22172. var texture = this._textures[name];
  22173. if (!texture.isReady()) {
  22174. return false;
  22175. }
  22176. }
  22177. return true;
  22178. };
  22179. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22180. if (this._animate) {
  22181. this._time += this.getScene().getAnimationRatio() * 0.03;
  22182. this.updateShaderUniforms();
  22183. }
  22184. _super.prototype.render.call(this, useCameraPostProcess);
  22185. };
  22186. CustomProceduralTexture.prototype.updateTextures = function () {
  22187. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22188. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22189. }
  22190. };
  22191. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22192. if (this._config) {
  22193. for (var j = 0; j < this._config.uniforms.length; j++) {
  22194. var uniform = this._config.uniforms[j];
  22195. switch (uniform.type) {
  22196. case "float":
  22197. this.setFloat(uniform.name, uniform.value);
  22198. break;
  22199. case "color3":
  22200. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22201. break;
  22202. case "color4":
  22203. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22204. break;
  22205. case "vector2":
  22206. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22207. break;
  22208. case "vector3":
  22209. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  22210. break;
  22211. }
  22212. }
  22213. }
  22214. this.setFloat("time", this._time);
  22215. };
  22216. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  22217. get: function () {
  22218. return this._animate;
  22219. },
  22220. set: function (value) {
  22221. this._animate = value;
  22222. },
  22223. enumerable: true,
  22224. configurable: true
  22225. });
  22226. return CustomProceduralTexture;
  22227. })(BABYLON.ProceduralTexture);
  22228. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  22229. })(BABYLON || (BABYLON = {}));
  22230. var BABYLON;
  22231. (function (BABYLON) {
  22232. var EffectFallbacks = (function () {
  22233. function EffectFallbacks() {
  22234. this._defines = {};
  22235. this._currentRank = 32;
  22236. this._maxRank = -1;
  22237. }
  22238. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22239. if (!this._defines[rank]) {
  22240. if (rank < this._currentRank) {
  22241. this._currentRank = rank;
  22242. }
  22243. if (rank > this._maxRank) {
  22244. this._maxRank = rank;
  22245. }
  22246. this._defines[rank] = new Array();
  22247. }
  22248. this._defines[rank].push(define);
  22249. };
  22250. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22251. this._meshRank = rank;
  22252. this._mesh = mesh;
  22253. if (rank > this._maxRank) {
  22254. this._maxRank = rank;
  22255. }
  22256. };
  22257. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22258. get: function () {
  22259. return this._currentRank <= this._maxRank;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22265. var currentFallbacks = this._defines[this._currentRank];
  22266. for (var index = 0; index < currentFallbacks.length; index++) {
  22267. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22268. }
  22269. if (this._mesh && this._currentRank === this._meshRank) {
  22270. this._mesh.computeBonesUsingShaders = false;
  22271. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22272. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22273. }
  22274. this._currentRank++;
  22275. return currentDefines;
  22276. };
  22277. return EffectFallbacks;
  22278. })();
  22279. BABYLON.EffectFallbacks = EffectFallbacks;
  22280. var Effect = (function () {
  22281. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22282. var _this = this;
  22283. this._isReady = false;
  22284. this._compilationError = "";
  22285. this._valueCache = [];
  22286. this._engine = engine;
  22287. this.name = baseName;
  22288. this.defines = defines;
  22289. this._uniformsNames = uniformsNames.concat(samplers);
  22290. this._samplers = samplers;
  22291. this._attributesNames = attributesNames;
  22292. this.onError = onError;
  22293. this.onCompiled = onCompiled;
  22294. this._indexParameters = indexParameters;
  22295. var vertexSource;
  22296. var fragmentSource;
  22297. if (baseName.vertexElement) {
  22298. vertexSource = document.getElementById(baseName.vertexElement);
  22299. if (!vertexSource) {
  22300. vertexSource = baseName.vertexElement;
  22301. }
  22302. }
  22303. else {
  22304. vertexSource = baseName.vertex || baseName;
  22305. }
  22306. if (baseName.fragmentElement) {
  22307. fragmentSource = document.getElementById(baseName.fragmentElement);
  22308. if (!fragmentSource) {
  22309. fragmentSource = baseName.fragmentElement;
  22310. }
  22311. }
  22312. else {
  22313. fragmentSource = baseName.fragment || baseName;
  22314. }
  22315. this._loadVertexShader(vertexSource, function (vertexCode) {
  22316. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22317. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22318. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22319. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  22320. });
  22321. });
  22322. });
  22323. });
  22324. }
  22325. // Properties
  22326. Effect.prototype.isReady = function () {
  22327. return this._isReady;
  22328. };
  22329. Effect.prototype.getProgram = function () {
  22330. return this._program;
  22331. };
  22332. Effect.prototype.getAttributesNames = function () {
  22333. return this._attributesNames;
  22334. };
  22335. Effect.prototype.getAttributeLocation = function (index) {
  22336. return this._attributes[index];
  22337. };
  22338. Effect.prototype.getAttributeLocationByName = function (name) {
  22339. var index = this._attributesNames.indexOf(name);
  22340. return this._attributes[index];
  22341. };
  22342. Effect.prototype.getAttributesCount = function () {
  22343. return this._attributes.length;
  22344. };
  22345. Effect.prototype.getUniformIndex = function (uniformName) {
  22346. return this._uniformsNames.indexOf(uniformName);
  22347. };
  22348. Effect.prototype.getUniform = function (uniformName) {
  22349. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22350. };
  22351. Effect.prototype.getSamplers = function () {
  22352. return this._samplers;
  22353. };
  22354. Effect.prototype.getCompilationError = function () {
  22355. return this._compilationError;
  22356. };
  22357. // Methods
  22358. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22359. // DOM element ?
  22360. if (vertex instanceof HTMLElement) {
  22361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22362. callback(vertexCode);
  22363. return;
  22364. }
  22365. // Is in local store ?
  22366. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22367. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22368. return;
  22369. }
  22370. var vertexShaderUrl;
  22371. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22372. vertexShaderUrl = vertex;
  22373. }
  22374. else {
  22375. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22376. }
  22377. // Vertex shader
  22378. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22379. };
  22380. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22381. // DOM element ?
  22382. if (fragment instanceof HTMLElement) {
  22383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22384. callback(fragmentCode);
  22385. return;
  22386. }
  22387. // Is in local store ?
  22388. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22389. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22390. return;
  22391. }
  22392. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22393. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22394. return;
  22395. }
  22396. var fragmentShaderUrl;
  22397. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22398. fragmentShaderUrl = fragment;
  22399. }
  22400. else {
  22401. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22402. }
  22403. // Fragment shader
  22404. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22405. };
  22406. Effect.prototype._dumpShadersName = function () {
  22407. if (this.name.vertexElement) {
  22408. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  22409. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  22410. }
  22411. else if (this.name.vertex) {
  22412. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  22413. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  22414. }
  22415. else {
  22416. BABYLON.Tools.Error("Vertex shader:" + this.name);
  22417. BABYLON.Tools.Error("Fragment shader:" + this.name);
  22418. }
  22419. };
  22420. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22421. var _this = this;
  22422. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22423. var match = regex.exec(sourceCode);
  22424. var returnValue = new String(sourceCode);
  22425. while (match != null) {
  22426. var includeFile = match[1];
  22427. if (Effect.IncludesShadersStore[includeFile]) {
  22428. // Substitution
  22429. var includeContent = Effect.IncludesShadersStore[includeFile];
  22430. if (match[2]) {
  22431. var splits = match[3].split(",");
  22432. for (var index = 0; index < splits.length; index += 2) {
  22433. var source = new RegExp(splits[index], "g");
  22434. var dest = splits[index + 1];
  22435. includeContent = includeContent.replace(source, dest);
  22436. }
  22437. }
  22438. if (match[4]) {
  22439. var indexString = match[5];
  22440. if (indexString.indexOf("..") !== -1) {
  22441. var indexSplits = indexString.split("..");
  22442. var minIndex = parseInt(indexSplits[0]);
  22443. var maxIndex = parseInt(indexSplits[1]);
  22444. var sourceIncludeContent = includeContent.slice(0);
  22445. includeContent = "";
  22446. if (isNaN(maxIndex)) {
  22447. maxIndex = this._indexParameters[indexSplits[1]];
  22448. }
  22449. for (var i = minIndex; i <= maxIndex; i++) {
  22450. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22451. }
  22452. }
  22453. else {
  22454. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22455. }
  22456. }
  22457. // Replace
  22458. returnValue = returnValue.replace(match[0], includeContent);
  22459. }
  22460. else {
  22461. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22462. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22463. Effect.IncludesShadersStore[includeFile] = fileContent;
  22464. _this._processIncludes(returnValue, callback);
  22465. });
  22466. return;
  22467. }
  22468. match = regex.exec(sourceCode);
  22469. }
  22470. callback(returnValue);
  22471. };
  22472. Effect.prototype._processPrecision = function (source) {
  22473. if (source.indexOf("precision highp float") === -1) {
  22474. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22475. source = "precision mediump float;\n" + source;
  22476. }
  22477. else {
  22478. source = "precision highp float;\n" + source;
  22479. }
  22480. }
  22481. else {
  22482. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22483. source = source.replace("precision highp float", "precision mediump float");
  22484. }
  22485. }
  22486. return source;
  22487. };
  22488. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22489. try {
  22490. var engine = this._engine;
  22491. // Precision
  22492. vertexSourceCode = this._processPrecision(vertexSourceCode);
  22493. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  22494. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22495. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22496. this._attributes = engine.getAttributes(this._program, attributesNames);
  22497. for (var index = 0; index < this._samplers.length; index++) {
  22498. var sampler = this.getUniform(this._samplers[index]);
  22499. if (sampler == null) {
  22500. this._samplers.splice(index, 1);
  22501. index--;
  22502. }
  22503. }
  22504. engine.bindSamplers(this);
  22505. this._isReady = true;
  22506. if (this.onCompiled) {
  22507. this.onCompiled(this);
  22508. }
  22509. }
  22510. catch (e) {
  22511. // Is it a problem with precision?
  22512. if (e.message.indexOf("highp") !== -1) {
  22513. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  22514. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  22515. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22516. return;
  22517. }
  22518. // Let's go through fallbacks then
  22519. if (fallbacks && fallbacks.isMoreFallbacks) {
  22520. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  22521. this._dumpShadersName();
  22522. defines = fallbacks.reduce(defines);
  22523. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22524. }
  22525. else {
  22526. BABYLON.Tools.Error("Unable to compile effect: ");
  22527. this._dumpShadersName();
  22528. BABYLON.Tools.Error("Defines: " + defines);
  22529. BABYLON.Tools.Error("Error: " + e.message);
  22530. this._compilationError = e.message;
  22531. if (this.onError) {
  22532. this.onError(this, this._compilationError);
  22533. }
  22534. }
  22535. }
  22536. };
  22537. Object.defineProperty(Effect.prototype, "isSupported", {
  22538. get: function () {
  22539. return this._compilationError === "";
  22540. },
  22541. enumerable: true,
  22542. configurable: true
  22543. });
  22544. Effect.prototype._bindTexture = function (channel, texture) {
  22545. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22546. };
  22547. Effect.prototype.setTexture = function (channel, texture) {
  22548. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  22549. };
  22550. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22551. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22552. };
  22553. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22554. if (!this._valueCache[uniformName]) {
  22555. this._valueCache[uniformName] = new BABYLON.Matrix();
  22556. }
  22557. for (var index = 0; index < 16; index++) {
  22558. this._valueCache[uniformName].m[index] = matrix.m[index];
  22559. }
  22560. };
  22561. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22562. if (!this._valueCache[uniformName]) {
  22563. this._valueCache[uniformName] = [x, y];
  22564. return;
  22565. }
  22566. this._valueCache[uniformName][0] = x;
  22567. this._valueCache[uniformName][1] = y;
  22568. };
  22569. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22570. if (!this._valueCache[uniformName]) {
  22571. this._valueCache[uniformName] = [x, y, z];
  22572. return;
  22573. }
  22574. this._valueCache[uniformName][0] = x;
  22575. this._valueCache[uniformName][1] = y;
  22576. this._valueCache[uniformName][2] = z;
  22577. };
  22578. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22579. if (!this._valueCache[uniformName]) {
  22580. this._valueCache[uniformName] = [x, y, z, w];
  22581. return;
  22582. }
  22583. this._valueCache[uniformName][0] = x;
  22584. this._valueCache[uniformName][1] = y;
  22585. this._valueCache[uniformName][2] = z;
  22586. this._valueCache[uniformName][3] = w;
  22587. };
  22588. Effect.prototype.setArray = function (uniformName, array) {
  22589. this._engine.setArray(this.getUniform(uniformName), array);
  22590. return this;
  22591. };
  22592. Effect.prototype.setArray2 = function (uniformName, array) {
  22593. this._engine.setArray2(this.getUniform(uniformName), array);
  22594. return this;
  22595. };
  22596. Effect.prototype.setArray3 = function (uniformName, array) {
  22597. this._engine.setArray3(this.getUniform(uniformName), array);
  22598. return this;
  22599. };
  22600. Effect.prototype.setArray4 = function (uniformName, array) {
  22601. this._engine.setArray4(this.getUniform(uniformName), array);
  22602. return this;
  22603. };
  22604. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22605. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22606. return this;
  22607. };
  22608. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22609. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  22610. // return this;
  22611. // this._cacheMatrix(uniformName, matrix);
  22612. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22613. return this;
  22614. };
  22615. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22616. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22617. return this;
  22618. };
  22619. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  22620. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  22621. return this;
  22622. };
  22623. Effect.prototype.setFloat = function (uniformName, value) {
  22624. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  22625. return this;
  22626. this._valueCache[uniformName] = value;
  22627. this._engine.setFloat(this.getUniform(uniformName), value);
  22628. return this;
  22629. };
  22630. Effect.prototype.setBool = function (uniformName, bool) {
  22631. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  22632. return this;
  22633. this._valueCache[uniformName] = bool;
  22634. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22635. return this;
  22636. };
  22637. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22638. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  22639. return this;
  22640. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  22641. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22642. return this;
  22643. };
  22644. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22645. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  22646. return this;
  22647. this._cacheFloat2(uniformName, x, y);
  22648. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22649. return this;
  22650. };
  22651. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22652. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  22653. return this;
  22654. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  22655. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22656. return this;
  22657. };
  22658. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22659. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  22660. return this;
  22661. this._cacheFloat3(uniformName, x, y, z);
  22662. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22663. return this;
  22664. };
  22665. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22666. 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)
  22667. return this;
  22668. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  22669. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22670. return this;
  22671. };
  22672. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22673. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  22674. return this;
  22675. this._cacheFloat4(uniformName, x, y, z, w);
  22676. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22677. return this;
  22678. };
  22679. Effect.prototype.setColor3 = function (uniformName, color3) {
  22680. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  22681. return this;
  22682. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  22683. this._engine.setColor3(this.getUniform(uniformName), color3);
  22684. return this;
  22685. };
  22686. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22687. 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)
  22688. return this;
  22689. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  22690. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22691. return this;
  22692. };
  22693. // Statics
  22694. Effect.ShadersStore = {};
  22695. Effect.IncludesShadersStore = {};
  22696. return Effect;
  22697. })();
  22698. BABYLON.Effect = Effect;
  22699. })(BABYLON || (BABYLON = {}));
  22700. var BABYLON;
  22701. (function (BABYLON) {
  22702. var MaterialHelper = (function () {
  22703. function MaterialHelper() {
  22704. }
  22705. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  22706. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22707. var lightIndex = 0;
  22708. var needNormals = false;
  22709. var needRebuild = false;
  22710. for (var index = 0; index < scene.lights.length; index++) {
  22711. var light = scene.lights[index];
  22712. if (!light.isEnabled()) {
  22713. continue;
  22714. }
  22715. // Excluded check
  22716. if (light._excludedMeshesIds.length > 0) {
  22717. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  22718. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  22719. if (excludedMesh) {
  22720. light.excludedMeshes.push(excludedMesh);
  22721. }
  22722. }
  22723. light._excludedMeshesIds = [];
  22724. }
  22725. // Included check
  22726. if (light._includedOnlyMeshesIds.length > 0) {
  22727. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  22728. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22729. if (includedOnlyMesh) {
  22730. light.includedOnlyMeshes.push(includedOnlyMesh);
  22731. }
  22732. }
  22733. light._includedOnlyMeshesIds = [];
  22734. }
  22735. if (!light.canAffectMesh(mesh)) {
  22736. continue;
  22737. }
  22738. needNormals = true;
  22739. if (defines["LIGHT" + lightIndex] === undefined) {
  22740. needRebuild = true;
  22741. }
  22742. defines["LIGHT" + lightIndex] = true;
  22743. var type;
  22744. if (light instanceof BABYLON.SpotLight) {
  22745. type = "SPOTLIGHT" + lightIndex;
  22746. }
  22747. else if (light instanceof BABYLON.HemisphericLight) {
  22748. type = "HEMILIGHT" + lightIndex;
  22749. }
  22750. else if (light instanceof BABYLON.PointLight) {
  22751. type = "POINTLIGHT" + lightIndex;
  22752. }
  22753. else {
  22754. type = "DIRLIGHT" + lightIndex;
  22755. }
  22756. if (defines[type] === undefined) {
  22757. needRebuild = true;
  22758. }
  22759. defines[type] = true;
  22760. // Specular
  22761. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22762. defines["SPECULARTERM"] = true;
  22763. }
  22764. // Shadows
  22765. if (scene.shadowsEnabled) {
  22766. var shadowGenerator = light.getShadowGenerator();
  22767. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22768. if (defines["SHADOW" + lightIndex] === undefined) {
  22769. needRebuild = true;
  22770. }
  22771. defines["SHADOW" + lightIndex] = true;
  22772. defines["SHADOWS"] = true;
  22773. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22774. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  22775. needRebuild = true;
  22776. }
  22777. defines["SHADOWVSM" + lightIndex] = true;
  22778. }
  22779. if (shadowGenerator.usePoissonSampling) {
  22780. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  22781. needRebuild = true;
  22782. }
  22783. defines["SHADOWPCF" + lightIndex] = true;
  22784. }
  22785. }
  22786. }
  22787. lightIndex++;
  22788. if (lightIndex === maxSimultaneousLights)
  22789. break;
  22790. }
  22791. if (needRebuild) {
  22792. defines.rebuild();
  22793. }
  22794. return needNormals;
  22795. };
  22796. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  22797. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22798. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22799. if (!defines["LIGHT" + lightIndex]) {
  22800. break;
  22801. }
  22802. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22803. samplersList.push("shadowSampler" + lightIndex);
  22804. }
  22805. };
  22806. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22807. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22808. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22809. if (!defines["LIGHT" + lightIndex]) {
  22810. break;
  22811. }
  22812. if (lightIndex > 0) {
  22813. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22814. }
  22815. if (defines["SHADOW" + lightIndex]) {
  22816. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22817. }
  22818. if (defines["SHADOWPCF" + lightIndex]) {
  22819. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22820. }
  22821. if (defines["SHADOWVSM" + lightIndex]) {
  22822. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22823. }
  22824. }
  22825. };
  22826. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22827. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22828. fallbacks.addCPUSkinningFallback(0, mesh);
  22829. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22830. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22831. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22832. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22833. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22834. }
  22835. }
  22836. };
  22837. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22838. if (defines["INSTANCES"]) {
  22839. attribs.push("world0");
  22840. attribs.push("world1");
  22841. attribs.push("world2");
  22842. attribs.push("world3");
  22843. }
  22844. };
  22845. // Bindings
  22846. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22847. var shadowGenerator = light.getShadowGenerator();
  22848. if (mesh.receiveShadows && shadowGenerator) {
  22849. if (!light.needCube()) {
  22850. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22851. }
  22852. else {
  22853. if (!depthValuesAlreadySet) {
  22854. depthValuesAlreadySet = true;
  22855. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22856. }
  22857. }
  22858. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22859. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22860. }
  22861. return depthValuesAlreadySet;
  22862. };
  22863. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22864. if (light instanceof BABYLON.PointLight) {
  22865. // Point Light
  22866. light.transferToEffect(effect, "vLightData" + lightIndex);
  22867. }
  22868. else if (light instanceof BABYLON.DirectionalLight) {
  22869. // Directional Light
  22870. light.transferToEffect(effect, "vLightData" + lightIndex);
  22871. }
  22872. else if (light instanceof BABYLON.SpotLight) {
  22873. // Spot Light
  22874. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22875. }
  22876. else if (light instanceof BABYLON.HemisphericLight) {
  22877. // Hemispheric Light
  22878. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22879. }
  22880. };
  22881. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22882. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22883. var lightIndex = 0;
  22884. var depthValuesAlreadySet = false;
  22885. for (var index = 0; index < scene.lights.length; index++) {
  22886. var light = scene.lights[index];
  22887. if (!light.isEnabled()) {
  22888. continue;
  22889. }
  22890. if (!light.canAffectMesh(mesh)) {
  22891. continue;
  22892. }
  22893. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22894. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22895. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22896. if (defines["SPECULARTERM"]) {
  22897. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22898. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22899. }
  22900. // Shadows
  22901. if (scene.shadowsEnabled) {
  22902. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22903. }
  22904. lightIndex++;
  22905. if (lightIndex === maxSimultaneousLights)
  22906. break;
  22907. }
  22908. };
  22909. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22910. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22911. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22912. effect.setColor3("vFogColor", scene.fogColor);
  22913. }
  22914. };
  22915. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22916. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22917. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22918. }
  22919. };
  22920. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22921. if (defines["LOGARITHMICDEPTH"]) {
  22922. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22923. }
  22924. };
  22925. MaterialHelper.BindClipPlane = function (effect, scene) {
  22926. if (scene.clipPlane) {
  22927. var clipPlane = scene.clipPlane;
  22928. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22929. }
  22930. };
  22931. return MaterialHelper;
  22932. })();
  22933. BABYLON.MaterialHelper = MaterialHelper;
  22934. })(BABYLON || (BABYLON = {}));
  22935. var BABYLON;
  22936. (function (BABYLON) {
  22937. var FresnelParameters = (function () {
  22938. function FresnelParameters() {
  22939. this.isEnabled = true;
  22940. this.leftColor = BABYLON.Color3.White();
  22941. this.rightColor = BABYLON.Color3.Black();
  22942. this.bias = 0;
  22943. this.power = 1;
  22944. }
  22945. FresnelParameters.prototype.clone = function () {
  22946. var newFresnelParameters = new FresnelParameters();
  22947. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22948. return new FresnelParameters;
  22949. };
  22950. FresnelParameters.prototype.serialize = function () {
  22951. var serializationObject = {};
  22952. serializationObject.isEnabled = this.isEnabled;
  22953. serializationObject.leftColor = this.leftColor;
  22954. serializationObject.rightColor = this.rightColor;
  22955. serializationObject.bias = this.bias;
  22956. serializationObject.power = this.power;
  22957. return serializationObject;
  22958. };
  22959. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22960. var fresnelParameters = new FresnelParameters();
  22961. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22962. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22963. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22964. fresnelParameters.bias = parsedFresnelParameters.bias;
  22965. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22966. return fresnelParameters;
  22967. };
  22968. return FresnelParameters;
  22969. })();
  22970. BABYLON.FresnelParameters = FresnelParameters;
  22971. })(BABYLON || (BABYLON = {}));
  22972. var BABYLON;
  22973. (function (BABYLON) {
  22974. var MaterialDefines = (function () {
  22975. function MaterialDefines() {
  22976. }
  22977. MaterialDefines.prototype.rebuild = function () {
  22978. if (this._keys) {
  22979. delete this._keys;
  22980. }
  22981. this._keys = Object.keys(this);
  22982. };
  22983. MaterialDefines.prototype.isEqual = function (other) {
  22984. if (this._keys.length !== other._keys.length) {
  22985. return false;
  22986. }
  22987. for (var index = 0; index < this._keys.length; index++) {
  22988. var prop = this._keys[index];
  22989. if (this[prop] !== other[prop]) {
  22990. return false;
  22991. }
  22992. }
  22993. return true;
  22994. };
  22995. MaterialDefines.prototype.cloneTo = function (other) {
  22996. if (this._keys.length !== other._keys.length) {
  22997. other._keys = this._keys.slice(0);
  22998. }
  22999. for (var index = 0; index < this._keys.length; index++) {
  23000. var prop = this._keys[index];
  23001. other[prop] = this[prop];
  23002. }
  23003. };
  23004. MaterialDefines.prototype.reset = function () {
  23005. for (var index = 0; index < this._keys.length; index++) {
  23006. var prop = this._keys[index];
  23007. if (typeof (this[prop]) === "number") {
  23008. this[prop] = 0;
  23009. }
  23010. else {
  23011. this[prop] = false;
  23012. }
  23013. }
  23014. };
  23015. MaterialDefines.prototype.toString = function () {
  23016. var result = "";
  23017. for (var index = 0; index < this._keys.length; index++) {
  23018. var prop = this._keys[index];
  23019. if (typeof (this[prop]) === "number") {
  23020. result += "#define " + prop + " " + this[prop] + "\n";
  23021. }
  23022. else if (this[prop]) {
  23023. result += "#define " + prop + "\n";
  23024. }
  23025. }
  23026. return result;
  23027. };
  23028. return MaterialDefines;
  23029. })();
  23030. BABYLON.MaterialDefines = MaterialDefines;
  23031. var Material = (function () {
  23032. function Material(name, scene, doNotAdd) {
  23033. this.name = name;
  23034. this.checkReadyOnEveryCall = false;
  23035. this.checkReadyOnlyOnce = false;
  23036. this.state = "";
  23037. this.alpha = 1.0;
  23038. this.backFaceCulling = true;
  23039. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23040. /**
  23041. * An event triggered when the material is disposed.
  23042. * @type {BABYLON.Observable}
  23043. */
  23044. this.onDisposeObservable = new BABYLON.Observable();
  23045. /**
  23046. * An event triggered when the material is compiled.
  23047. * @type {BABYLON.Observable}
  23048. */
  23049. this.onBindObservable = new BABYLON.Observable();
  23050. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23051. this.disableDepthWrite = false;
  23052. this.fogEnabled = true;
  23053. this.pointSize = 1.0;
  23054. this.zOffset = 0;
  23055. this._wasPreviouslyReady = false;
  23056. this._fillMode = Material.TriangleFillMode;
  23057. this.id = name;
  23058. this._scene = scene;
  23059. if (!doNotAdd) {
  23060. scene.materials.push(this);
  23061. }
  23062. }
  23063. Object.defineProperty(Material, "TriangleFillMode", {
  23064. get: function () {
  23065. return Material._TriangleFillMode;
  23066. },
  23067. enumerable: true,
  23068. configurable: true
  23069. });
  23070. Object.defineProperty(Material, "WireFrameFillMode", {
  23071. get: function () {
  23072. return Material._WireFrameFillMode;
  23073. },
  23074. enumerable: true,
  23075. configurable: true
  23076. });
  23077. Object.defineProperty(Material, "PointFillMode", {
  23078. get: function () {
  23079. return Material._PointFillMode;
  23080. },
  23081. enumerable: true,
  23082. configurable: true
  23083. });
  23084. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23085. get: function () {
  23086. return Material._ClockWiseSideOrientation;
  23087. },
  23088. enumerable: true,
  23089. configurable: true
  23090. });
  23091. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23092. get: function () {
  23093. return Material._CounterClockWiseSideOrientation;
  23094. },
  23095. enumerable: true,
  23096. configurable: true
  23097. });
  23098. Object.defineProperty(Material.prototype, "onDispose", {
  23099. set: function (callback) {
  23100. if (this._onDisposeObserver) {
  23101. this.onDisposeObservable.remove(this._onDisposeObserver);
  23102. }
  23103. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23104. },
  23105. enumerable: true,
  23106. configurable: true
  23107. });
  23108. Object.defineProperty(Material.prototype, "onBind", {
  23109. set: function (callback) {
  23110. if (this._onBindObserver) {
  23111. this.onBindObservable.remove(this._onBindObserver);
  23112. }
  23113. this._onBindObserver = this.onBindObservable.add(callback);
  23114. },
  23115. enumerable: true,
  23116. configurable: true
  23117. });
  23118. Object.defineProperty(Material.prototype, "wireframe", {
  23119. get: function () {
  23120. return this._fillMode === Material.WireFrameFillMode;
  23121. },
  23122. set: function (value) {
  23123. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23124. },
  23125. enumerable: true,
  23126. configurable: true
  23127. });
  23128. Object.defineProperty(Material.prototype, "pointsCloud", {
  23129. get: function () {
  23130. return this._fillMode === Material.PointFillMode;
  23131. },
  23132. set: function (value) {
  23133. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23134. },
  23135. enumerable: true,
  23136. configurable: true
  23137. });
  23138. Object.defineProperty(Material.prototype, "fillMode", {
  23139. get: function () {
  23140. return this._fillMode;
  23141. },
  23142. set: function (value) {
  23143. this._fillMode = value;
  23144. },
  23145. enumerable: true,
  23146. configurable: true
  23147. });
  23148. /**
  23149. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23150. * subclasses should override adding information pertainent to themselves
  23151. */
  23152. Material.prototype.toString = function (fullDetails) {
  23153. var ret = "Name: " + this.name;
  23154. if (fullDetails) {
  23155. }
  23156. return ret;
  23157. };
  23158. Object.defineProperty(Material.prototype, "isFrozen", {
  23159. get: function () {
  23160. return this.checkReadyOnlyOnce;
  23161. },
  23162. enumerable: true,
  23163. configurable: true
  23164. });
  23165. Material.prototype.freeze = function () {
  23166. this.checkReadyOnlyOnce = true;
  23167. };
  23168. Material.prototype.unfreeze = function () {
  23169. this.checkReadyOnlyOnce = false;
  23170. };
  23171. Material.prototype.isReady = function (mesh, useInstances) {
  23172. return true;
  23173. };
  23174. Material.prototype.getEffect = function () {
  23175. return this._effect;
  23176. };
  23177. Material.prototype.getScene = function () {
  23178. return this._scene;
  23179. };
  23180. Material.prototype.needAlphaBlending = function () {
  23181. return (this.alpha < 1.0);
  23182. };
  23183. Material.prototype.needAlphaTesting = function () {
  23184. return false;
  23185. };
  23186. Material.prototype.getAlphaTestTexture = function () {
  23187. return null;
  23188. };
  23189. Material.prototype.markDirty = function () {
  23190. this._wasPreviouslyReady = false;
  23191. };
  23192. Material.prototype._preBind = function () {
  23193. var engine = this._scene.getEngine();
  23194. engine.enableEffect(this._effect);
  23195. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  23196. };
  23197. Material.prototype.bind = function (world, mesh) {
  23198. this._scene._cachedMaterial = this;
  23199. this.onBindObservable.notifyObservers(mesh);
  23200. if (this.disableDepthWrite) {
  23201. var engine = this._scene.getEngine();
  23202. this._cachedDepthWriteState = engine.getDepthWrite();
  23203. engine.setDepthWrite(false);
  23204. }
  23205. };
  23206. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23207. };
  23208. Material.prototype.unbind = function () {
  23209. if (this.disableDepthWrite) {
  23210. var engine = this._scene.getEngine();
  23211. engine.setDepthWrite(this._cachedDepthWriteState);
  23212. }
  23213. };
  23214. Material.prototype.clone = function (name) {
  23215. return null;
  23216. };
  23217. Material.prototype.getBindedMeshes = function () {
  23218. var result = new Array();
  23219. for (var index = 0; index < this._scene.meshes.length; index++) {
  23220. var mesh = this._scene.meshes[index];
  23221. if (mesh.material === this) {
  23222. result.push(mesh);
  23223. }
  23224. }
  23225. return result;
  23226. };
  23227. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23228. // Animations
  23229. this.getScene().stopAnimation(this);
  23230. // Remove from scene
  23231. var index = this._scene.materials.indexOf(this);
  23232. if (index >= 0) {
  23233. this._scene.materials.splice(index, 1);
  23234. }
  23235. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23236. if (forceDisposeEffect && this._effect) {
  23237. this._scene.getEngine()._releaseEffect(this._effect);
  23238. this._effect = null;
  23239. }
  23240. // Remove from meshes
  23241. for (index = 0; index < this._scene.meshes.length; index++) {
  23242. var mesh = this._scene.meshes[index];
  23243. if (mesh.material === this) {
  23244. mesh.material = null;
  23245. }
  23246. }
  23247. // Callback
  23248. this.onDisposeObservable.notifyObservers(this);
  23249. this.onDisposeObservable.clear();
  23250. this.onBindObservable.clear();
  23251. };
  23252. Material.prototype.serialize = function () {
  23253. return BABYLON.SerializationHelper.Serialize(this);
  23254. };
  23255. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23256. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23257. multiMaterial.id = parsedMultiMaterial.id;
  23258. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23259. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23260. var subMatId = parsedMultiMaterial.materials[matIndex];
  23261. if (subMatId) {
  23262. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23263. }
  23264. else {
  23265. multiMaterial.subMaterials.push(null);
  23266. }
  23267. }
  23268. return multiMaterial;
  23269. };
  23270. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23271. if (!parsedMaterial.customType) {
  23272. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23273. }
  23274. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23275. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23276. ;
  23277. };
  23278. Material._TriangleFillMode = 0;
  23279. Material._WireFrameFillMode = 1;
  23280. Material._PointFillMode = 2;
  23281. Material._ClockWiseSideOrientation = 0;
  23282. Material._CounterClockWiseSideOrientation = 1;
  23283. __decorate([
  23284. BABYLON.serialize()
  23285. ], Material.prototype, "id", void 0);
  23286. __decorate([
  23287. BABYLON.serialize()
  23288. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23289. __decorate([
  23290. BABYLON.serialize()
  23291. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23292. __decorate([
  23293. BABYLON.serialize()
  23294. ], Material.prototype, "state", void 0);
  23295. __decorate([
  23296. BABYLON.serialize()
  23297. ], Material.prototype, "alpha", void 0);
  23298. __decorate([
  23299. BABYLON.serialize()
  23300. ], Material.prototype, "backFaceCulling", void 0);
  23301. __decorate([
  23302. BABYLON.serialize()
  23303. ], Material.prototype, "sideOrientation", void 0);
  23304. __decorate([
  23305. BABYLON.serialize()
  23306. ], Material.prototype, "alphaMode", void 0);
  23307. __decorate([
  23308. BABYLON.serialize()
  23309. ], Material.prototype, "disableDepthWrite", void 0);
  23310. __decorate([
  23311. BABYLON.serialize()
  23312. ], Material.prototype, "fogEnabled", void 0);
  23313. __decorate([
  23314. BABYLON.serialize()
  23315. ], Material.prototype, "pointSize", void 0);
  23316. __decorate([
  23317. BABYLON.serialize()
  23318. ], Material.prototype, "zOffset", void 0);
  23319. __decorate([
  23320. BABYLON.serialize()
  23321. ], Material.prototype, "wireframe", null);
  23322. __decorate([
  23323. BABYLON.serialize()
  23324. ], Material.prototype, "pointsCloud", null);
  23325. __decorate([
  23326. BABYLON.serialize()
  23327. ], Material.prototype, "fillMode", null);
  23328. return Material;
  23329. })();
  23330. BABYLON.Material = Material;
  23331. })(BABYLON || (BABYLON = {}));
  23332. var BABYLON;
  23333. (function (BABYLON) {
  23334. var StandardMaterialDefines = (function (_super) {
  23335. __extends(StandardMaterialDefines, _super);
  23336. function StandardMaterialDefines() {
  23337. _super.call(this);
  23338. this.DIFFUSE = false;
  23339. this.AMBIENT = false;
  23340. this.OPACITY = false;
  23341. this.OPACITYRGB = false;
  23342. this.REFLECTION = false;
  23343. this.EMISSIVE = false;
  23344. this.SPECULAR = false;
  23345. this.BUMP = false;
  23346. this.PARALLAX = false;
  23347. this.PARALLAXOCCLUSION = false;
  23348. this.SPECULAROVERALPHA = false;
  23349. this.CLIPPLANE = false;
  23350. this.ALPHATEST = false;
  23351. this.ALPHAFROMDIFFUSE = false;
  23352. this.POINTSIZE = false;
  23353. this.FOG = false;
  23354. this.SPECULARTERM = false;
  23355. this.DIFFUSEFRESNEL = false;
  23356. this.OPACITYFRESNEL = false;
  23357. this.REFLECTIONFRESNEL = false;
  23358. this.REFRACTIONFRESNEL = false;
  23359. this.EMISSIVEFRESNEL = false;
  23360. this.FRESNEL = false;
  23361. this.NORMAL = false;
  23362. this.UV1 = false;
  23363. this.UV2 = false;
  23364. this.VERTEXCOLOR = false;
  23365. this.VERTEXALPHA = false;
  23366. this.NUM_BONE_INFLUENCERS = 0;
  23367. this.BonesPerMesh = 0;
  23368. this.INSTANCES = false;
  23369. this.GLOSSINESS = false;
  23370. this.ROUGHNESS = false;
  23371. this.EMISSIVEASILLUMINATION = false;
  23372. this.LINKEMISSIVEWITHDIFFUSE = false;
  23373. this.REFLECTIONFRESNELFROMSPECULAR = false;
  23374. this.LIGHTMAP = false;
  23375. this.USELIGHTMAPASSHADOWMAP = false;
  23376. this.REFLECTIONMAP_3D = false;
  23377. this.REFLECTIONMAP_SPHERICAL = false;
  23378. this.REFLECTIONMAP_PLANAR = false;
  23379. this.REFLECTIONMAP_CUBIC = false;
  23380. this.REFLECTIONMAP_PROJECTION = false;
  23381. this.REFLECTIONMAP_SKYBOX = false;
  23382. this.REFLECTIONMAP_EXPLICIT = false;
  23383. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  23384. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  23385. this.INVERTCUBICMAP = false;
  23386. this.LOGARITHMICDEPTH = false;
  23387. this.REFRACTION = false;
  23388. this.REFRACTIONMAP_3D = false;
  23389. this.REFLECTIONOVERALPHA = false;
  23390. this.INVERTNORMALMAPX = false;
  23391. this.INVERTNORMALMAPY = false;
  23392. this.rebuild();
  23393. }
  23394. return StandardMaterialDefines;
  23395. })(BABYLON.MaterialDefines);
  23396. var StandardMaterial = (function (_super) {
  23397. __extends(StandardMaterial, _super);
  23398. function StandardMaterial(name, scene) {
  23399. var _this = this;
  23400. _super.call(this, name, scene);
  23401. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23402. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  23403. this.specularColor = new BABYLON.Color3(1, 1, 1);
  23404. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  23405. this.specularPower = 64;
  23406. this.useAlphaFromDiffuseTexture = false;
  23407. this.useEmissiveAsIllumination = false;
  23408. this.linkEmissiveWithDiffuse = false;
  23409. this.useReflectionFresnelFromSpecular = false;
  23410. this.useSpecularOverAlpha = false;
  23411. this.useReflectionOverAlpha = false;
  23412. this.disableLighting = false;
  23413. this.useParallax = false;
  23414. this.useParallaxOcclusion = false;
  23415. this.parallaxScaleBias = 0.05;
  23416. this.roughness = 0;
  23417. this.indexOfRefraction = 0.98;
  23418. this.invertRefractionY = true;
  23419. this.useLightmapAsShadowmap = false;
  23420. this.useGlossinessFromSpecularMapAlpha = false;
  23421. this.maxSimultaneousLights = 4;
  23422. /**
  23423. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  23424. */
  23425. this.invertNormalMapX = false;
  23426. /**
  23427. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  23428. */
  23429. this.invertNormalMapY = false;
  23430. this._renderTargets = new BABYLON.SmartArray(16);
  23431. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  23432. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  23433. this._defines = new StandardMaterialDefines();
  23434. this._cachedDefines = new StandardMaterialDefines();
  23435. this._cachedDefines.BonesPerMesh = -1;
  23436. this.getRenderTargetTextures = function () {
  23437. _this._renderTargets.reset();
  23438. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  23439. _this._renderTargets.push(_this.reflectionTexture);
  23440. }
  23441. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  23442. _this._renderTargets.push(_this.refractionTexture);
  23443. }
  23444. return _this._renderTargets;
  23445. };
  23446. }
  23447. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  23448. get: function () {
  23449. return this._useLogarithmicDepth;
  23450. },
  23451. set: function (value) {
  23452. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  23453. },
  23454. enumerable: true,
  23455. configurable: true
  23456. });
  23457. StandardMaterial.prototype.needAlphaBlending = function () {
  23458. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  23459. };
  23460. StandardMaterial.prototype.needAlphaTesting = function () {
  23461. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  23462. };
  23463. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  23464. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  23465. };
  23466. StandardMaterial.prototype.getAlphaTestTexture = function () {
  23467. return this.diffuseTexture;
  23468. };
  23469. // Methods
  23470. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  23471. if (!mesh) {
  23472. return true;
  23473. }
  23474. if (this._defines.INSTANCES !== useInstances) {
  23475. return false;
  23476. }
  23477. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  23478. return true;
  23479. }
  23480. return false;
  23481. };
  23482. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  23483. if (this.isFrozen) {
  23484. if (this._wasPreviouslyReady) {
  23485. return true;
  23486. }
  23487. }
  23488. var scene = this.getScene();
  23489. if (!this.checkReadyOnEveryCall) {
  23490. if (this._renderId === scene.getRenderId()) {
  23491. if (this._checkCache(scene, mesh, useInstances)) {
  23492. return true;
  23493. }
  23494. }
  23495. }
  23496. var engine = scene.getEngine();
  23497. var needNormals = false;
  23498. var needUVs = false;
  23499. this._defines.reset();
  23500. // Textures
  23501. if (scene.texturesEnabled) {
  23502. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23503. if (!this.diffuseTexture.isReady()) {
  23504. return false;
  23505. }
  23506. else {
  23507. needUVs = true;
  23508. this._defines.DIFFUSE = true;
  23509. }
  23510. }
  23511. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23512. if (!this.ambientTexture.isReady()) {
  23513. return false;
  23514. }
  23515. else {
  23516. needUVs = true;
  23517. this._defines.AMBIENT = true;
  23518. }
  23519. }
  23520. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23521. if (!this.opacityTexture.isReady()) {
  23522. return false;
  23523. }
  23524. else {
  23525. needUVs = true;
  23526. this._defines.OPACITY = true;
  23527. if (this.opacityTexture.getAlphaFromRGB) {
  23528. this._defines.OPACITYRGB = true;
  23529. }
  23530. }
  23531. }
  23532. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23533. if (!this.reflectionTexture.isReady()) {
  23534. return false;
  23535. }
  23536. else {
  23537. needNormals = true;
  23538. this._defines.REFLECTION = true;
  23539. if (this.roughness > 0) {
  23540. this._defines.ROUGHNESS = true;
  23541. }
  23542. if (this.useReflectionOverAlpha) {
  23543. this._defines.REFLECTIONOVERALPHA = true;
  23544. }
  23545. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  23546. this._defines.INVERTCUBICMAP = true;
  23547. }
  23548. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  23549. switch (this.reflectionTexture.coordinatesMode) {
  23550. case BABYLON.Texture.CUBIC_MODE:
  23551. case BABYLON.Texture.INVCUBIC_MODE:
  23552. this._defines.REFLECTIONMAP_CUBIC = true;
  23553. break;
  23554. case BABYLON.Texture.EXPLICIT_MODE:
  23555. this._defines.REFLECTIONMAP_EXPLICIT = true;
  23556. break;
  23557. case BABYLON.Texture.PLANAR_MODE:
  23558. this._defines.REFLECTIONMAP_PLANAR = true;
  23559. break;
  23560. case BABYLON.Texture.PROJECTION_MODE:
  23561. this._defines.REFLECTIONMAP_PROJECTION = true;
  23562. break;
  23563. case BABYLON.Texture.SKYBOX_MODE:
  23564. this._defines.REFLECTIONMAP_SKYBOX = true;
  23565. break;
  23566. case BABYLON.Texture.SPHERICAL_MODE:
  23567. this._defines.REFLECTIONMAP_SPHERICAL = true;
  23568. break;
  23569. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  23570. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  23571. break;
  23572. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  23573. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  23574. break;
  23575. }
  23576. }
  23577. }
  23578. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23579. if (!this.emissiveTexture.isReady()) {
  23580. return false;
  23581. }
  23582. else {
  23583. needUVs = true;
  23584. this._defines.EMISSIVE = true;
  23585. }
  23586. }
  23587. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23588. if (!this.lightmapTexture.isReady()) {
  23589. return false;
  23590. }
  23591. else {
  23592. needUVs = true;
  23593. this._defines.LIGHTMAP = true;
  23594. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  23595. }
  23596. }
  23597. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23598. if (!this.specularTexture.isReady()) {
  23599. return false;
  23600. }
  23601. else {
  23602. needUVs = true;
  23603. this._defines.SPECULAR = true;
  23604. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  23605. }
  23606. }
  23607. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  23608. if (!this.bumpTexture.isReady()) {
  23609. return false;
  23610. }
  23611. else {
  23612. needUVs = true;
  23613. this._defines.BUMP = true;
  23614. if (this.useParallax) {
  23615. this._defines.PARALLAX = true;
  23616. if (this.useParallaxOcclusion) {
  23617. this._defines.PARALLAXOCCLUSION = true;
  23618. }
  23619. }
  23620. if (this.invertNormalMapX) {
  23621. this._defines.INVERTNORMALMAPX = true;
  23622. }
  23623. if (this.invertNormalMapY) {
  23624. this._defines.INVERTNORMALMAPY = true;
  23625. }
  23626. }
  23627. }
  23628. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23629. if (!this.refractionTexture.isReady()) {
  23630. return false;
  23631. }
  23632. else {
  23633. needUVs = true;
  23634. this._defines.REFRACTION = true;
  23635. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  23636. }
  23637. }
  23638. }
  23639. // Effect
  23640. if (scene.clipPlane) {
  23641. this._defines.CLIPPLANE = true;
  23642. }
  23643. if (engine.getAlphaTesting()) {
  23644. this._defines.ALPHATEST = true;
  23645. }
  23646. if (this._shouldUseAlphaFromDiffuseTexture()) {
  23647. this._defines.ALPHAFROMDIFFUSE = true;
  23648. }
  23649. if (this.useEmissiveAsIllumination) {
  23650. this._defines.EMISSIVEASILLUMINATION = true;
  23651. }
  23652. if (this.linkEmissiveWithDiffuse) {
  23653. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  23654. }
  23655. if (this.useLogarithmicDepth) {
  23656. this._defines.LOGARITHMICDEPTH = true;
  23657. }
  23658. // Point size
  23659. if (this.pointsCloud || scene.forcePointsCloud) {
  23660. this._defines.POINTSIZE = true;
  23661. }
  23662. // Fog
  23663. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23664. this._defines.FOG = true;
  23665. }
  23666. if (scene.lightsEnabled && !this.disableLighting) {
  23667. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  23668. }
  23669. if (StandardMaterial.FresnelEnabled) {
  23670. // Fresnel
  23671. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  23672. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  23673. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  23674. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  23675. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23676. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23677. this._defines.DIFFUSEFRESNEL = true;
  23678. }
  23679. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23680. this._defines.OPACITYFRESNEL = true;
  23681. }
  23682. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23683. this._defines.REFLECTIONFRESNEL = true;
  23684. if (this.useReflectionFresnelFromSpecular) {
  23685. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  23686. }
  23687. }
  23688. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23689. this._defines.REFRACTIONFRESNEL = true;
  23690. }
  23691. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23692. this._defines.EMISSIVEFRESNEL = true;
  23693. }
  23694. needNormals = true;
  23695. this._defines.FRESNEL = true;
  23696. }
  23697. }
  23698. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  23699. this._defines.SPECULAROVERALPHA = true;
  23700. }
  23701. // Attribs
  23702. if (mesh) {
  23703. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23704. this._defines.NORMAL = true;
  23705. }
  23706. if (needUVs) {
  23707. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23708. this._defines.UV1 = true;
  23709. }
  23710. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23711. this._defines.UV2 = true;
  23712. }
  23713. }
  23714. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23715. this._defines.VERTEXCOLOR = true;
  23716. if (mesh.hasVertexAlpha) {
  23717. this._defines.VERTEXALPHA = true;
  23718. }
  23719. }
  23720. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23721. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  23722. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  23723. }
  23724. // Instances
  23725. if (useInstances) {
  23726. this._defines.INSTANCES = true;
  23727. }
  23728. }
  23729. // Get correct effect
  23730. if (!this._defines.isEqual(this._cachedDefines)) {
  23731. this._defines.cloneTo(this._cachedDefines);
  23732. scene.resetCachedMaterial();
  23733. // Fallbacks
  23734. var fallbacks = new BABYLON.EffectFallbacks();
  23735. if (this._defines.REFLECTION) {
  23736. fallbacks.addFallback(0, "REFLECTION");
  23737. }
  23738. if (this._defines.SPECULAR) {
  23739. fallbacks.addFallback(0, "SPECULAR");
  23740. }
  23741. if (this._defines.BUMP) {
  23742. fallbacks.addFallback(0, "BUMP");
  23743. }
  23744. if (this._defines.PARALLAX) {
  23745. fallbacks.addFallback(1, "PARALLAX");
  23746. }
  23747. if (this._defines.PARALLAXOCCLUSION) {
  23748. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  23749. }
  23750. if (this._defines.SPECULAROVERALPHA) {
  23751. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  23752. }
  23753. if (this._defines.FOG) {
  23754. fallbacks.addFallback(1, "FOG");
  23755. }
  23756. if (this._defines.POINTSIZE) {
  23757. fallbacks.addFallback(0, "POINTSIZE");
  23758. }
  23759. if (this._defines.LOGARITHMICDEPTH) {
  23760. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  23761. }
  23762. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  23763. if (this._defines.SPECULARTERM) {
  23764. fallbacks.addFallback(0, "SPECULARTERM");
  23765. }
  23766. if (this._defines.DIFFUSEFRESNEL) {
  23767. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  23768. }
  23769. if (this._defines.OPACITYFRESNEL) {
  23770. fallbacks.addFallback(2, "OPACITYFRESNEL");
  23771. }
  23772. if (this._defines.REFLECTIONFRESNEL) {
  23773. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  23774. }
  23775. if (this._defines.EMISSIVEFRESNEL) {
  23776. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  23777. }
  23778. if (this._defines.FRESNEL) {
  23779. fallbacks.addFallback(4, "FRESNEL");
  23780. }
  23781. //Attributes
  23782. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23783. if (this._defines.NORMAL) {
  23784. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23785. }
  23786. if (this._defines.UV1) {
  23787. attribs.push(BABYLON.VertexBuffer.UVKind);
  23788. }
  23789. if (this._defines.UV2) {
  23790. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23791. }
  23792. if (this._defines.VERTEXCOLOR) {
  23793. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23794. }
  23795. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23796. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23797. // Legacy browser patch
  23798. var shaderName = "default";
  23799. if (!scene.getEngine().getCaps().standardDerivatives) {
  23800. shaderName = "legacydefault";
  23801. }
  23802. var join = this._defines.toString();
  23803. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23804. "vFogInfos", "vFogColor", "pointSize",
  23805. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23806. "mBones",
  23807. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23808. "depthValues",
  23809. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23810. "logarithmicDepthConstant"
  23811. ];
  23812. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  23813. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  23814. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  23815. }
  23816. if (!this._effect.isReady()) {
  23817. return false;
  23818. }
  23819. this._renderId = scene.getRenderId();
  23820. this._wasPreviouslyReady = true;
  23821. if (mesh) {
  23822. if (!mesh._materialDefines) {
  23823. mesh._materialDefines = new StandardMaterialDefines();
  23824. }
  23825. this._defines.cloneTo(mesh._materialDefines);
  23826. }
  23827. return true;
  23828. };
  23829. StandardMaterial.prototype.unbind = function () {
  23830. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23831. this._effect.setTexture("reflection2DSampler", null);
  23832. }
  23833. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23834. this._effect.setTexture("refraction2DSampler", null);
  23835. }
  23836. _super.prototype.unbind.call(this);
  23837. };
  23838. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23839. this._effect.setMatrix("world", world);
  23840. };
  23841. StandardMaterial.prototype.bind = function (world, mesh) {
  23842. var scene = this.getScene();
  23843. // Matrices
  23844. this.bindOnlyWorldMatrix(world);
  23845. // Bones
  23846. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23847. if (scene.getCachedMaterial() !== this) {
  23848. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23849. if (StandardMaterial.FresnelEnabled) {
  23850. // Fresnel
  23851. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23852. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23853. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23854. }
  23855. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23856. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23857. }
  23858. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23859. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23860. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23861. }
  23862. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23863. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23864. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23865. }
  23866. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23867. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23868. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23869. }
  23870. }
  23871. // Textures
  23872. if (scene.texturesEnabled) {
  23873. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23874. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23875. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23876. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23877. }
  23878. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23879. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23880. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23881. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23882. }
  23883. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23884. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23885. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23886. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23887. }
  23888. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23889. if (this.reflectionTexture.isCube) {
  23890. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23891. }
  23892. else {
  23893. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23894. }
  23895. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23896. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23897. }
  23898. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23899. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23900. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23901. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23902. }
  23903. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23904. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23905. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23906. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23907. }
  23908. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23909. this._effect.setTexture("specularSampler", this.specularTexture);
  23910. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23911. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23912. }
  23913. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23914. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23915. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23916. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23917. }
  23918. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23919. var depth = 1.0;
  23920. if (this.refractionTexture.isCube) {
  23921. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23922. }
  23923. else {
  23924. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23925. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23926. if (this.refractionTexture.depth) {
  23927. depth = this.refractionTexture.depth;
  23928. }
  23929. }
  23930. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23931. }
  23932. }
  23933. // Clip plane
  23934. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23935. // Point size
  23936. if (this.pointsCloud) {
  23937. this._effect.setFloat("pointSize", this.pointSize);
  23938. }
  23939. // Colors
  23940. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23941. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23942. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23943. if (this._defines.SPECULARTERM) {
  23944. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23945. }
  23946. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23947. }
  23948. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23949. // Diffuse
  23950. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23951. // Lights
  23952. if (scene.lightsEnabled && !this.disableLighting) {
  23953. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  23954. }
  23955. // View
  23956. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23957. this._effect.setMatrix("view", scene.getViewMatrix());
  23958. }
  23959. // Fog
  23960. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23961. // Log. depth
  23962. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23963. }
  23964. _super.prototype.bind.call(this, world, mesh);
  23965. };
  23966. StandardMaterial.prototype.getAnimatables = function () {
  23967. var results = [];
  23968. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23969. results.push(this.diffuseTexture);
  23970. }
  23971. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23972. results.push(this.ambientTexture);
  23973. }
  23974. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23975. results.push(this.opacityTexture);
  23976. }
  23977. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23978. results.push(this.reflectionTexture);
  23979. }
  23980. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23981. results.push(this.emissiveTexture);
  23982. }
  23983. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23984. results.push(this.specularTexture);
  23985. }
  23986. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23987. results.push(this.bumpTexture);
  23988. }
  23989. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23990. results.push(this.lightmapTexture);
  23991. }
  23992. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23993. results.push(this.refractionTexture);
  23994. }
  23995. return results;
  23996. };
  23997. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23998. if (forceDisposeTextures) {
  23999. if (this.diffuseTexture) {
  24000. this.diffuseTexture.dispose();
  24001. }
  24002. if (this.ambientTexture) {
  24003. this.ambientTexture.dispose();
  24004. }
  24005. if (this.opacityTexture) {
  24006. this.opacityTexture.dispose();
  24007. }
  24008. if (this.reflectionTexture) {
  24009. this.reflectionTexture.dispose();
  24010. }
  24011. if (this.emissiveTexture) {
  24012. this.emissiveTexture.dispose();
  24013. }
  24014. if (this.specularTexture) {
  24015. this.specularTexture.dispose();
  24016. }
  24017. if (this.bumpTexture) {
  24018. this.bumpTexture.dispose();
  24019. }
  24020. if (this.lightmapTexture) {
  24021. this.lightmapTexture.dispose();
  24022. }
  24023. if (this.refractionTexture) {
  24024. this.refractionTexture.dispose();
  24025. }
  24026. }
  24027. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  24028. };
  24029. StandardMaterial.prototype.clone = function (name) {
  24030. var _this = this;
  24031. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  24032. };
  24033. StandardMaterial.prototype.serialize = function () {
  24034. return BABYLON.SerializationHelper.Serialize(this);
  24035. };
  24036. // Statics
  24037. StandardMaterial.Parse = function (source, scene, rootUrl) {
  24038. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  24039. };
  24040. // Flags used to enable or disable a type of texture for all Standard Materials
  24041. StandardMaterial.DiffuseTextureEnabled = true;
  24042. StandardMaterial.AmbientTextureEnabled = true;
  24043. StandardMaterial.OpacityTextureEnabled = true;
  24044. StandardMaterial.ReflectionTextureEnabled = true;
  24045. StandardMaterial.EmissiveTextureEnabled = true;
  24046. StandardMaterial.SpecularTextureEnabled = true;
  24047. StandardMaterial.BumpTextureEnabled = true;
  24048. StandardMaterial.FresnelEnabled = true;
  24049. StandardMaterial.LightmapTextureEnabled = true;
  24050. StandardMaterial.RefractionTextureEnabled = true;
  24051. __decorate([
  24052. BABYLON.serializeAsTexture()
  24053. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  24054. __decorate([
  24055. BABYLON.serializeAsTexture()
  24056. ], StandardMaterial.prototype, "ambientTexture", void 0);
  24057. __decorate([
  24058. BABYLON.serializeAsTexture()
  24059. ], StandardMaterial.prototype, "opacityTexture", void 0);
  24060. __decorate([
  24061. BABYLON.serializeAsTexture()
  24062. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  24063. __decorate([
  24064. BABYLON.serializeAsTexture()
  24065. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  24066. __decorate([
  24067. BABYLON.serializeAsTexture()
  24068. ], StandardMaterial.prototype, "specularTexture", void 0);
  24069. __decorate([
  24070. BABYLON.serializeAsTexture()
  24071. ], StandardMaterial.prototype, "bumpTexture", void 0);
  24072. __decorate([
  24073. BABYLON.serializeAsTexture()
  24074. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  24075. __decorate([
  24076. BABYLON.serializeAsTexture()
  24077. ], StandardMaterial.prototype, "refractionTexture", void 0);
  24078. __decorate([
  24079. BABYLON.serializeAsColor3("ambient")
  24080. ], StandardMaterial.prototype, "ambientColor", void 0);
  24081. __decorate([
  24082. BABYLON.serializeAsColor3("diffuse")
  24083. ], StandardMaterial.prototype, "diffuseColor", void 0);
  24084. __decorate([
  24085. BABYLON.serializeAsColor3("specular")
  24086. ], StandardMaterial.prototype, "specularColor", void 0);
  24087. __decorate([
  24088. BABYLON.serializeAsColor3("emissive")
  24089. ], StandardMaterial.prototype, "emissiveColor", void 0);
  24090. __decorate([
  24091. BABYLON.serialize()
  24092. ], StandardMaterial.prototype, "specularPower", void 0);
  24093. __decorate([
  24094. BABYLON.serialize()
  24095. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  24096. __decorate([
  24097. BABYLON.serialize()
  24098. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  24099. __decorate([
  24100. BABYLON.serialize()
  24101. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  24102. __decorate([
  24103. BABYLON.serialize()
  24104. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  24105. __decorate([
  24106. BABYLON.serialize()
  24107. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  24108. __decorate([
  24109. BABYLON.serialize()
  24110. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  24111. __decorate([
  24112. BABYLON.serialize()
  24113. ], StandardMaterial.prototype, "disableLighting", void 0);
  24114. __decorate([
  24115. BABYLON.serialize()
  24116. ], StandardMaterial.prototype, "useParallax", void 0);
  24117. __decorate([
  24118. BABYLON.serialize()
  24119. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  24120. __decorate([
  24121. BABYLON.serialize()
  24122. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  24123. __decorate([
  24124. BABYLON.serialize()
  24125. ], StandardMaterial.prototype, "roughness", void 0);
  24126. __decorate([
  24127. BABYLON.serialize()
  24128. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  24129. __decorate([
  24130. BABYLON.serialize()
  24131. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  24132. __decorate([
  24133. BABYLON.serialize()
  24134. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  24135. __decorate([
  24136. BABYLON.serializeAsFresnelParameters()
  24137. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  24138. __decorate([
  24139. BABYLON.serializeAsFresnelParameters()
  24140. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  24141. __decorate([
  24142. BABYLON.serializeAsFresnelParameters()
  24143. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  24144. __decorate([
  24145. BABYLON.serializeAsFresnelParameters()
  24146. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  24147. __decorate([
  24148. BABYLON.serializeAsFresnelParameters()
  24149. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  24150. __decorate([
  24151. BABYLON.serialize()
  24152. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  24153. __decorate([
  24154. BABYLON.serialize()
  24155. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  24156. __decorate([
  24157. BABYLON.serialize()
  24158. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  24159. __decorate([
  24160. BABYLON.serialize()
  24161. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  24162. __decorate([
  24163. BABYLON.serialize()
  24164. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  24165. return StandardMaterial;
  24166. })(BABYLON.Material);
  24167. BABYLON.StandardMaterial = StandardMaterial;
  24168. })(BABYLON || (BABYLON = {}));
  24169. var BABYLON;
  24170. (function (BABYLON) {
  24171. var MultiMaterial = (function (_super) {
  24172. __extends(MultiMaterial, _super);
  24173. function MultiMaterial(name, scene) {
  24174. _super.call(this, name, scene, true);
  24175. this.subMaterials = new Array();
  24176. scene.multiMaterials.push(this);
  24177. }
  24178. // Properties
  24179. MultiMaterial.prototype.getSubMaterial = function (index) {
  24180. if (index < 0 || index >= this.subMaterials.length) {
  24181. return this.getScene().defaultMaterial;
  24182. }
  24183. return this.subMaterials[index];
  24184. };
  24185. // Methods
  24186. MultiMaterial.prototype.isReady = function (mesh) {
  24187. for (var index = 0; index < this.subMaterials.length; index++) {
  24188. var subMaterial = this.subMaterials[index];
  24189. if (subMaterial) {
  24190. if (!this.subMaterials[index].isReady(mesh)) {
  24191. return false;
  24192. }
  24193. }
  24194. }
  24195. return true;
  24196. };
  24197. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  24198. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  24199. for (var index = 0; index < this.subMaterials.length; index++) {
  24200. var subMaterial = null;
  24201. if (cloneChildren) {
  24202. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  24203. }
  24204. else {
  24205. subMaterial = this.subMaterials[index];
  24206. }
  24207. newMultiMaterial.subMaterials.push(subMaterial);
  24208. }
  24209. return newMultiMaterial;
  24210. };
  24211. MultiMaterial.prototype.serialize = function () {
  24212. var serializationObject = {};
  24213. serializationObject.name = this.name;
  24214. serializationObject.id = this.id;
  24215. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24216. serializationObject.materials = [];
  24217. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  24218. var subMat = this.subMaterials[matIndex];
  24219. if (subMat) {
  24220. serializationObject.materials.push(subMat.id);
  24221. }
  24222. else {
  24223. serializationObject.materials.push(null);
  24224. }
  24225. }
  24226. return serializationObject;
  24227. };
  24228. return MultiMaterial;
  24229. })(BABYLON.Material);
  24230. BABYLON.MultiMaterial = MultiMaterial;
  24231. })(BABYLON || (BABYLON = {}));
  24232. var BABYLON;
  24233. (function (BABYLON) {
  24234. var SceneLoader = (function () {
  24235. function SceneLoader() {
  24236. }
  24237. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  24238. get: function () {
  24239. return 0;
  24240. },
  24241. enumerable: true,
  24242. configurable: true
  24243. });
  24244. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  24245. get: function () {
  24246. return 1;
  24247. },
  24248. enumerable: true,
  24249. configurable: true
  24250. });
  24251. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  24252. get: function () {
  24253. return 2;
  24254. },
  24255. enumerable: true,
  24256. configurable: true
  24257. });
  24258. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  24259. get: function () {
  24260. return 3;
  24261. },
  24262. enumerable: true,
  24263. configurable: true
  24264. });
  24265. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  24266. get: function () {
  24267. return SceneLoader._ForceFullSceneLoadingForIncremental;
  24268. },
  24269. set: function (value) {
  24270. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  24276. get: function () {
  24277. return SceneLoader._ShowLoadingScreen;
  24278. },
  24279. set: function (value) {
  24280. SceneLoader._ShowLoadingScreen = value;
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. Object.defineProperty(SceneLoader, "loggingLevel", {
  24286. get: function () {
  24287. return SceneLoader._loggingLevel;
  24288. },
  24289. set: function (value) {
  24290. SceneLoader._loggingLevel = value;
  24291. },
  24292. enumerable: true,
  24293. configurable: true
  24294. });
  24295. SceneLoader._getPluginForFilename = function (sceneFilename) {
  24296. var dotPosition = sceneFilename.lastIndexOf(".");
  24297. var queryStringPosition = sceneFilename.indexOf("?");
  24298. if (queryStringPosition === -1) {
  24299. queryStringPosition = sceneFilename.length;
  24300. }
  24301. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  24302. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24303. var plugin = this._registeredPlugins[index];
  24304. if (plugin.extensions.indexOf(extension) !== -1) {
  24305. return plugin;
  24306. }
  24307. }
  24308. return this._registeredPlugins[0];
  24309. };
  24310. // Public functions
  24311. SceneLoader.GetPluginForExtension = function (extension) {
  24312. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24313. var plugin = this._registeredPlugins[index];
  24314. if (plugin.extensions.indexOf(extension) !== -1) {
  24315. return plugin;
  24316. }
  24317. }
  24318. return null;
  24319. };
  24320. SceneLoader.RegisterPlugin = function (plugin) {
  24321. plugin.extensions = plugin.extensions.toLowerCase();
  24322. SceneLoader._registeredPlugins.push(plugin);
  24323. };
  24324. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24325. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24326. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24327. return;
  24328. }
  24329. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24330. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24331. return;
  24332. }
  24333. var loadingToken = {};
  24334. scene._addPendingData(loadingToken);
  24335. var manifestChecked = function (success) {
  24336. scene.database = database;
  24337. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  24338. var importMeshFromData = function (data) {
  24339. var meshes = [];
  24340. var particleSystems = [];
  24341. var skeletons = [];
  24342. try {
  24343. if (plugin.importMesh) {
  24344. var syncedPlugin = plugin;
  24345. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  24346. if (onerror) {
  24347. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24348. }
  24349. scene._removePendingData(loadingToken);
  24350. return;
  24351. }
  24352. if (onsuccess) {
  24353. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24354. onsuccess(meshes, particleSystems, skeletons);
  24355. scene._removePendingData(loadingToken);
  24356. }
  24357. }
  24358. else {
  24359. var asyncedPlugin = plugin;
  24360. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  24361. if (onsuccess) {
  24362. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24363. onsuccess(meshes, particleSystems, skeletons);
  24364. scene._removePendingData(loadingToken);
  24365. }
  24366. }, function () {
  24367. if (onerror) {
  24368. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24369. }
  24370. scene._removePendingData(loadingToken);
  24371. });
  24372. }
  24373. }
  24374. catch (e) {
  24375. if (onerror) {
  24376. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  24377. }
  24378. scene._removePendingData(loadingToken);
  24379. }
  24380. };
  24381. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24382. // Direct load
  24383. importMeshFromData(sceneFilename.substr(5));
  24384. return;
  24385. }
  24386. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  24387. importMeshFromData(data);
  24388. }, progressCallBack, database);
  24389. };
  24390. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  24391. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24392. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24393. }
  24394. else {
  24395. // If the scene is a data stream or offline support is not enabled, it's a direct load
  24396. manifestChecked(true);
  24397. }
  24398. };
  24399. /**
  24400. * Load a scene
  24401. * @param rootUrl a string that defines the root url for scene and resources
  24402. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24403. * @param engine is the instance of BABYLON.Engine to use to create the scene
  24404. */
  24405. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  24406. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  24407. };
  24408. /**
  24409. * Append a scene
  24410. * @param rootUrl a string that defines the root url for scene and resources
  24411. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24412. * @param scene is the instance of BABYLON.Scene to append to
  24413. */
  24414. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24415. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24416. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24417. return;
  24418. }
  24419. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  24420. var database;
  24421. var loadingToken = {};
  24422. scene._addPendingData(loadingToken);
  24423. if (SceneLoader.ShowLoadingScreen) {
  24424. scene.getEngine().displayLoadingUI();
  24425. }
  24426. var loadSceneFromData = function (data) {
  24427. scene.database = database;
  24428. if (plugin.load) {
  24429. var syncedPlugin = plugin;
  24430. if (!syncedPlugin.load(scene, data, rootUrl)) {
  24431. if (onerror) {
  24432. onerror(scene);
  24433. }
  24434. scene._removePendingData(loadingToken);
  24435. scene.getEngine().hideLoadingUI();
  24436. return;
  24437. }
  24438. if (onsuccess) {
  24439. onsuccess(scene);
  24440. }
  24441. scene._removePendingData(loadingToken);
  24442. }
  24443. else {
  24444. var asyncedPlugin = plugin;
  24445. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  24446. if (onsuccess) {
  24447. onsuccess(scene);
  24448. }
  24449. }, function () {
  24450. if (onerror) {
  24451. onerror(scene);
  24452. }
  24453. scene._removePendingData(loadingToken);
  24454. scene.getEngine().hideLoadingUI();
  24455. });
  24456. }
  24457. if (SceneLoader.ShowLoadingScreen) {
  24458. scene.executeWhenReady(function () {
  24459. scene.getEngine().hideLoadingUI();
  24460. });
  24461. }
  24462. };
  24463. var manifestChecked = function (success) {
  24464. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  24465. };
  24466. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24467. // Direct load
  24468. loadSceneFromData(sceneFilename.substr(5));
  24469. return;
  24470. }
  24471. if (rootUrl.indexOf("file:") === -1) {
  24472. if (scene.getEngine().enableOfflineSupport) {
  24473. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24474. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24475. }
  24476. else {
  24477. manifestChecked(true);
  24478. }
  24479. }
  24480. else {
  24481. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  24482. }
  24483. };
  24484. // Flags
  24485. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  24486. SceneLoader._ShowLoadingScreen = true;
  24487. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  24488. // Members
  24489. SceneLoader._registeredPlugins = new Array();
  24490. return SceneLoader;
  24491. })();
  24492. BABYLON.SceneLoader = SceneLoader;
  24493. ;
  24494. })(BABYLON || (BABYLON = {}));
  24495. var BABYLON;
  24496. (function (BABYLON) {
  24497. var Internals;
  24498. (function (Internals) {
  24499. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  24500. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24501. var parsedMaterial = parsedData.materials[index];
  24502. if (parsedMaterial.id === id) {
  24503. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24504. }
  24505. }
  24506. return null;
  24507. };
  24508. var isDescendantOf = function (mesh, names, hierarchyIds) {
  24509. names = (names instanceof Array) ? names : [names];
  24510. for (var i in names) {
  24511. if (mesh.name === names[i]) {
  24512. hierarchyIds.push(mesh.id);
  24513. return true;
  24514. }
  24515. }
  24516. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  24517. hierarchyIds.push(mesh.id);
  24518. return true;
  24519. }
  24520. return false;
  24521. };
  24522. var logOperation = function (operation, producer) {
  24523. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  24524. };
  24525. BABYLON.SceneLoader.RegisterPlugin({
  24526. extensions: ".babylon",
  24527. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  24528. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24529. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24530. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24531. // and avoid problems with multiple concurrent .babylon loads.
  24532. var log = "importMesh has failed JSON parse";
  24533. try {
  24534. var parsedData = JSON.parse(data);
  24535. log = "";
  24536. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24537. var loadedSkeletonsIds = [];
  24538. var loadedMaterialsIds = [];
  24539. var hierarchyIds = [];
  24540. var index;
  24541. var cache;
  24542. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24543. var parsedMesh = parsedData.meshes[index];
  24544. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  24545. if (meshesNames instanceof Array) {
  24546. // Remove found mesh name from list.
  24547. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  24548. }
  24549. //Geometry?
  24550. if (parsedMesh.geometryId) {
  24551. //does the file contain geometries?
  24552. if (parsedData.geometries) {
  24553. //find the correct geometry and add it to the scene
  24554. var found = false;
  24555. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  24556. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  24557. return;
  24558. }
  24559. else {
  24560. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  24561. if (parsedGeometryData.id === parsedMesh.geometryId) {
  24562. switch (geometryType) {
  24563. case "boxes":
  24564. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  24565. break;
  24566. case "spheres":
  24567. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  24568. break;
  24569. case "cylinders":
  24570. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  24571. break;
  24572. case "toruses":
  24573. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  24574. break;
  24575. case "grounds":
  24576. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  24577. break;
  24578. case "planes":
  24579. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  24580. break;
  24581. case "torusKnots":
  24582. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  24583. break;
  24584. case "vertexData":
  24585. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  24586. break;
  24587. }
  24588. found = true;
  24589. }
  24590. });
  24591. }
  24592. });
  24593. if (!found) {
  24594. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  24595. }
  24596. }
  24597. }
  24598. // Material ?
  24599. if (parsedMesh.materialId) {
  24600. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  24601. if (!materialFound && parsedData.multiMaterials) {
  24602. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  24603. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  24604. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  24605. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  24606. var subMatId = parsedMultiMaterial.materials[matIndex];
  24607. loadedMaterialsIds.push(subMatId);
  24608. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  24609. log += "\n\tMaterial " + mat.toString(fullDetails);
  24610. }
  24611. loadedMaterialsIds.push(parsedMultiMaterial.id);
  24612. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24613. materialFound = true;
  24614. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  24615. break;
  24616. }
  24617. }
  24618. }
  24619. if (!materialFound) {
  24620. loadedMaterialsIds.push(parsedMesh.materialId);
  24621. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  24622. if (!mat) {
  24623. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  24624. }
  24625. else {
  24626. log += "\n\tMaterial " + mat.toString(fullDetails);
  24627. }
  24628. }
  24629. }
  24630. // Skeleton ?
  24631. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  24632. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  24633. if (!skeletonAlreadyLoaded) {
  24634. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  24635. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  24636. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  24637. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24638. skeletons.push(skeleton);
  24639. loadedSkeletonsIds.push(parsedSkeleton.id);
  24640. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  24641. }
  24642. }
  24643. }
  24644. }
  24645. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24646. meshes.push(mesh);
  24647. log += "\n\tMesh " + mesh.toString(fullDetails);
  24648. }
  24649. }
  24650. // Connecting parents
  24651. var currentMesh;
  24652. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24653. currentMesh = scene.meshes[index];
  24654. if (currentMesh._waitingParentId) {
  24655. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  24656. currentMesh._waitingParentId = undefined;
  24657. }
  24658. }
  24659. // freeze and compute world matrix application
  24660. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24661. currentMesh = scene.meshes[index];
  24662. if (currentMesh._waitingFreezeWorldMatrix) {
  24663. currentMesh.freezeWorldMatrix();
  24664. currentMesh._waitingFreezeWorldMatrix = undefined;
  24665. }
  24666. else {
  24667. currentMesh.computeWorldMatrix(true);
  24668. }
  24669. }
  24670. // Particles
  24671. if (parsedData.particleSystems) {
  24672. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24673. var parsedParticleSystem = parsedData.particleSystems[index];
  24674. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  24675. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  24676. }
  24677. }
  24678. }
  24679. return true;
  24680. }
  24681. catch (err) {
  24682. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  24683. log = null;
  24684. throw err;
  24685. }
  24686. finally {
  24687. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24688. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24689. }
  24690. }
  24691. },
  24692. load: function (scene, data, rootUrl) {
  24693. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24694. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24695. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24696. // and avoid problems with multiple concurrent .babylon loads.
  24697. var log = "importScene has failed JSON parse";
  24698. try {
  24699. var parsedData = JSON.parse(data);
  24700. log = "";
  24701. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24702. // Scene
  24703. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  24704. scene.autoClear = parsedData.autoClear;
  24705. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  24706. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  24707. if (parsedData.gravity) {
  24708. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  24709. }
  24710. // Fog
  24711. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  24712. scene.fogMode = parsedData.fogMode;
  24713. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  24714. scene.fogStart = parsedData.fogStart;
  24715. scene.fogEnd = parsedData.fogEnd;
  24716. scene.fogDensity = parsedData.fogDensity;
  24717. log += "\tFog mode for scene: ";
  24718. switch (scene.fogMode) {
  24719. // getters not compiling, so using hardcoded
  24720. case 1:
  24721. log += "exp\n";
  24722. break;
  24723. case 2:
  24724. log += "exp2\n";
  24725. break;
  24726. case 3:
  24727. log += "linear\n";
  24728. break;
  24729. }
  24730. }
  24731. //Physics
  24732. if (parsedData.physicsEnabled) {
  24733. var physicsPlugin;
  24734. if (parsedData.physicsEngine === "cannon") {
  24735. physicsPlugin = new BABYLON.CannonJSPlugin();
  24736. }
  24737. else if (parsedData.physicsEngine === "oimo") {
  24738. physicsPlugin = new BABYLON.OimoJSPlugin();
  24739. }
  24740. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  24741. //else - default engine, which is currently oimo
  24742. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  24743. scene.enablePhysics(physicsGravity, physicsPlugin);
  24744. }
  24745. //collisions, if defined. otherwise, default is true
  24746. if (parsedData.collisionsEnabled != undefined) {
  24747. scene.collisionsEnabled = parsedData.collisionsEnabled;
  24748. }
  24749. scene.workerCollisions = !!parsedData.workerCollisions;
  24750. var index;
  24751. var cache;
  24752. // Lights
  24753. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  24754. var parsedLight = parsedData.lights[index];
  24755. var light = BABYLON.Light.Parse(parsedLight, scene);
  24756. log += (index === 0 ? "\n\tLights:" : "");
  24757. log += "\n\t\t" + light.toString(fullDetails);
  24758. }
  24759. // Animations
  24760. if (parsedData.animations) {
  24761. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  24762. var parsedAnimation = parsedData.animations[index];
  24763. var animation = BABYLON.Animation.Parse(parsedAnimation);
  24764. scene.animations.push(animation);
  24765. log += (index === 0 ? "\n\tAnimations:" : "");
  24766. log += "\n\t\t" + animation.toString(fullDetails);
  24767. }
  24768. }
  24769. if (parsedData.autoAnimate) {
  24770. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  24771. }
  24772. // Materials
  24773. if (parsedData.materials) {
  24774. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24775. var parsedMaterial = parsedData.materials[index];
  24776. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24777. log += (index === 0 ? "\n\tMaterials:" : "");
  24778. log += "\n\t\t" + mat.toString(fullDetails);
  24779. }
  24780. }
  24781. if (parsedData.multiMaterials) {
  24782. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  24783. var parsedMultiMaterial = parsedData.multiMaterials[index];
  24784. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24785. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  24786. log += "\n\t\t" + mmat.toString(fullDetails);
  24787. }
  24788. }
  24789. // Skeletons
  24790. if (parsedData.skeletons) {
  24791. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  24792. var parsedSkeleton = parsedData.skeletons[index];
  24793. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24794. log += (index === 0 ? "\n\tSkeletons:" : "");
  24795. log += "\n\t\t" + skeleton.toString(fullDetails);
  24796. }
  24797. }
  24798. // Geometries
  24799. var geometries = parsedData.geometries;
  24800. if (geometries) {
  24801. // Boxes
  24802. var boxes = geometries.boxes;
  24803. if (boxes) {
  24804. for (index = 0, cache = boxes.length; index < cache; index++) {
  24805. var parsedBox = boxes[index];
  24806. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24807. }
  24808. }
  24809. // Spheres
  24810. var spheres = geometries.spheres;
  24811. if (spheres) {
  24812. for (index = 0, cache = spheres.length; index < cache; index++) {
  24813. var parsedSphere = spheres[index];
  24814. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24815. }
  24816. }
  24817. // Cylinders
  24818. var cylinders = geometries.cylinders;
  24819. if (cylinders) {
  24820. for (index = 0, cache = cylinders.length; index < cache; index++) {
  24821. var parsedCylinder = cylinders[index];
  24822. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  24823. }
  24824. }
  24825. // Toruses
  24826. var toruses = geometries.toruses;
  24827. if (toruses) {
  24828. for (index = 0, cache = toruses.length; index < cache; index++) {
  24829. var parsedTorus = toruses[index];
  24830. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24831. }
  24832. }
  24833. // Grounds
  24834. var grounds = geometries.grounds;
  24835. if (grounds) {
  24836. for (index = 0, cache = grounds.length; index < cache; index++) {
  24837. var parsedGround = grounds[index];
  24838. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24839. }
  24840. }
  24841. // Planes
  24842. var planes = geometries.planes;
  24843. if (planes) {
  24844. for (index = 0, cache = planes.length; index < cache; index++) {
  24845. var parsedPlane = planes[index];
  24846. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24847. }
  24848. }
  24849. // TorusKnots
  24850. var torusKnots = geometries.torusKnots;
  24851. if (torusKnots) {
  24852. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24853. var parsedTorusKnot = torusKnots[index];
  24854. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24855. }
  24856. }
  24857. // VertexData
  24858. var vertexData = geometries.vertexData;
  24859. if (vertexData) {
  24860. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24861. var parsedVertexData = vertexData[index];
  24862. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24863. }
  24864. }
  24865. }
  24866. // Meshes
  24867. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24868. var parsedMesh = parsedData.meshes[index];
  24869. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24870. log += (index === 0 ? "\n\tMeshes:" : "");
  24871. log += "\n\t\t" + mesh.toString(fullDetails);
  24872. }
  24873. // Cameras
  24874. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24875. var parsedCamera = parsedData.cameras[index];
  24876. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24877. log += (index === 0 ? "\n\tCameras:" : "");
  24878. log += "\n\t\t" + camera.toString(fullDetails);
  24879. }
  24880. if (parsedData.activeCameraID) {
  24881. scene.setActiveCameraByID(parsedData.activeCameraID);
  24882. }
  24883. // Browsing all the graph to connect the dots
  24884. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24885. var camera = scene.cameras[index];
  24886. if (camera._waitingParentId) {
  24887. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24888. camera._waitingParentId = undefined;
  24889. }
  24890. }
  24891. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24892. var light = scene.lights[index];
  24893. if (light._waitingParentId) {
  24894. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24895. light._waitingParentId = undefined;
  24896. }
  24897. }
  24898. // Sounds
  24899. var loadedSounds = [];
  24900. var loadedSound;
  24901. if (BABYLON.AudioEngine && parsedData.sounds) {
  24902. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24903. var parsedSound = parsedData.sounds[index];
  24904. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24905. if (!parsedSound.url)
  24906. parsedSound.url = parsedSound.name;
  24907. if (!loadedSounds[parsedSound.url]) {
  24908. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24909. loadedSounds[parsedSound.url] = loadedSound;
  24910. }
  24911. else {
  24912. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24913. }
  24914. }
  24915. else {
  24916. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24917. }
  24918. }
  24919. }
  24920. loadedSounds = [];
  24921. // Connect parents & children and parse actions
  24922. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24923. var mesh = scene.meshes[index];
  24924. if (mesh._waitingParentId) {
  24925. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24926. mesh._waitingParentId = undefined;
  24927. }
  24928. if (mesh._waitingActions) {
  24929. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24930. mesh._waitingActions = undefined;
  24931. }
  24932. }
  24933. // freeze world matrix application
  24934. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24935. var currentMesh = scene.meshes[index];
  24936. if (currentMesh._waitingFreezeWorldMatrix) {
  24937. currentMesh.freezeWorldMatrix();
  24938. currentMesh._waitingFreezeWorldMatrix = undefined;
  24939. }
  24940. else {
  24941. currentMesh.computeWorldMatrix(true);
  24942. }
  24943. }
  24944. // Particles Systems
  24945. if (parsedData.particleSystems) {
  24946. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24947. var parsedParticleSystem = parsedData.particleSystems[index];
  24948. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24949. }
  24950. }
  24951. // Lens flares
  24952. if (parsedData.lensFlareSystems) {
  24953. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24954. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24955. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24956. }
  24957. }
  24958. // Shadows
  24959. if (parsedData.shadowGenerators) {
  24960. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24961. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24962. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24963. }
  24964. }
  24965. // Actions (scene)
  24966. if (parsedData.actions) {
  24967. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24968. }
  24969. // Finish
  24970. return true;
  24971. }
  24972. catch (err) {
  24973. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24974. log = null;
  24975. throw err;
  24976. }
  24977. finally {
  24978. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24979. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24980. }
  24981. }
  24982. }
  24983. });
  24984. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24985. })(BABYLON || (BABYLON = {}));
  24986. var BABYLON;
  24987. (function (BABYLON) {
  24988. var SpriteManager = (function () {
  24989. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24991. this.name = name;
  24992. this.cellSize = cellSize;
  24993. this.sprites = new Array();
  24994. this.renderingGroupId = 0;
  24995. this.layerMask = 0x0FFFFFFF;
  24996. this.fogEnabled = true;
  24997. this.isPickable = false;
  24998. /**
  24999. * An event triggered when the manager is disposed.
  25000. * @type {BABYLON.Observable}
  25001. */
  25002. this.onDisposeObservable = new BABYLON.Observable();
  25003. this._vertexDeclaration = [4, 4, 4, 4];
  25004. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  25005. this._capacity = capacity;
  25006. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  25007. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25008. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25009. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  25010. this._scene = scene;
  25011. this._scene.spriteManagers.push(this);
  25012. // VBO
  25013. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  25014. var indices = [];
  25015. var index = 0;
  25016. for (var count = 0; count < capacity; count++) {
  25017. indices.push(index);
  25018. indices.push(index + 1);
  25019. indices.push(index + 2);
  25020. indices.push(index);
  25021. indices.push(index + 2);
  25022. indices.push(index + 3);
  25023. index += 4;
  25024. }
  25025. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25026. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  25027. // Effects
  25028. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  25029. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  25030. }
  25031. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  25032. set: function (callback) {
  25033. if (this._onDisposeObserver) {
  25034. this.onDisposeObservable.remove(this._onDisposeObserver);
  25035. }
  25036. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25037. },
  25038. enumerable: true,
  25039. configurable: true
  25040. });
  25041. Object.defineProperty(SpriteManager.prototype, "texture", {
  25042. get: function () {
  25043. return this._spriteTexture;
  25044. },
  25045. set: function (value) {
  25046. this._spriteTexture = value;
  25047. },
  25048. enumerable: true,
  25049. configurable: true
  25050. });
  25051. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  25052. var arrayOffset = index * 16;
  25053. if (offsetX === 0)
  25054. offsetX = this._epsilon;
  25055. else if (offsetX === 1)
  25056. offsetX = 1 - this._epsilon;
  25057. if (offsetY === 0)
  25058. offsetY = this._epsilon;
  25059. else if (offsetY === 1)
  25060. offsetY = 1 - this._epsilon;
  25061. this._vertices[arrayOffset] = sprite.position.x;
  25062. this._vertices[arrayOffset + 1] = sprite.position.y;
  25063. this._vertices[arrayOffset + 2] = sprite.position.z;
  25064. this._vertices[arrayOffset + 3] = sprite.angle;
  25065. this._vertices[arrayOffset + 4] = sprite.width;
  25066. this._vertices[arrayOffset + 5] = sprite.height;
  25067. this._vertices[arrayOffset + 6] = offsetX;
  25068. this._vertices[arrayOffset + 7] = offsetY;
  25069. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  25070. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  25071. var offset = (sprite.cellIndex / rowSize) >> 0;
  25072. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  25073. this._vertices[arrayOffset + 11] = offset;
  25074. // Color
  25075. this._vertices[arrayOffset + 12] = sprite.color.r;
  25076. this._vertices[arrayOffset + 13] = sprite.color.g;
  25077. this._vertices[arrayOffset + 14] = sprite.color.b;
  25078. this._vertices[arrayOffset + 15] = sprite.color.a;
  25079. };
  25080. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  25081. var count = Math.min(this._capacity, this.sprites.length);
  25082. var min = BABYLON.Vector3.Zero();
  25083. var max = BABYLON.Vector3.Zero();
  25084. var distance = Number.MAX_VALUE;
  25085. var currentSprite;
  25086. var cameraSpacePosition = BABYLON.Vector3.Zero();
  25087. var cameraView = camera.getViewMatrix();
  25088. for (var index = 0; index < count; index++) {
  25089. var sprite = this.sprites[index];
  25090. if (!sprite) {
  25091. continue;
  25092. }
  25093. if (predicate) {
  25094. if (!predicate(sprite)) {
  25095. continue;
  25096. }
  25097. }
  25098. else if (!sprite.isPickable) {
  25099. continue;
  25100. }
  25101. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  25102. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  25103. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  25104. if (ray.intersectsBoxMinMax(min, max)) {
  25105. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  25106. if (distance > currentDistance) {
  25107. distance = currentDistance;
  25108. currentSprite = sprite;
  25109. if (fastCheck) {
  25110. break;
  25111. }
  25112. }
  25113. }
  25114. }
  25115. if (currentSprite) {
  25116. var result = new BABYLON.PickingInfo();
  25117. result.hit = true;
  25118. result.pickedSprite = currentSprite;
  25119. result.distance = distance;
  25120. return result;
  25121. }
  25122. return null;
  25123. };
  25124. SpriteManager.prototype.render = function () {
  25125. // Check
  25126. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  25127. return;
  25128. var engine = this._scene.getEngine();
  25129. var baseSize = this._spriteTexture.getBaseSize();
  25130. // Sprites
  25131. var deltaTime = engine.getDeltaTime();
  25132. var max = Math.min(this._capacity, this.sprites.length);
  25133. var rowSize = baseSize.width / this.cellSize;
  25134. var offset = 0;
  25135. for (var index = 0; index < max; index++) {
  25136. var sprite = this.sprites[index];
  25137. if (!sprite) {
  25138. continue;
  25139. }
  25140. sprite._animate(deltaTime);
  25141. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  25142. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  25143. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  25144. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  25145. }
  25146. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  25147. // Render
  25148. var effect = this._effectBase;
  25149. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25150. effect = this._effectFog;
  25151. }
  25152. engine.enableEffect(effect);
  25153. var viewMatrix = this._scene.getViewMatrix();
  25154. effect.setTexture("diffuseSampler", this._spriteTexture);
  25155. effect.setMatrix("view", viewMatrix);
  25156. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25157. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  25158. // Fog
  25159. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25160. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  25161. effect.setColor3("vFogColor", this._scene.fogColor);
  25162. }
  25163. // VBOs
  25164. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25165. // Draw order
  25166. engine.setDepthFunctionToLessOrEqual();
  25167. effect.setBool("alphaTest", true);
  25168. engine.setColorWrite(false);
  25169. engine.draw(true, 0, max * 6);
  25170. engine.setColorWrite(true);
  25171. effect.setBool("alphaTest", false);
  25172. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25173. engine.draw(true, 0, max * 6);
  25174. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25175. };
  25176. SpriteManager.prototype.dispose = function () {
  25177. if (this._vertexBuffer) {
  25178. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25179. this._vertexBuffer = null;
  25180. }
  25181. if (this._indexBuffer) {
  25182. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25183. this._indexBuffer = null;
  25184. }
  25185. if (this._spriteTexture) {
  25186. this._spriteTexture.dispose();
  25187. this._spriteTexture = null;
  25188. }
  25189. // Remove from scene
  25190. var index = this._scene.spriteManagers.indexOf(this);
  25191. this._scene.spriteManagers.splice(index, 1);
  25192. // Callback
  25193. this.onDisposeObservable.notifyObservers(this);
  25194. this.onDisposeObservable.clear();
  25195. };
  25196. return SpriteManager;
  25197. })();
  25198. BABYLON.SpriteManager = SpriteManager;
  25199. })(BABYLON || (BABYLON = {}));
  25200. var BABYLON;
  25201. (function (BABYLON) {
  25202. var Sprite = (function () {
  25203. function Sprite(name, manager) {
  25204. this.name = name;
  25205. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25206. this.width = 1.0;
  25207. this.height = 1.0;
  25208. this.angle = 0;
  25209. this.cellIndex = 0;
  25210. this.invertU = 0;
  25211. this.invertV = 0;
  25212. this.animations = new Array();
  25213. this.isPickable = false;
  25214. this._animationStarted = false;
  25215. this._loopAnimation = false;
  25216. this._fromIndex = 0;
  25217. this._toIndex = 0;
  25218. this._delay = 0;
  25219. this._direction = 1;
  25220. this._frameCount = 0;
  25221. this._time = 0;
  25222. this._manager = manager;
  25223. this._manager.sprites.push(this);
  25224. this.position = BABYLON.Vector3.Zero();
  25225. }
  25226. Object.defineProperty(Sprite.prototype, "size", {
  25227. get: function () {
  25228. return this.width;
  25229. },
  25230. set: function (value) {
  25231. this.width = value;
  25232. this.height = value;
  25233. },
  25234. enumerable: true,
  25235. configurable: true
  25236. });
  25237. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  25238. this._fromIndex = from;
  25239. this._toIndex = to;
  25240. this._loopAnimation = loop;
  25241. this._delay = delay;
  25242. this._animationStarted = true;
  25243. this._direction = from < to ? 1 : -1;
  25244. this.cellIndex = from;
  25245. this._time = 0;
  25246. };
  25247. Sprite.prototype.stopAnimation = function () {
  25248. this._animationStarted = false;
  25249. };
  25250. Sprite.prototype._animate = function (deltaTime) {
  25251. if (!this._animationStarted)
  25252. return;
  25253. this._time += deltaTime;
  25254. if (this._time > this._delay) {
  25255. this._time = this._time % this._delay;
  25256. this.cellIndex += this._direction;
  25257. if (this.cellIndex == this._toIndex) {
  25258. if (this._loopAnimation) {
  25259. this.cellIndex = this._fromIndex;
  25260. }
  25261. else {
  25262. this._animationStarted = false;
  25263. if (this.disposeWhenFinishedAnimating) {
  25264. this.dispose();
  25265. }
  25266. }
  25267. }
  25268. }
  25269. };
  25270. Sprite.prototype.dispose = function () {
  25271. for (var i = 0; i < this._manager.sprites.length; i++) {
  25272. if (this._manager.sprites[i] == this) {
  25273. this._manager.sprites.splice(i, 1);
  25274. }
  25275. }
  25276. };
  25277. return Sprite;
  25278. })();
  25279. BABYLON.Sprite = Sprite;
  25280. })(BABYLON || (BABYLON = {}));
  25281. var BABYLON;
  25282. (function (BABYLON) {
  25283. var Layer = (function () {
  25284. function Layer(name, imgUrl, scene, isBackground, color) {
  25285. this.name = name;
  25286. this.scale = new BABYLON.Vector2(1, 1);
  25287. this.offset = new BABYLON.Vector2(0, 0);
  25288. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  25289. this._vertexDeclaration = [2];
  25290. this._vertexStrideSize = 2 * 4;
  25291. // Events
  25292. /**
  25293. * An event triggered when the layer is disposed.
  25294. * @type {BABYLON.Observable}
  25295. */
  25296. this.onDisposeObservable = new BABYLON.Observable();
  25297. /**
  25298. * An event triggered before rendering the scene
  25299. * @type {BABYLON.Observable}
  25300. */
  25301. this.onBeforeRenderObservable = new BABYLON.Observable();
  25302. /**
  25303. * An event triggered after rendering the scene
  25304. * @type {BABYLON.Observable}
  25305. */
  25306. this.onAfterRenderObservable = new BABYLON.Observable();
  25307. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  25308. this.isBackground = isBackground === undefined ? true : isBackground;
  25309. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  25310. this._scene = scene;
  25311. this._scene.layers.push(this);
  25312. // VBO
  25313. var vertices = [];
  25314. vertices.push(1, 1);
  25315. vertices.push(-1, 1);
  25316. vertices.push(-1, -1);
  25317. vertices.push(1, -1);
  25318. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  25319. // Indices
  25320. var indices = [];
  25321. indices.push(0);
  25322. indices.push(1);
  25323. indices.push(2);
  25324. indices.push(0);
  25325. indices.push(2);
  25326. indices.push(3);
  25327. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25328. // Effects
  25329. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  25330. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  25331. }
  25332. Object.defineProperty(Layer.prototype, "onDispose", {
  25333. set: function (callback) {
  25334. if (this._onDisposeObserver) {
  25335. this.onDisposeObservable.remove(this._onDisposeObserver);
  25336. }
  25337. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25338. },
  25339. enumerable: true,
  25340. configurable: true
  25341. });
  25342. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  25343. set: function (callback) {
  25344. if (this._onBeforeRenderObserver) {
  25345. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25346. }
  25347. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25348. },
  25349. enumerable: true,
  25350. configurable: true
  25351. });
  25352. Object.defineProperty(Layer.prototype, "onAfterRender", {
  25353. set: function (callback) {
  25354. if (this._onAfterRenderObserver) {
  25355. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25356. }
  25357. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25358. },
  25359. enumerable: true,
  25360. configurable: true
  25361. });
  25362. Layer.prototype.render = function () {
  25363. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  25364. // Check
  25365. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  25366. return;
  25367. var engine = this._scene.getEngine();
  25368. this.onBeforeRenderObservable.notifyObservers(this);
  25369. // Render
  25370. engine.enableEffect(currentEffect);
  25371. engine.setState(false);
  25372. // Texture
  25373. currentEffect.setTexture("textureSampler", this.texture);
  25374. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  25375. // Color
  25376. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  25377. // Scale / offset
  25378. currentEffect.setVector2("offset", this.offset);
  25379. currentEffect.setVector2("scale", this.scale);
  25380. // VBOs
  25381. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  25382. // Draw order
  25383. if (!this._alphaTestEffect) {
  25384. engine.setAlphaMode(this.alphaBlendingMode);
  25385. engine.draw(true, 0, 6);
  25386. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25387. }
  25388. else {
  25389. engine.draw(true, 0, 6);
  25390. }
  25391. this.onAfterRenderObservable.notifyObservers(this);
  25392. };
  25393. Layer.prototype.dispose = function () {
  25394. if (this._vertexBuffer) {
  25395. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25396. this._vertexBuffer = null;
  25397. }
  25398. if (this._indexBuffer) {
  25399. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25400. this._indexBuffer = null;
  25401. }
  25402. if (this.texture) {
  25403. this.texture.dispose();
  25404. this.texture = null;
  25405. }
  25406. // Remove from scene
  25407. var index = this._scene.layers.indexOf(this);
  25408. this._scene.layers.splice(index, 1);
  25409. // Callback
  25410. this.onDisposeObservable.notifyObservers(this);
  25411. this.onDisposeObservable.clear();
  25412. this.onAfterRenderObservable.clear();
  25413. this.onBeforeRenderObservable.clear();
  25414. };
  25415. return Layer;
  25416. })();
  25417. BABYLON.Layer = Layer;
  25418. })(BABYLON || (BABYLON = {}));
  25419. var BABYLON;
  25420. (function (BABYLON) {
  25421. var Particle = (function () {
  25422. function Particle() {
  25423. this.position = BABYLON.Vector3.Zero();
  25424. this.direction = BABYLON.Vector3.Zero();
  25425. this.color = new BABYLON.Color4(0, 0, 0, 0);
  25426. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  25427. this.lifeTime = 1.0;
  25428. this.age = 0;
  25429. this.size = 0;
  25430. this.angle = 0;
  25431. this.angularSpeed = 0;
  25432. }
  25433. Particle.prototype.copyTo = function (other) {
  25434. other.position.copyFrom(this.position);
  25435. other.direction.copyFrom(this.direction);
  25436. other.color.copyFrom(this.color);
  25437. other.colorStep.copyFrom(this.colorStep);
  25438. other.lifeTime = this.lifeTime;
  25439. other.age = this.age;
  25440. other.size = this.size;
  25441. other.angle = this.angle;
  25442. other.angularSpeed = this.angularSpeed;
  25443. };
  25444. return Particle;
  25445. })();
  25446. BABYLON.Particle = Particle;
  25447. })(BABYLON || (BABYLON = {}));
  25448. var BABYLON;
  25449. (function (BABYLON) {
  25450. var randomNumber = function (min, max) {
  25451. if (min === max) {
  25452. return (min);
  25453. }
  25454. var random = Math.random();
  25455. return ((random * (max - min)) + min);
  25456. };
  25457. var ParticleSystem = (function () {
  25458. function ParticleSystem(name, capacity, scene, customEffect) {
  25459. var _this = this;
  25460. this.name = name;
  25461. // Members
  25462. this.animations = [];
  25463. this.renderingGroupId = 0;
  25464. this.emitter = null;
  25465. this.emitRate = 10;
  25466. this.manualEmitCount = -1;
  25467. this.updateSpeed = 0.01;
  25468. this.targetStopDuration = 0;
  25469. this.disposeOnStop = false;
  25470. this.minEmitPower = 1;
  25471. this.maxEmitPower = 1;
  25472. this.minLifeTime = 1;
  25473. this.maxLifeTime = 1;
  25474. this.minSize = 1;
  25475. this.maxSize = 1;
  25476. this.minAngularSpeed = 0;
  25477. this.maxAngularSpeed = 0;
  25478. this.layerMask = 0x0FFFFFFF;
  25479. /**
  25480. * An event triggered when the system is disposed.
  25481. * @type {BABYLON.Observable}
  25482. */
  25483. this.onDisposeObservable = new BABYLON.Observable();
  25484. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  25485. this.forceDepthWrite = false;
  25486. this.gravity = BABYLON.Vector3.Zero();
  25487. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  25488. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  25489. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  25490. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  25491. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25492. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25493. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  25494. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25495. this.particles = new Array();
  25496. this._vertexDeclaration = [3, 4, 4];
  25497. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  25498. this._stockParticles = new Array();
  25499. this._newPartsExcess = 0;
  25500. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  25501. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  25502. this._scaledDirection = BABYLON.Vector3.Zero();
  25503. this._scaledGravity = BABYLON.Vector3.Zero();
  25504. this._currentRenderId = -1;
  25505. this._started = false;
  25506. this._stopped = false;
  25507. this._actualFrame = 0;
  25508. this.id = name;
  25509. this._capacity = capacity;
  25510. this._scene = scene;
  25511. this._customEffect = customEffect;
  25512. scene.particleSystems.push(this);
  25513. // VBO
  25514. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  25515. var indices = [];
  25516. var index = 0;
  25517. for (var count = 0; count < capacity; count++) {
  25518. indices.push(index);
  25519. indices.push(index + 1);
  25520. indices.push(index + 2);
  25521. indices.push(index);
  25522. indices.push(index + 2);
  25523. indices.push(index + 3);
  25524. index += 4;
  25525. }
  25526. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25527. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  25528. // Default behaviors
  25529. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  25530. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  25531. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  25532. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  25533. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  25534. };
  25535. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  25536. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  25537. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  25538. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  25539. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  25540. };
  25541. this.updateFunction = function (particles) {
  25542. for (var index = 0; index < particles.length; index++) {
  25543. var particle = particles[index];
  25544. particle.age += _this._scaledUpdateSpeed;
  25545. if (particle.age >= particle.lifeTime) {
  25546. _this.recycleParticle(particle);
  25547. index--;
  25548. continue;
  25549. }
  25550. else {
  25551. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  25552. particle.color.addInPlace(_this._scaledColorStep);
  25553. if (particle.color.a < 0)
  25554. particle.color.a = 0;
  25555. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  25556. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  25557. particle.position.addInPlace(_this._scaledDirection);
  25558. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  25559. particle.direction.addInPlace(_this._scaledGravity);
  25560. }
  25561. }
  25562. };
  25563. }
  25564. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  25565. set: function (callback) {
  25566. if (this._onDisposeObserver) {
  25567. this.onDisposeObservable.remove(this._onDisposeObserver);
  25568. }
  25569. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25570. },
  25571. enumerable: true,
  25572. configurable: true
  25573. });
  25574. ParticleSystem.prototype.recycleParticle = function (particle) {
  25575. var lastParticle = this.particles.pop();
  25576. if (lastParticle !== particle) {
  25577. lastParticle.copyTo(particle);
  25578. this._stockParticles.push(lastParticle);
  25579. }
  25580. };
  25581. ParticleSystem.prototype.getCapacity = function () {
  25582. return this._capacity;
  25583. };
  25584. ParticleSystem.prototype.isAlive = function () {
  25585. return this._alive;
  25586. };
  25587. ParticleSystem.prototype.isStarted = function () {
  25588. return this._started;
  25589. };
  25590. ParticleSystem.prototype.start = function () {
  25591. this._started = true;
  25592. this._stopped = false;
  25593. this._actualFrame = 0;
  25594. };
  25595. ParticleSystem.prototype.stop = function () {
  25596. this._stopped = true;
  25597. };
  25598. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  25599. var offset = index * 11;
  25600. this._vertices[offset] = particle.position.x;
  25601. this._vertices[offset + 1] = particle.position.y;
  25602. this._vertices[offset + 2] = particle.position.z;
  25603. this._vertices[offset + 3] = particle.color.r;
  25604. this._vertices[offset + 4] = particle.color.g;
  25605. this._vertices[offset + 5] = particle.color.b;
  25606. this._vertices[offset + 6] = particle.color.a;
  25607. this._vertices[offset + 7] = particle.angle;
  25608. this._vertices[offset + 8] = particle.size;
  25609. this._vertices[offset + 9] = offsetX;
  25610. this._vertices[offset + 10] = offsetY;
  25611. };
  25612. ParticleSystem.prototype._update = function (newParticles) {
  25613. // Update current
  25614. this._alive = this.particles.length > 0;
  25615. this.updateFunction(this.particles);
  25616. // Add new ones
  25617. var worldMatrix;
  25618. if (this.emitter.position) {
  25619. worldMatrix = this.emitter.getWorldMatrix();
  25620. }
  25621. else {
  25622. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  25623. }
  25624. var particle;
  25625. for (var index = 0; index < newParticles; index++) {
  25626. if (this.particles.length === this._capacity) {
  25627. break;
  25628. }
  25629. if (this._stockParticles.length !== 0) {
  25630. particle = this._stockParticles.pop();
  25631. particle.age = 0;
  25632. }
  25633. else {
  25634. particle = new BABYLON.Particle();
  25635. }
  25636. this.particles.push(particle);
  25637. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  25638. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  25639. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  25640. particle.size = randomNumber(this.minSize, this.maxSize);
  25641. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  25642. this.startPositionFunction(worldMatrix, particle.position, particle);
  25643. var step = randomNumber(0, 1.0);
  25644. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  25645. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  25646. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  25647. }
  25648. };
  25649. ParticleSystem.prototype._getEffect = function () {
  25650. if (this._customEffect) {
  25651. return this._customEffect;
  25652. }
  25653. ;
  25654. var defines = [];
  25655. if (this._scene.clipPlane) {
  25656. defines.push("#define CLIPPLANE");
  25657. }
  25658. // Effect
  25659. var join = defines.join("\n");
  25660. if (this._cachedDefines !== join) {
  25661. this._cachedDefines = join;
  25662. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  25663. }
  25664. return this._effect;
  25665. };
  25666. ParticleSystem.prototype.animate = function () {
  25667. if (!this._started)
  25668. return;
  25669. var effect = this._getEffect();
  25670. // Check
  25671. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  25672. return;
  25673. if (this._currentRenderId === this._scene.getRenderId()) {
  25674. return;
  25675. }
  25676. this._currentRenderId = this._scene.getRenderId();
  25677. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  25678. // determine the number of particles we need to create
  25679. var newParticles;
  25680. if (this.manualEmitCount > -1) {
  25681. newParticles = this.manualEmitCount;
  25682. this._newPartsExcess = 0;
  25683. this.manualEmitCount = 0;
  25684. }
  25685. else {
  25686. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  25687. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  25688. }
  25689. if (this._newPartsExcess > 1.0) {
  25690. newParticles += this._newPartsExcess >> 0;
  25691. this._newPartsExcess -= this._newPartsExcess >> 0;
  25692. }
  25693. this._alive = false;
  25694. if (!this._stopped) {
  25695. this._actualFrame += this._scaledUpdateSpeed;
  25696. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  25697. this.stop();
  25698. }
  25699. else {
  25700. newParticles = 0;
  25701. }
  25702. this._update(newParticles);
  25703. // Stopped?
  25704. if (this._stopped) {
  25705. if (!this._alive) {
  25706. this._started = false;
  25707. if (this.disposeOnStop) {
  25708. this._scene._toBeDisposed.push(this);
  25709. }
  25710. }
  25711. }
  25712. // Update VBO
  25713. var offset = 0;
  25714. for (var index = 0; index < this.particles.length; index++) {
  25715. var particle = this.particles[index];
  25716. this._appendParticleVertex(offset++, particle, 0, 0);
  25717. this._appendParticleVertex(offset++, particle, 1, 0);
  25718. this._appendParticleVertex(offset++, particle, 1, 1);
  25719. this._appendParticleVertex(offset++, particle, 0, 1);
  25720. }
  25721. var engine = this._scene.getEngine();
  25722. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  25723. };
  25724. ParticleSystem.prototype.render = function () {
  25725. var effect = this._getEffect();
  25726. // Check
  25727. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  25728. return 0;
  25729. var engine = this._scene.getEngine();
  25730. // Render
  25731. engine.enableEffect(effect);
  25732. engine.setState(false);
  25733. var viewMatrix = this._scene.getViewMatrix();
  25734. effect.setTexture("diffuseSampler", this.particleTexture);
  25735. effect.setMatrix("view", viewMatrix);
  25736. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25737. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  25738. if (this._scene.clipPlane) {
  25739. var clipPlane = this._scene.clipPlane;
  25740. var invView = viewMatrix.clone();
  25741. invView.invert();
  25742. effect.setMatrix("invView", invView);
  25743. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25744. }
  25745. // VBOs
  25746. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25747. // Draw order
  25748. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  25749. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  25750. }
  25751. else {
  25752. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25753. }
  25754. if (this.forceDepthWrite) {
  25755. engine.setDepthWrite(true);
  25756. }
  25757. engine.draw(true, 0, this.particles.length * 6);
  25758. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25759. return this.particles.length;
  25760. };
  25761. ParticleSystem.prototype.dispose = function () {
  25762. if (this._vertexBuffer) {
  25763. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25764. this._vertexBuffer = null;
  25765. }
  25766. if (this._indexBuffer) {
  25767. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25768. this._indexBuffer = null;
  25769. }
  25770. if (this.particleTexture) {
  25771. this.particleTexture.dispose();
  25772. this.particleTexture = null;
  25773. }
  25774. // Remove from scene
  25775. var index = this._scene.particleSystems.indexOf(this);
  25776. this._scene.particleSystems.splice(index, 1);
  25777. // Callback
  25778. this.onDisposeObservable.notifyObservers(this);
  25779. this.onDisposeObservable.clear();
  25780. };
  25781. // Clone
  25782. ParticleSystem.prototype.clone = function (name, newEmitter) {
  25783. var result = new ParticleSystem(name, this._capacity, this._scene);
  25784. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  25785. if (newEmitter === undefined) {
  25786. newEmitter = this.emitter;
  25787. }
  25788. result.emitter = newEmitter;
  25789. if (this.particleTexture) {
  25790. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  25791. }
  25792. result.start();
  25793. return result;
  25794. };
  25795. ParticleSystem.prototype.serialize = function () {
  25796. var serializationObject = {};
  25797. serializationObject.name = this.name;
  25798. serializationObject.id = this.id;
  25799. // Emitter
  25800. if (this.emitter.position) {
  25801. serializationObject.emitterId = this.emitter.id;
  25802. }
  25803. else {
  25804. serializationObject.emitter = this.emitter.asArray();
  25805. }
  25806. serializationObject.capacity = this.getCapacity();
  25807. if (this.particleTexture) {
  25808. serializationObject.textureName = this.particleTexture.name;
  25809. }
  25810. // Animations
  25811. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25812. // Particle system
  25813. serializationObject.minAngularSpeed = this.minAngularSpeed;
  25814. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  25815. serializationObject.minSize = this.minSize;
  25816. serializationObject.maxSize = this.maxSize;
  25817. serializationObject.minEmitPower = this.minEmitPower;
  25818. serializationObject.maxEmitPower = this.maxEmitPower;
  25819. serializationObject.minLifeTime = this.minLifeTime;
  25820. serializationObject.maxLifeTime = this.maxLifeTime;
  25821. serializationObject.emitRate = this.emitRate;
  25822. serializationObject.minEmitBox = this.minEmitBox.asArray();
  25823. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  25824. serializationObject.gravity = this.gravity.asArray();
  25825. serializationObject.direction1 = this.direction1.asArray();
  25826. serializationObject.direction2 = this.direction2.asArray();
  25827. serializationObject.color1 = this.color1.asArray();
  25828. serializationObject.color2 = this.color2.asArray();
  25829. serializationObject.colorDead = this.colorDead.asArray();
  25830. serializationObject.updateSpeed = this.updateSpeed;
  25831. serializationObject.targetStopDuration = this.targetStopDuration;
  25832. serializationObject.textureMask = this.textureMask.asArray();
  25833. serializationObject.blendMode = this.blendMode;
  25834. return serializationObject;
  25835. };
  25836. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  25837. var name = parsedParticleSystem.name;
  25838. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  25839. if (parsedParticleSystem.id) {
  25840. particleSystem.id = parsedParticleSystem.id;
  25841. }
  25842. // Texture
  25843. if (parsedParticleSystem.textureName) {
  25844. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  25845. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  25846. }
  25847. // Emitter
  25848. if (parsedParticleSystem.emitterId) {
  25849. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  25850. }
  25851. else {
  25852. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  25853. }
  25854. // Animations
  25855. if (parsedParticleSystem.animations) {
  25856. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  25857. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  25858. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25859. }
  25860. }
  25861. if (parsedParticleSystem.autoAnimate) {
  25862. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  25863. }
  25864. // Particle system
  25865. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  25866. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  25867. particleSystem.minSize = parsedParticleSystem.minSize;
  25868. particleSystem.maxSize = parsedParticleSystem.maxSize;
  25869. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  25870. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  25871. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  25872. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  25873. particleSystem.emitRate = parsedParticleSystem.emitRate;
  25874. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  25875. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  25876. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  25877. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  25878. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  25879. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  25880. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  25881. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  25882. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  25883. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  25884. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  25885. particleSystem.blendMode = parsedParticleSystem.blendMode;
  25886. if (!parsedParticleSystem.preventAutoStart) {
  25887. particleSystem.start();
  25888. }
  25889. return particleSystem;
  25890. };
  25891. // Statics
  25892. ParticleSystem.BLENDMODE_ONEONE = 0;
  25893. ParticleSystem.BLENDMODE_STANDARD = 1;
  25894. return ParticleSystem;
  25895. })();
  25896. BABYLON.ParticleSystem = ParticleSystem;
  25897. })(BABYLON || (BABYLON = {}));
  25898. var BABYLON;
  25899. (function (BABYLON) {
  25900. var AnimationRange = (function () {
  25901. function AnimationRange(name, from, to) {
  25902. this.name = name;
  25903. this.from = from;
  25904. this.to = to;
  25905. }
  25906. AnimationRange.prototype.clone = function () {
  25907. return new AnimationRange(this.name, this.from, this.to);
  25908. };
  25909. return AnimationRange;
  25910. })();
  25911. BABYLON.AnimationRange = AnimationRange;
  25912. /**
  25913. * Composed of a frame, and an action function
  25914. */
  25915. var AnimationEvent = (function () {
  25916. function AnimationEvent(frame, action, onlyOnce) {
  25917. this.frame = frame;
  25918. this.action = action;
  25919. this.onlyOnce = onlyOnce;
  25920. this.isDone = false;
  25921. }
  25922. return AnimationEvent;
  25923. })();
  25924. BABYLON.AnimationEvent = AnimationEvent;
  25925. var PathCursor = (function () {
  25926. function PathCursor(path) {
  25927. this.path = path;
  25928. this._onchange = new Array();
  25929. this.value = 0;
  25930. this.animations = new Array();
  25931. }
  25932. PathCursor.prototype.getPoint = function () {
  25933. var point = this.path.getPointAtLengthPosition(this.value);
  25934. return new BABYLON.Vector3(point.x, 0, point.y);
  25935. };
  25936. PathCursor.prototype.moveAhead = function (step) {
  25937. if (step === void 0) { step = 0.002; }
  25938. this.move(step);
  25939. return this;
  25940. };
  25941. PathCursor.prototype.moveBack = function (step) {
  25942. if (step === void 0) { step = 0.002; }
  25943. this.move(-step);
  25944. return this;
  25945. };
  25946. PathCursor.prototype.move = function (step) {
  25947. if (Math.abs(step) > 1) {
  25948. throw "step size should be less than 1.";
  25949. }
  25950. this.value += step;
  25951. this.ensureLimits();
  25952. this.raiseOnChange();
  25953. return this;
  25954. };
  25955. PathCursor.prototype.ensureLimits = function () {
  25956. while (this.value > 1) {
  25957. this.value -= 1;
  25958. }
  25959. while (this.value < 0) {
  25960. this.value += 1;
  25961. }
  25962. return this;
  25963. };
  25964. // used by animation engine
  25965. PathCursor.prototype.markAsDirty = function (propertyName) {
  25966. this.ensureLimits();
  25967. this.raiseOnChange();
  25968. return this;
  25969. };
  25970. PathCursor.prototype.raiseOnChange = function () {
  25971. var _this = this;
  25972. this._onchange.forEach(function (f) { return f(_this); });
  25973. return this;
  25974. };
  25975. PathCursor.prototype.onchange = function (f) {
  25976. this._onchange.push(f);
  25977. return this;
  25978. };
  25979. return PathCursor;
  25980. })();
  25981. BABYLON.PathCursor = PathCursor;
  25982. var Animation = (function () {
  25983. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25984. this.name = name;
  25985. this.targetProperty = targetProperty;
  25986. this.framePerSecond = framePerSecond;
  25987. this.dataType = dataType;
  25988. this.loopMode = loopMode;
  25989. this.enableBlending = enableBlending;
  25990. this._offsetsCache = {};
  25991. this._highLimitsCache = {};
  25992. this._stopped = false;
  25993. this._blendingFactor = 0;
  25994. // The set of event that will be linked to this animation
  25995. this._events = new Array();
  25996. this.allowMatricesInterpolation = false;
  25997. this.blendingSpeed = 0.01;
  25998. this._ranges = {};
  25999. this.targetPropertyPath = targetProperty.split(".");
  26000. this.dataType = dataType;
  26001. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  26002. }
  26003. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  26004. var dataType = undefined;
  26005. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  26006. dataType = Animation.ANIMATIONTYPE_FLOAT;
  26007. }
  26008. else if (from instanceof BABYLON.Quaternion) {
  26009. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  26010. }
  26011. else if (from instanceof BABYLON.Vector3) {
  26012. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  26013. }
  26014. else if (from instanceof BABYLON.Vector2) {
  26015. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  26016. }
  26017. else if (from instanceof BABYLON.Color3) {
  26018. dataType = Animation.ANIMATIONTYPE_COLOR3;
  26019. }
  26020. else if (from instanceof BABYLON.Size) {
  26021. dataType = Animation.ANIMATIONTYPE_SIZE;
  26022. }
  26023. if (dataType == undefined) {
  26024. return null;
  26025. }
  26026. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  26027. var keys = [];
  26028. keys.push({ frame: 0, value: from });
  26029. keys.push({ frame: totalFrame, value: to });
  26030. animation.setKeys(keys);
  26031. if (easingFunction !== undefined) {
  26032. animation.setEasingFunction(easingFunction);
  26033. }
  26034. return animation;
  26035. };
  26036. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26037. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26038. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26039. };
  26040. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26041. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26042. node.animations.push(animation);
  26043. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26044. };
  26045. // Methods
  26046. /**
  26047. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26048. */
  26049. Animation.prototype.toString = function (fullDetails) {
  26050. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  26051. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  26052. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  26053. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26054. if (fullDetails) {
  26055. ret += ", Ranges: {";
  26056. var first = true;
  26057. for (var name in this._ranges) {
  26058. if (first) {
  26059. ret += ", ";
  26060. first = false;
  26061. }
  26062. ret += name;
  26063. }
  26064. ret += "}";
  26065. }
  26066. return ret;
  26067. };
  26068. /**
  26069. * Add an event to this animation.
  26070. */
  26071. Animation.prototype.addEvent = function (event) {
  26072. this._events.push(event);
  26073. };
  26074. /**
  26075. * Remove all events found at the given frame
  26076. * @param frame
  26077. */
  26078. Animation.prototype.removeEvents = function (frame) {
  26079. for (var index = 0; index < this._events.length; index++) {
  26080. if (this._events[index].frame === frame) {
  26081. this._events.splice(index, 1);
  26082. index--;
  26083. }
  26084. }
  26085. };
  26086. Animation.prototype.createRange = function (name, from, to) {
  26087. // check name not already in use; could happen for bones after serialized
  26088. if (!this._ranges[name]) {
  26089. this._ranges[name] = new AnimationRange(name, from, to);
  26090. }
  26091. };
  26092. Animation.prototype.deleteRange = function (name, deleteFrames) {
  26093. if (deleteFrames === void 0) { deleteFrames = true; }
  26094. if (this._ranges[name]) {
  26095. if (deleteFrames) {
  26096. var from = this._ranges[name].from;
  26097. var to = this._ranges[name].to;
  26098. // this loop MUST go high to low for multiple splices to work
  26099. for (var key = this._keys.length - 1; key >= 0; key--) {
  26100. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  26101. this._keys.splice(key, 1);
  26102. }
  26103. }
  26104. }
  26105. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26106. }
  26107. };
  26108. Animation.prototype.getRange = function (name) {
  26109. return this._ranges[name];
  26110. };
  26111. Animation.prototype.reset = function () {
  26112. this._offsetsCache = {};
  26113. this._highLimitsCache = {};
  26114. this.currentFrame = 0;
  26115. this._blendingFactor = 0;
  26116. this._originalBlendValue = null;
  26117. };
  26118. Animation.prototype.isStopped = function () {
  26119. return this._stopped;
  26120. };
  26121. Animation.prototype.getKeys = function () {
  26122. return this._keys;
  26123. };
  26124. Animation.prototype.getHighestFrame = function () {
  26125. var ret = 0;
  26126. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  26127. if (ret < this._keys[key].frame) {
  26128. ret = this._keys[key].frame;
  26129. }
  26130. }
  26131. return ret;
  26132. };
  26133. Animation.prototype.getEasingFunction = function () {
  26134. return this._easingFunction;
  26135. };
  26136. Animation.prototype.setEasingFunction = function (easingFunction) {
  26137. this._easingFunction = easingFunction;
  26138. };
  26139. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  26140. return startValue + (endValue - startValue) * gradient;
  26141. };
  26142. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  26143. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  26144. };
  26145. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  26146. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  26147. };
  26148. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  26149. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  26150. };
  26151. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  26152. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  26153. };
  26154. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  26155. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  26156. };
  26157. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  26158. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  26159. };
  26160. Animation.prototype.clone = function () {
  26161. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  26162. if (this._keys) {
  26163. clone.setKeys(this._keys);
  26164. }
  26165. if (this._ranges) {
  26166. clone._ranges = {};
  26167. for (var name in this._ranges) {
  26168. clone._ranges[name] = this._ranges[name].clone();
  26169. }
  26170. }
  26171. return clone;
  26172. };
  26173. Animation.prototype.setKeys = function (values) {
  26174. this._keys = values.slice(0);
  26175. this._offsetsCache = {};
  26176. this._highLimitsCache = {};
  26177. };
  26178. Animation.prototype._getKeyValue = function (value) {
  26179. if (typeof value === "function") {
  26180. return value();
  26181. }
  26182. return value;
  26183. };
  26184. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  26185. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  26186. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  26187. }
  26188. this.currentFrame = currentFrame;
  26189. // Try to get a hash to find the right key
  26190. 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));
  26191. if (this._keys[startKey].frame >= currentFrame) {
  26192. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  26193. startKey--;
  26194. }
  26195. }
  26196. for (var key = startKey; key < this._keys.length; key++) {
  26197. if (this._keys[key + 1].frame >= currentFrame) {
  26198. var startValue = this._getKeyValue(this._keys[key].value);
  26199. var endValue = this._getKeyValue(this._keys[key + 1].value);
  26200. // gradient : percent of currentFrame between the frame inf and the frame sup
  26201. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  26202. // check for easingFunction and correction of gradient
  26203. if (this._easingFunction != null) {
  26204. gradient = this._easingFunction.ease(gradient);
  26205. }
  26206. switch (this.dataType) {
  26207. // Float
  26208. case Animation.ANIMATIONTYPE_FLOAT:
  26209. switch (loopMode) {
  26210. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26211. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26212. return this.floatInterpolateFunction(startValue, endValue, gradient);
  26213. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26214. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  26215. }
  26216. break;
  26217. // Quaternion
  26218. case Animation.ANIMATIONTYPE_QUATERNION:
  26219. var quaternion = null;
  26220. switch (loopMode) {
  26221. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26222. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26223. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  26224. break;
  26225. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26226. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26227. break;
  26228. }
  26229. return quaternion;
  26230. // Vector3
  26231. case Animation.ANIMATIONTYPE_VECTOR3:
  26232. switch (loopMode) {
  26233. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26234. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26235. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  26236. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26237. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26238. }
  26239. // Vector2
  26240. case Animation.ANIMATIONTYPE_VECTOR2:
  26241. switch (loopMode) {
  26242. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26243. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26244. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  26245. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26246. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26247. }
  26248. // Size
  26249. case Animation.ANIMATIONTYPE_SIZE:
  26250. switch (loopMode) {
  26251. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26252. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26253. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  26254. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26255. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26256. }
  26257. // Color3
  26258. case Animation.ANIMATIONTYPE_COLOR3:
  26259. switch (loopMode) {
  26260. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26261. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26262. return this.color3InterpolateFunction(startValue, endValue, gradient);
  26263. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26264. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26265. }
  26266. // Matrix
  26267. case Animation.ANIMATIONTYPE_MATRIX:
  26268. switch (loopMode) {
  26269. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26270. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26271. if (this.allowMatricesInterpolation) {
  26272. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  26273. }
  26274. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26275. return startValue;
  26276. }
  26277. default:
  26278. break;
  26279. }
  26280. break;
  26281. }
  26282. }
  26283. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  26284. };
  26285. Animation.prototype.setValue = function (currentValue, blend) {
  26286. if (blend === void 0) { blend = false; }
  26287. // Set value
  26288. var path;
  26289. var destination;
  26290. if (this.targetPropertyPath.length > 1) {
  26291. var property = this._target[this.targetPropertyPath[0]];
  26292. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  26293. property = property[this.targetPropertyPath[index]];
  26294. }
  26295. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  26296. destination = property;
  26297. }
  26298. else {
  26299. path = this.targetPropertyPath[0];
  26300. destination = this._target;
  26301. }
  26302. // Blending
  26303. if (this.enableBlending && this._blendingFactor <= 1.0) {
  26304. if (!this._originalBlendValue) {
  26305. if (destination[path].clone) {
  26306. this._originalBlendValue = destination[path].clone();
  26307. }
  26308. else {
  26309. this._originalBlendValue = destination[path];
  26310. }
  26311. }
  26312. if (this._originalBlendValue.prototype) {
  26313. if (this._originalBlendValue.prototype.Lerp) {
  26314. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  26315. }
  26316. else {
  26317. destination[path] = currentValue;
  26318. }
  26319. }
  26320. else if (this._originalBlendValue.m) {
  26321. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  26322. }
  26323. else {
  26324. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  26325. }
  26326. this._blendingFactor += this.blendingSpeed;
  26327. }
  26328. else {
  26329. destination[path] = currentValue;
  26330. }
  26331. if (this._target.markAsDirty) {
  26332. this._target.markAsDirty(this.targetProperty);
  26333. }
  26334. };
  26335. Animation.prototype.goToFrame = function (frame) {
  26336. if (frame < this._keys[0].frame) {
  26337. frame = this._keys[0].frame;
  26338. }
  26339. else if (frame > this._keys[this._keys.length - 1].frame) {
  26340. frame = this._keys[this._keys.length - 1].frame;
  26341. }
  26342. var currentValue = this._interpolate(frame, 0, this.loopMode);
  26343. this.setValue(currentValue);
  26344. };
  26345. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  26346. if (blend === void 0) { blend = false; }
  26347. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  26348. this._stopped = true;
  26349. return false;
  26350. }
  26351. var returnValue = true;
  26352. // Adding a start key at frame 0 if missing
  26353. if (this._keys[0].frame !== 0) {
  26354. var newKey = { frame: 0, value: this._keys[0].value };
  26355. this._keys.splice(0, 0, newKey);
  26356. }
  26357. // Check limits
  26358. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  26359. from = this._keys[0].frame;
  26360. }
  26361. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  26362. to = this._keys[this._keys.length - 1].frame;
  26363. }
  26364. // Compute ratio
  26365. var range = to - from;
  26366. var offsetValue;
  26367. // ratio represents the frame delta between from and to
  26368. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  26369. var highLimitValue = 0;
  26370. if (ratio > range && !loop) {
  26371. returnValue = false;
  26372. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  26373. }
  26374. else {
  26375. // Get max value if required
  26376. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  26377. var keyOffset = to.toString() + from.toString();
  26378. if (!this._offsetsCache[keyOffset]) {
  26379. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26380. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26381. switch (this.dataType) {
  26382. // Float
  26383. case Animation.ANIMATIONTYPE_FLOAT:
  26384. this._offsetsCache[keyOffset] = toValue - fromValue;
  26385. break;
  26386. // Quaternion
  26387. case Animation.ANIMATIONTYPE_QUATERNION:
  26388. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26389. break;
  26390. // Vector3
  26391. case Animation.ANIMATIONTYPE_VECTOR3:
  26392. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26393. // Vector2
  26394. case Animation.ANIMATIONTYPE_VECTOR2:
  26395. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26396. // Size
  26397. case Animation.ANIMATIONTYPE_SIZE:
  26398. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26399. // Color3
  26400. case Animation.ANIMATIONTYPE_COLOR3:
  26401. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26402. default:
  26403. break;
  26404. }
  26405. this._highLimitsCache[keyOffset] = toValue;
  26406. }
  26407. highLimitValue = this._highLimitsCache[keyOffset];
  26408. offsetValue = this._offsetsCache[keyOffset];
  26409. }
  26410. }
  26411. if (offsetValue === undefined) {
  26412. switch (this.dataType) {
  26413. // Float
  26414. case Animation.ANIMATIONTYPE_FLOAT:
  26415. offsetValue = 0;
  26416. break;
  26417. // Quaternion
  26418. case Animation.ANIMATIONTYPE_QUATERNION:
  26419. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  26420. break;
  26421. // Vector3
  26422. case Animation.ANIMATIONTYPE_VECTOR3:
  26423. offsetValue = BABYLON.Vector3.Zero();
  26424. break;
  26425. // Vector2
  26426. case Animation.ANIMATIONTYPE_VECTOR2:
  26427. offsetValue = BABYLON.Vector2.Zero();
  26428. break;
  26429. // Size
  26430. case Animation.ANIMATIONTYPE_SIZE:
  26431. offsetValue = BABYLON.Size.Zero();
  26432. break;
  26433. // Color3
  26434. case Animation.ANIMATIONTYPE_COLOR3:
  26435. offsetValue = BABYLON.Color3.Black();
  26436. }
  26437. }
  26438. // Compute value
  26439. var repeatCount = (ratio / range) >> 0;
  26440. var currentFrame = returnValue ? from + ratio % range : to;
  26441. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  26442. // Set value
  26443. this.setValue(currentValue);
  26444. // Check events
  26445. for (var index = 0; index < this._events.length; index++) {
  26446. if (currentFrame >= this._events[index].frame) {
  26447. var event = this._events[index];
  26448. if (!event.isDone) {
  26449. // If event should be done only once, remove it.
  26450. if (event.onlyOnce) {
  26451. this._events.splice(index, 1);
  26452. index--;
  26453. }
  26454. event.isDone = true;
  26455. event.action();
  26456. } // Don't do anything if the event has already be done.
  26457. }
  26458. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  26459. // reset event, the animation is looping
  26460. this._events[index].isDone = false;
  26461. }
  26462. }
  26463. if (!returnValue) {
  26464. this._stopped = true;
  26465. }
  26466. return returnValue;
  26467. };
  26468. Animation.prototype.serialize = function () {
  26469. var serializationObject = {};
  26470. serializationObject.name = this.name;
  26471. serializationObject.property = this.targetProperty;
  26472. serializationObject.framePerSecond = this.framePerSecond;
  26473. serializationObject.dataType = this.dataType;
  26474. serializationObject.loopBehavior = this.loopMode;
  26475. var dataType = this.dataType;
  26476. serializationObject.keys = [];
  26477. var keys = this.getKeys();
  26478. for (var index = 0; index < keys.length; index++) {
  26479. var animationKey = keys[index];
  26480. var key = {};
  26481. key.frame = animationKey.frame;
  26482. switch (dataType) {
  26483. case Animation.ANIMATIONTYPE_FLOAT:
  26484. key.values = [animationKey.value];
  26485. break;
  26486. case Animation.ANIMATIONTYPE_QUATERNION:
  26487. case Animation.ANIMATIONTYPE_MATRIX:
  26488. case Animation.ANIMATIONTYPE_VECTOR3:
  26489. case Animation.ANIMATIONTYPE_COLOR3:
  26490. key.values = animationKey.value.asArray();
  26491. break;
  26492. }
  26493. serializationObject.keys.push(key);
  26494. }
  26495. serializationObject.ranges = [];
  26496. for (var name in this._ranges) {
  26497. var range = {};
  26498. range.name = name;
  26499. range.from = this._ranges[name].from;
  26500. range.to = this._ranges[name].to;
  26501. serializationObject.ranges.push(range);
  26502. }
  26503. return serializationObject;
  26504. };
  26505. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  26506. get: function () {
  26507. return Animation._ANIMATIONTYPE_FLOAT;
  26508. },
  26509. enumerable: true,
  26510. configurable: true
  26511. });
  26512. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  26513. get: function () {
  26514. return Animation._ANIMATIONTYPE_VECTOR3;
  26515. },
  26516. enumerable: true,
  26517. configurable: true
  26518. });
  26519. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  26520. get: function () {
  26521. return Animation._ANIMATIONTYPE_VECTOR2;
  26522. },
  26523. enumerable: true,
  26524. configurable: true
  26525. });
  26526. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  26527. get: function () {
  26528. return Animation._ANIMATIONTYPE_SIZE;
  26529. },
  26530. enumerable: true,
  26531. configurable: true
  26532. });
  26533. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  26534. get: function () {
  26535. return Animation._ANIMATIONTYPE_QUATERNION;
  26536. },
  26537. enumerable: true,
  26538. configurable: true
  26539. });
  26540. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  26541. get: function () {
  26542. return Animation._ANIMATIONTYPE_MATRIX;
  26543. },
  26544. enumerable: true,
  26545. configurable: true
  26546. });
  26547. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  26548. get: function () {
  26549. return Animation._ANIMATIONTYPE_COLOR3;
  26550. },
  26551. enumerable: true,
  26552. configurable: true
  26553. });
  26554. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  26555. get: function () {
  26556. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  26557. },
  26558. enumerable: true,
  26559. configurable: true
  26560. });
  26561. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  26562. get: function () {
  26563. return Animation._ANIMATIONLOOPMODE_CYCLE;
  26564. },
  26565. enumerable: true,
  26566. configurable: true
  26567. });
  26568. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  26569. get: function () {
  26570. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  26571. },
  26572. enumerable: true,
  26573. configurable: true
  26574. });
  26575. Animation.Parse = function (parsedAnimation) {
  26576. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  26577. var dataType = parsedAnimation.dataType;
  26578. var keys = [];
  26579. var data;
  26580. var index;
  26581. for (index = 0; index < parsedAnimation.keys.length; index++) {
  26582. var key = parsedAnimation.keys[index];
  26583. switch (dataType) {
  26584. case Animation.ANIMATIONTYPE_FLOAT:
  26585. data = key.values[0];
  26586. break;
  26587. case Animation.ANIMATIONTYPE_QUATERNION:
  26588. data = BABYLON.Quaternion.FromArray(key.values);
  26589. break;
  26590. case Animation.ANIMATIONTYPE_MATRIX:
  26591. data = BABYLON.Matrix.FromArray(key.values);
  26592. break;
  26593. case Animation.ANIMATIONTYPE_COLOR3:
  26594. data = BABYLON.Color3.FromArray(key.values);
  26595. break;
  26596. case Animation.ANIMATIONTYPE_VECTOR3:
  26597. default:
  26598. data = BABYLON.Vector3.FromArray(key.values);
  26599. break;
  26600. }
  26601. keys.push({
  26602. frame: key.frame,
  26603. value: data
  26604. });
  26605. }
  26606. animation.setKeys(keys);
  26607. if (parsedAnimation.ranges) {
  26608. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  26609. data = parsedAnimation.ranges[index];
  26610. animation.createRange(data.name, data.from, data.to);
  26611. }
  26612. }
  26613. return animation;
  26614. };
  26615. Animation.AppendSerializedAnimations = function (source, destination) {
  26616. if (source.animations) {
  26617. destination.animations = [];
  26618. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  26619. var animation = source.animations[animationIndex];
  26620. destination.animations.push(animation.serialize());
  26621. }
  26622. }
  26623. };
  26624. // Statics
  26625. Animation._ANIMATIONTYPE_FLOAT = 0;
  26626. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  26627. Animation._ANIMATIONTYPE_QUATERNION = 2;
  26628. Animation._ANIMATIONTYPE_MATRIX = 3;
  26629. Animation._ANIMATIONTYPE_COLOR3 = 4;
  26630. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  26631. Animation._ANIMATIONTYPE_SIZE = 6;
  26632. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  26633. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  26634. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  26635. return Animation;
  26636. })();
  26637. BABYLON.Animation = Animation;
  26638. })(BABYLON || (BABYLON = {}));
  26639. var BABYLON;
  26640. (function (BABYLON) {
  26641. var Animatable = (function () {
  26642. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  26643. if (fromFrame === void 0) { fromFrame = 0; }
  26644. if (toFrame === void 0) { toFrame = 100; }
  26645. if (loopAnimation === void 0) { loopAnimation = false; }
  26646. if (speedRatio === void 0) { speedRatio = 1.0; }
  26647. this.target = target;
  26648. this.fromFrame = fromFrame;
  26649. this.toFrame = toFrame;
  26650. this.loopAnimation = loopAnimation;
  26651. this.speedRatio = speedRatio;
  26652. this.onAnimationEnd = onAnimationEnd;
  26653. this._animations = new Array();
  26654. this._paused = false;
  26655. this.animationStarted = false;
  26656. if (animations) {
  26657. this.appendAnimations(target, animations);
  26658. }
  26659. this._scene = scene;
  26660. scene._activeAnimatables.push(this);
  26661. }
  26662. // Methods
  26663. Animatable.prototype.getAnimations = function () {
  26664. return this._animations;
  26665. };
  26666. Animatable.prototype.appendAnimations = function (target, animations) {
  26667. for (var index = 0; index < animations.length; index++) {
  26668. var animation = animations[index];
  26669. animation._target = target;
  26670. this._animations.push(animation);
  26671. }
  26672. };
  26673. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  26674. var animations = this._animations;
  26675. for (var index = 0; index < animations.length; index++) {
  26676. if (animations[index].targetProperty === property) {
  26677. return animations[index];
  26678. }
  26679. }
  26680. return null;
  26681. };
  26682. Animatable.prototype.reset = function () {
  26683. var animations = this._animations;
  26684. for (var index = 0; index < animations.length; index++) {
  26685. animations[index].reset();
  26686. }
  26687. this._localDelayOffset = null;
  26688. this._pausedDelay = null;
  26689. };
  26690. Animatable.prototype.enableBlending = function (blendingSpeed) {
  26691. var animations = this._animations;
  26692. for (var index = 0; index < animations.length; index++) {
  26693. animations[index].enableBlending = true;
  26694. animations[index].blendingSpeed = blendingSpeed;
  26695. }
  26696. };
  26697. Animatable.prototype.disableBlending = function () {
  26698. var animations = this._animations;
  26699. for (var index = 0; index < animations.length; index++) {
  26700. animations[index].enableBlending = false;
  26701. }
  26702. };
  26703. Animatable.prototype.goToFrame = function (frame) {
  26704. var animations = this._animations;
  26705. for (var index = 0; index < animations.length; index++) {
  26706. animations[index].goToFrame(frame);
  26707. }
  26708. };
  26709. Animatable.prototype.pause = function () {
  26710. if (this._paused) {
  26711. return;
  26712. }
  26713. this._paused = true;
  26714. };
  26715. Animatable.prototype.restart = function () {
  26716. this._paused = false;
  26717. };
  26718. Animatable.prototype.stop = function () {
  26719. var index = this._scene._activeAnimatables.indexOf(this);
  26720. if (index > -1) {
  26721. this._scene._activeAnimatables.splice(index, 1);
  26722. var animations = this._animations;
  26723. for (var index = 0; index < animations.length; index++) {
  26724. animations[index].reset();
  26725. }
  26726. if (this.onAnimationEnd) {
  26727. this.onAnimationEnd();
  26728. }
  26729. }
  26730. };
  26731. Animatable.prototype._animate = function (delay) {
  26732. if (this._paused) {
  26733. this.animationStarted = false;
  26734. if (!this._pausedDelay) {
  26735. this._pausedDelay = delay;
  26736. }
  26737. return true;
  26738. }
  26739. if (!this._localDelayOffset) {
  26740. this._localDelayOffset = delay;
  26741. }
  26742. else if (this._pausedDelay) {
  26743. this._localDelayOffset += delay - this._pausedDelay;
  26744. this._pausedDelay = null;
  26745. }
  26746. // Animating
  26747. var running = false;
  26748. var animations = this._animations;
  26749. var index;
  26750. for (index = 0; index < animations.length; index++) {
  26751. var animation = animations[index];
  26752. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  26753. running = running || isRunning;
  26754. }
  26755. this.animationStarted = running;
  26756. if (!running) {
  26757. // Remove from active animatables
  26758. index = this._scene._activeAnimatables.indexOf(this);
  26759. this._scene._activeAnimatables.splice(index, 1);
  26760. }
  26761. if (!running && this.onAnimationEnd) {
  26762. this.onAnimationEnd();
  26763. this.onAnimationEnd = null;
  26764. }
  26765. return running;
  26766. };
  26767. return Animatable;
  26768. })();
  26769. BABYLON.Animatable = Animatable;
  26770. })(BABYLON || (BABYLON = {}));
  26771. var BABYLON;
  26772. (function (BABYLON) {
  26773. var EasingFunction = (function () {
  26774. function EasingFunction() {
  26775. // Properties
  26776. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  26777. }
  26778. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  26779. get: function () {
  26780. return EasingFunction._EASINGMODE_EASEIN;
  26781. },
  26782. enumerable: true,
  26783. configurable: true
  26784. });
  26785. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  26786. get: function () {
  26787. return EasingFunction._EASINGMODE_EASEOUT;
  26788. },
  26789. enumerable: true,
  26790. configurable: true
  26791. });
  26792. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  26793. get: function () {
  26794. return EasingFunction._EASINGMODE_EASEINOUT;
  26795. },
  26796. enumerable: true,
  26797. configurable: true
  26798. });
  26799. EasingFunction.prototype.setEasingMode = function (easingMode) {
  26800. var n = Math.min(Math.max(easingMode, 0), 2);
  26801. this._easingMode = n;
  26802. };
  26803. EasingFunction.prototype.getEasingMode = function () {
  26804. return this._easingMode;
  26805. };
  26806. EasingFunction.prototype.easeInCore = function (gradient) {
  26807. throw new Error('You must implement this method');
  26808. };
  26809. EasingFunction.prototype.ease = function (gradient) {
  26810. switch (this._easingMode) {
  26811. case EasingFunction.EASINGMODE_EASEIN:
  26812. return this.easeInCore(gradient);
  26813. case EasingFunction.EASINGMODE_EASEOUT:
  26814. return (1 - this.easeInCore(1 - gradient));
  26815. }
  26816. if (gradient >= 0.5) {
  26817. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  26818. }
  26819. return (this.easeInCore(gradient * 2) * 0.5);
  26820. };
  26821. //Statics
  26822. EasingFunction._EASINGMODE_EASEIN = 0;
  26823. EasingFunction._EASINGMODE_EASEOUT = 1;
  26824. EasingFunction._EASINGMODE_EASEINOUT = 2;
  26825. return EasingFunction;
  26826. })();
  26827. BABYLON.EasingFunction = EasingFunction;
  26828. var CircleEase = (function (_super) {
  26829. __extends(CircleEase, _super);
  26830. function CircleEase() {
  26831. _super.apply(this, arguments);
  26832. }
  26833. CircleEase.prototype.easeInCore = function (gradient) {
  26834. gradient = Math.max(0, Math.min(1, gradient));
  26835. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  26836. };
  26837. return CircleEase;
  26838. })(EasingFunction);
  26839. BABYLON.CircleEase = CircleEase;
  26840. var BackEase = (function (_super) {
  26841. __extends(BackEase, _super);
  26842. function BackEase(amplitude) {
  26843. if (amplitude === void 0) { amplitude = 1; }
  26844. _super.call(this);
  26845. this.amplitude = amplitude;
  26846. }
  26847. BackEase.prototype.easeInCore = function (gradient) {
  26848. var num = Math.max(0, this.amplitude);
  26849. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  26850. };
  26851. return BackEase;
  26852. })(EasingFunction);
  26853. BABYLON.BackEase = BackEase;
  26854. var BounceEase = (function (_super) {
  26855. __extends(BounceEase, _super);
  26856. function BounceEase(bounces, bounciness) {
  26857. if (bounces === void 0) { bounces = 3; }
  26858. if (bounciness === void 0) { bounciness = 2; }
  26859. _super.call(this);
  26860. this.bounces = bounces;
  26861. this.bounciness = bounciness;
  26862. }
  26863. BounceEase.prototype.easeInCore = function (gradient) {
  26864. var y = Math.max(0.0, this.bounces);
  26865. var bounciness = this.bounciness;
  26866. if (bounciness <= 1.0) {
  26867. bounciness = 1.001;
  26868. }
  26869. var num9 = Math.pow(bounciness, y);
  26870. var num5 = 1.0 - bounciness;
  26871. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  26872. var num15 = gradient * num4;
  26873. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  26874. var num3 = Math.floor(num65);
  26875. var num13 = num3 + 1.0;
  26876. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  26877. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  26878. var num7 = (num8 + num12) * 0.5;
  26879. var num6 = gradient - num7;
  26880. var num2 = num7 - num8;
  26881. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  26882. };
  26883. return BounceEase;
  26884. })(EasingFunction);
  26885. BABYLON.BounceEase = BounceEase;
  26886. var CubicEase = (function (_super) {
  26887. __extends(CubicEase, _super);
  26888. function CubicEase() {
  26889. _super.apply(this, arguments);
  26890. }
  26891. CubicEase.prototype.easeInCore = function (gradient) {
  26892. return (gradient * gradient * gradient);
  26893. };
  26894. return CubicEase;
  26895. })(EasingFunction);
  26896. BABYLON.CubicEase = CubicEase;
  26897. var ElasticEase = (function (_super) {
  26898. __extends(ElasticEase, _super);
  26899. function ElasticEase(oscillations, springiness) {
  26900. if (oscillations === void 0) { oscillations = 3; }
  26901. if (springiness === void 0) { springiness = 3; }
  26902. _super.call(this);
  26903. this.oscillations = oscillations;
  26904. this.springiness = springiness;
  26905. }
  26906. ElasticEase.prototype.easeInCore = function (gradient) {
  26907. var num2;
  26908. var num3 = Math.max(0.0, this.oscillations);
  26909. var num = Math.max(0.0, this.springiness);
  26910. if (num == 0) {
  26911. num2 = gradient;
  26912. }
  26913. else {
  26914. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  26915. }
  26916. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  26917. };
  26918. return ElasticEase;
  26919. })(EasingFunction);
  26920. BABYLON.ElasticEase = ElasticEase;
  26921. var ExponentialEase = (function (_super) {
  26922. __extends(ExponentialEase, _super);
  26923. function ExponentialEase(exponent) {
  26924. if (exponent === void 0) { exponent = 2; }
  26925. _super.call(this);
  26926. this.exponent = exponent;
  26927. }
  26928. ExponentialEase.prototype.easeInCore = function (gradient) {
  26929. if (this.exponent <= 0) {
  26930. return gradient;
  26931. }
  26932. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  26933. };
  26934. return ExponentialEase;
  26935. })(EasingFunction);
  26936. BABYLON.ExponentialEase = ExponentialEase;
  26937. var PowerEase = (function (_super) {
  26938. __extends(PowerEase, _super);
  26939. function PowerEase(power) {
  26940. if (power === void 0) { power = 2; }
  26941. _super.call(this);
  26942. this.power = power;
  26943. }
  26944. PowerEase.prototype.easeInCore = function (gradient) {
  26945. var y = Math.max(0.0, this.power);
  26946. return Math.pow(gradient, y);
  26947. };
  26948. return PowerEase;
  26949. })(EasingFunction);
  26950. BABYLON.PowerEase = PowerEase;
  26951. var QuadraticEase = (function (_super) {
  26952. __extends(QuadraticEase, _super);
  26953. function QuadraticEase() {
  26954. _super.apply(this, arguments);
  26955. }
  26956. QuadraticEase.prototype.easeInCore = function (gradient) {
  26957. return (gradient * gradient);
  26958. };
  26959. return QuadraticEase;
  26960. })(EasingFunction);
  26961. BABYLON.QuadraticEase = QuadraticEase;
  26962. var QuarticEase = (function (_super) {
  26963. __extends(QuarticEase, _super);
  26964. function QuarticEase() {
  26965. _super.apply(this, arguments);
  26966. }
  26967. QuarticEase.prototype.easeInCore = function (gradient) {
  26968. return (gradient * gradient * gradient * gradient);
  26969. };
  26970. return QuarticEase;
  26971. })(EasingFunction);
  26972. BABYLON.QuarticEase = QuarticEase;
  26973. var QuinticEase = (function (_super) {
  26974. __extends(QuinticEase, _super);
  26975. function QuinticEase() {
  26976. _super.apply(this, arguments);
  26977. }
  26978. QuinticEase.prototype.easeInCore = function (gradient) {
  26979. return (gradient * gradient * gradient * gradient * gradient);
  26980. };
  26981. return QuinticEase;
  26982. })(EasingFunction);
  26983. BABYLON.QuinticEase = QuinticEase;
  26984. var SineEase = (function (_super) {
  26985. __extends(SineEase, _super);
  26986. function SineEase() {
  26987. _super.apply(this, arguments);
  26988. }
  26989. SineEase.prototype.easeInCore = function (gradient) {
  26990. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26991. };
  26992. return SineEase;
  26993. })(EasingFunction);
  26994. BABYLON.SineEase = SineEase;
  26995. var BezierCurveEase = (function (_super) {
  26996. __extends(BezierCurveEase, _super);
  26997. function BezierCurveEase(x1, y1, x2, y2) {
  26998. if (x1 === void 0) { x1 = 0; }
  26999. if (y1 === void 0) { y1 = 0; }
  27000. if (x2 === void 0) { x2 = 1; }
  27001. if (y2 === void 0) { y2 = 1; }
  27002. _super.call(this);
  27003. this.x1 = x1;
  27004. this.y1 = y1;
  27005. this.x2 = x2;
  27006. this.y2 = y2;
  27007. }
  27008. BezierCurveEase.prototype.easeInCore = function (gradient) {
  27009. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  27010. };
  27011. return BezierCurveEase;
  27012. })(EasingFunction);
  27013. BABYLON.BezierCurveEase = BezierCurveEase;
  27014. })(BABYLON || (BABYLON = {}));
  27015. var BABYLON;
  27016. (function (BABYLON) {
  27017. var Bone = (function (_super) {
  27018. __extends(Bone, _super);
  27019. function Bone(name, skeleton, parentBone, matrix, restPose) {
  27020. _super.call(this, name, skeleton.getScene());
  27021. this.name = name;
  27022. this.children = new Array();
  27023. this.animations = new Array();
  27024. this._worldTransform = new BABYLON.Matrix();
  27025. this._absoluteTransform = new BABYLON.Matrix();
  27026. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  27027. this._skeleton = skeleton;
  27028. this._matrix = matrix;
  27029. this._baseMatrix = matrix;
  27030. this._restPose = restPose ? restPose : matrix.clone();
  27031. skeleton.bones.push(this);
  27032. if (parentBone) {
  27033. this._parent = parentBone;
  27034. parentBone.children.push(this);
  27035. }
  27036. else {
  27037. this._parent = null;
  27038. }
  27039. this._updateDifferenceMatrix();
  27040. }
  27041. // Members
  27042. Bone.prototype.getParent = function () {
  27043. return this._parent;
  27044. };
  27045. Bone.prototype.getLocalMatrix = function () {
  27046. return this._matrix;
  27047. };
  27048. Bone.prototype.getBaseMatrix = function () {
  27049. return this._baseMatrix;
  27050. };
  27051. Bone.prototype.getRestPose = function () {
  27052. return this._restPose;
  27053. };
  27054. Bone.prototype.returnToRest = function () {
  27055. this.updateMatrix(this._restPose.clone());
  27056. };
  27057. Bone.prototype.getWorldMatrix = function () {
  27058. return this._worldTransform;
  27059. };
  27060. Bone.prototype.getInvertedAbsoluteTransform = function () {
  27061. return this._invertedAbsoluteTransform;
  27062. };
  27063. Bone.prototype.getAbsoluteTransform = function () {
  27064. return this._absoluteTransform;
  27065. };
  27066. // Methods
  27067. Bone.prototype.updateMatrix = function (matrix) {
  27068. this._baseMatrix = matrix.clone();
  27069. this._matrix = matrix.clone();
  27070. this._skeleton._markAsDirty();
  27071. this._updateDifferenceMatrix();
  27072. };
  27073. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  27074. if (!rootMatrix) {
  27075. rootMatrix = this._baseMatrix;
  27076. }
  27077. if (this._parent) {
  27078. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  27079. }
  27080. else {
  27081. this._absoluteTransform.copyFrom(rootMatrix);
  27082. }
  27083. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  27084. for (var index = 0; index < this.children.length; index++) {
  27085. this.children[index]._updateDifferenceMatrix();
  27086. }
  27087. };
  27088. Bone.prototype.markAsDirty = function () {
  27089. this._currentRenderId++;
  27090. this._skeleton._markAsDirty();
  27091. };
  27092. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  27093. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27094. // all animation may be coming from a library skeleton, so may need to create animation
  27095. if (this.animations.length === 0) {
  27096. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  27097. this.animations[0].setKeys([]);
  27098. }
  27099. // get animation info / verify there is such a range from the source bone
  27100. var sourceRange = source.animations[0].getRange(rangeName);
  27101. if (!sourceRange) {
  27102. return false;
  27103. }
  27104. var from = sourceRange.from;
  27105. var to = sourceRange.to;
  27106. var sourceKeys = source.animations[0].getKeys();
  27107. // rescaling prep
  27108. var sourceBoneLength = source.length;
  27109. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  27110. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  27111. var destKeys = this.animations[0].getKeys();
  27112. // loop vars declaration / initialization
  27113. var orig;
  27114. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  27115. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  27116. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  27117. var mat;
  27118. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  27119. orig = sourceKeys[key];
  27120. if (orig.frame >= from && orig.frame <= to) {
  27121. if (scalingReqd) {
  27122. orig.value.decompose(origScale, origRotation, origTranslation);
  27123. origTranslation.scaleInPlace(ratio);
  27124. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  27125. }
  27126. else {
  27127. mat = orig.value;
  27128. }
  27129. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  27130. }
  27131. }
  27132. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  27133. return true;
  27134. };
  27135. return Bone;
  27136. })(BABYLON.Node);
  27137. BABYLON.Bone = Bone;
  27138. })(BABYLON || (BABYLON = {}));
  27139. var BABYLON;
  27140. (function (BABYLON) {
  27141. var Skeleton = (function () {
  27142. function Skeleton(name, id, scene) {
  27143. this.name = name;
  27144. this.id = id;
  27145. this.bones = new Array();
  27146. this.needInitialSkinMatrix = false;
  27147. this._isDirty = true;
  27148. this._meshesWithPoseMatrix = new Array();
  27149. this._identity = BABYLON.Matrix.Identity();
  27150. this._ranges = {};
  27151. this.bones = [];
  27152. this._scene = scene;
  27153. scene.skeletons.push(this);
  27154. //make sure it will recalculate the matrix next time prepare is called.
  27155. this._isDirty = true;
  27156. }
  27157. // Members
  27158. Skeleton.prototype.getTransformMatrices = function (mesh) {
  27159. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  27160. return mesh._bonesTransformMatrices;
  27161. }
  27162. return this._transformMatrices;
  27163. };
  27164. Skeleton.prototype.getScene = function () {
  27165. return this._scene;
  27166. };
  27167. // Methods
  27168. /**
  27169. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27170. */
  27171. Skeleton.prototype.toString = function (fullDetails) {
  27172. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  27173. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27174. if (fullDetails) {
  27175. ret += ", Ranges: {";
  27176. var first = true;
  27177. for (var name_1 in this._ranges) {
  27178. if (first) {
  27179. ret += ", ";
  27180. first = false;
  27181. }
  27182. ret += name_1;
  27183. }
  27184. ret += "}";
  27185. }
  27186. return ret;
  27187. };
  27188. /**
  27189. * Get bone's index searching by name
  27190. * @param {string} name is bone's name to search for
  27191. * @return {number} Indice of the bone. Returns -1 if not found
  27192. */
  27193. Skeleton.prototype.getBoneIndexByName = function (name) {
  27194. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  27195. if (this.bones[boneIndex].name === name) {
  27196. return boneIndex;
  27197. }
  27198. }
  27199. return -1;
  27200. };
  27201. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  27202. // check name not already in use
  27203. if (!this._ranges[name]) {
  27204. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  27205. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27206. if (this.bones[i].animations[0]) {
  27207. this.bones[i].animations[0].createRange(name, from, to);
  27208. }
  27209. }
  27210. }
  27211. };
  27212. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  27213. if (deleteFrames === void 0) { deleteFrames = true; }
  27214. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27215. if (this.bones[i].animations[0]) {
  27216. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  27217. }
  27218. }
  27219. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27220. };
  27221. Skeleton.prototype.getAnimationRange = function (name) {
  27222. return this._ranges[name];
  27223. };
  27224. /**
  27225. * Returns as an Array, all AnimationRanges defined on this skeleton
  27226. */
  27227. Skeleton.prototype.getAnimationRanges = function () {
  27228. var animationRanges = [];
  27229. var name;
  27230. var i = 0;
  27231. for (name in this._ranges) {
  27232. animationRanges[i] = this._ranges[name];
  27233. i++;
  27234. }
  27235. return animationRanges;
  27236. };
  27237. /**
  27238. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  27239. */
  27240. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  27241. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27242. if (this._ranges[name] || !source.getAnimationRange(name)) {
  27243. return false;
  27244. }
  27245. var ret = true;
  27246. var frameOffset = this._getHighestAnimationFrame() + 1;
  27247. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  27248. var boneDict = {};
  27249. var sourceBones = source.bones;
  27250. var nBones;
  27251. var i;
  27252. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  27253. boneDict[sourceBones[i].name] = sourceBones[i];
  27254. }
  27255. if (this.bones.length !== sourceBones.length) {
  27256. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  27257. ret = false;
  27258. }
  27259. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  27260. var boneName = this.bones[i].name;
  27261. var sourceBone = boneDict[boneName];
  27262. if (sourceBone) {
  27263. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  27264. }
  27265. else {
  27266. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  27267. ret = false;
  27268. }
  27269. }
  27270. // do not call createAnimationRange(), since it also is done to bones, which was already done
  27271. var range = source.getAnimationRange(name);
  27272. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  27273. return ret;
  27274. };
  27275. Skeleton.prototype.returnToRest = function () {
  27276. for (var index = 0; index < this.bones.length; index++) {
  27277. this.bones[index].returnToRest();
  27278. }
  27279. };
  27280. Skeleton.prototype._getHighestAnimationFrame = function () {
  27281. var ret = 0;
  27282. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27283. if (this.bones[i].animations[0]) {
  27284. var highest = this.bones[i].animations[0].getHighestFrame();
  27285. if (ret < highest) {
  27286. ret = highest;
  27287. }
  27288. }
  27289. }
  27290. return ret;
  27291. };
  27292. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  27293. var range = this.getAnimationRange(name);
  27294. if (!range) {
  27295. return null;
  27296. }
  27297. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  27298. };
  27299. Skeleton.prototype._markAsDirty = function () {
  27300. this._isDirty = true;
  27301. };
  27302. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  27303. this._meshesWithPoseMatrix.push(mesh);
  27304. };
  27305. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  27306. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  27307. if (index > -1) {
  27308. this._meshesWithPoseMatrix.splice(index, 1);
  27309. }
  27310. };
  27311. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  27312. for (var index = 0; index < this.bones.length; index++) {
  27313. var bone = this.bones[index];
  27314. var parentBone = bone.getParent();
  27315. if (parentBone) {
  27316. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  27317. }
  27318. else {
  27319. if (initialSkinMatrix) {
  27320. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  27321. }
  27322. else {
  27323. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  27324. }
  27325. }
  27326. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  27327. }
  27328. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  27329. };
  27330. Skeleton.prototype.prepare = function () {
  27331. if (!this._isDirty) {
  27332. return;
  27333. }
  27334. if (this.needInitialSkinMatrix) {
  27335. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  27336. var mesh = this._meshesWithPoseMatrix[index];
  27337. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  27338. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27339. }
  27340. var poseMatrix = mesh.getPoseMatrix();
  27341. // Prepare bones
  27342. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  27343. var bone = this.bones[boneIndex];
  27344. if (!bone.getParent()) {
  27345. var matrix = bone.getBaseMatrix();
  27346. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  27347. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  27348. }
  27349. }
  27350. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  27351. }
  27352. }
  27353. else {
  27354. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  27355. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27356. }
  27357. this._computeTransformMatrices(this._transformMatrices, null);
  27358. }
  27359. this._isDirty = false;
  27360. this._scene._activeBones += this.bones.length;
  27361. };
  27362. Skeleton.prototype.getAnimatables = function () {
  27363. if (!this._animatables || this._animatables.length !== this.bones.length) {
  27364. this._animatables = [];
  27365. for (var index = 0; index < this.bones.length; index++) {
  27366. this._animatables.push(this.bones[index]);
  27367. }
  27368. }
  27369. return this._animatables;
  27370. };
  27371. Skeleton.prototype.clone = function (name, id) {
  27372. var result = new Skeleton(name, id || name, this._scene);
  27373. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27374. for (var index = 0; index < this.bones.length; index++) {
  27375. var source = this.bones[index];
  27376. var parentBone = null;
  27377. if (source.getParent()) {
  27378. var parentIndex = this.bones.indexOf(source.getParent());
  27379. parentBone = result.bones[parentIndex];
  27380. }
  27381. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  27382. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  27383. }
  27384. if (this._ranges) {
  27385. result._ranges = {};
  27386. for (var rangeName in this._ranges) {
  27387. result._ranges[rangeName] = this._ranges[rangeName].clone();
  27388. }
  27389. }
  27390. this._isDirty = true;
  27391. return result;
  27392. };
  27393. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  27394. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  27395. this.bones.forEach(function (bone) {
  27396. bone.animations.forEach(function (animation) {
  27397. animation.enableBlending = true;
  27398. animation.blendingSpeed = blendingSpeed;
  27399. });
  27400. });
  27401. };
  27402. Skeleton.prototype.dispose = function () {
  27403. this._meshesWithPoseMatrix = [];
  27404. // Animations
  27405. this.getScene().stopAnimation(this);
  27406. // Remove from scene
  27407. this.getScene().removeSkeleton(this);
  27408. };
  27409. Skeleton.prototype.serialize = function () {
  27410. var serializationObject = {};
  27411. serializationObject.name = this.name;
  27412. serializationObject.id = this.id;
  27413. serializationObject.bones = [];
  27414. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27415. for (var index = 0; index < this.bones.length; index++) {
  27416. var bone = this.bones[index];
  27417. var serializedBone = {
  27418. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  27419. name: bone.name,
  27420. matrix: bone.getLocalMatrix().toArray(),
  27421. rest: bone.getRestPose().toArray()
  27422. };
  27423. serializationObject.bones.push(serializedBone);
  27424. if (bone.length) {
  27425. serializedBone.length = bone.length;
  27426. }
  27427. if (bone.animations && bone.animations.length > 0) {
  27428. serializedBone.animation = bone.animations[0].serialize();
  27429. }
  27430. serializationObject.ranges = [];
  27431. for (var name in this._ranges) {
  27432. var range = {};
  27433. range.name = name;
  27434. range.from = this._ranges[name].from;
  27435. range.to = this._ranges[name].to;
  27436. serializationObject.ranges.push(range);
  27437. }
  27438. }
  27439. return serializationObject;
  27440. };
  27441. Skeleton.Parse = function (parsedSkeleton, scene) {
  27442. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  27443. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  27444. var index;
  27445. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  27446. var parsedBone = parsedSkeleton.bones[index];
  27447. var parentBone = null;
  27448. if (parsedBone.parentBoneIndex > -1) {
  27449. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  27450. }
  27451. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  27452. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  27453. if (parsedBone.length) {
  27454. bone.length = parsedBone.length;
  27455. }
  27456. if (parsedBone.animation) {
  27457. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  27458. }
  27459. }
  27460. // placed after bones, so createAnimationRange can cascade down
  27461. if (parsedSkeleton.ranges) {
  27462. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  27463. var data = parsedSkeleton.ranges[index];
  27464. skeleton.createAnimationRange(data.name, data.from, data.to);
  27465. }
  27466. }
  27467. return skeleton;
  27468. };
  27469. return Skeleton;
  27470. })();
  27471. BABYLON.Skeleton = Skeleton;
  27472. })(BABYLON || (BABYLON = {}));
  27473. var BABYLON;
  27474. (function (BABYLON) {
  27475. var PostProcess = (function () {
  27476. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  27477. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  27478. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27479. this.name = name;
  27480. this.width = -1;
  27481. this.height = -1;
  27482. /*
  27483. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  27484. Can only be used on a single postprocess or on the last one of a chain.
  27485. */
  27486. this.enablePixelPerfectMode = false;
  27487. this._reusable = false;
  27488. this._textures = new BABYLON.SmartArray(2);
  27489. this._currentRenderTextureInd = 0;
  27490. this._scaleRatio = new BABYLON.Vector2(1, 1);
  27491. // Events
  27492. /**
  27493. * An event triggered when the postprocess is activated.
  27494. * @type {BABYLON.Observable}
  27495. */
  27496. this.onActivateObservable = new BABYLON.Observable();
  27497. /**
  27498. * An event triggered when the postprocess changes its size.
  27499. * @type {BABYLON.Observable}
  27500. */
  27501. this.onSizeChangedObservable = new BABYLON.Observable();
  27502. /**
  27503. * An event triggered when the postprocess applies its effect.
  27504. * @type {BABYLON.Observable}
  27505. */
  27506. this.onApplyObservable = new BABYLON.Observable();
  27507. /**
  27508. * An event triggered before rendering the postprocess
  27509. * @type {BABYLON.Observable}
  27510. */
  27511. this.onBeforeRenderObservable = new BABYLON.Observable();
  27512. /**
  27513. * An event triggered after rendering the postprocess
  27514. * @type {BABYLON.Observable}
  27515. */
  27516. this.onAfterRenderObservable = new BABYLON.Observable();
  27517. if (camera != null) {
  27518. this._camera = camera;
  27519. this._scene = camera.getScene();
  27520. camera.attachPostProcess(this);
  27521. this._engine = this._scene.getEngine();
  27522. }
  27523. else {
  27524. this._engine = engine;
  27525. }
  27526. this._options = options;
  27527. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  27528. this._reusable = reusable || false;
  27529. this._textureType = textureType;
  27530. this._samplers = samplers || [];
  27531. this._samplers.push("textureSampler");
  27532. this._fragmentUrl = fragmentUrl;
  27533. this._parameters = parameters || [];
  27534. this._parameters.push("scale");
  27535. this.updateEffect(defines);
  27536. }
  27537. Object.defineProperty(PostProcess.prototype, "onActivate", {
  27538. set: function (callback) {
  27539. if (this._onActivateObserver) {
  27540. this.onActivateObservable.remove(this._onActivateObserver);
  27541. }
  27542. this._onActivateObserver = this.onActivateObservable.add(callback);
  27543. },
  27544. enumerable: true,
  27545. configurable: true
  27546. });
  27547. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  27548. set: function (callback) {
  27549. if (this._onSizeChangedObserver) {
  27550. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  27551. }
  27552. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  27553. },
  27554. enumerable: true,
  27555. configurable: true
  27556. });
  27557. Object.defineProperty(PostProcess.prototype, "onApply", {
  27558. set: function (callback) {
  27559. if (this._onApplyObserver) {
  27560. this.onApplyObservable.remove(this._onApplyObserver);
  27561. }
  27562. this._onApplyObserver = this.onApplyObservable.add(callback);
  27563. },
  27564. enumerable: true,
  27565. configurable: true
  27566. });
  27567. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  27568. set: function (callback) {
  27569. if (this._onBeforeRenderObserver) {
  27570. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27571. }
  27572. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27573. },
  27574. enumerable: true,
  27575. configurable: true
  27576. });
  27577. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  27578. set: function (callback) {
  27579. if (this._onAfterRenderObserver) {
  27580. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27581. }
  27582. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27583. },
  27584. enumerable: true,
  27585. configurable: true
  27586. });
  27587. PostProcess.prototype.updateEffect = function (defines) {
  27588. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  27589. };
  27590. PostProcess.prototype.isReusable = function () {
  27591. return this._reusable;
  27592. };
  27593. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  27594. PostProcess.prototype.markTextureDirty = function () {
  27595. this.width = -1;
  27596. };
  27597. PostProcess.prototype.activate = function (camera, sourceTexture) {
  27598. camera = camera || this._camera;
  27599. var scene = camera.getScene();
  27600. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  27601. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  27602. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  27603. var desiredWidth = this._options.width || requiredWidth;
  27604. var desiredHeight = this._options.height || requiredHeight;
  27605. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27606. if (!this._options.width) {
  27607. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  27608. }
  27609. if (!this._options.height) {
  27610. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  27611. }
  27612. }
  27613. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  27614. if (this._textures.length > 0) {
  27615. for (var i = 0; i < this._textures.length; i++) {
  27616. this._engine._releaseTexture(this._textures.data[i]);
  27617. }
  27618. this._textures.reset();
  27619. }
  27620. this.width = desiredWidth;
  27621. this.height = desiredHeight;
  27622. 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 }));
  27623. if (this._reusable) {
  27624. 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 }));
  27625. }
  27626. this.onSizeChangedObservable.notifyObservers(this);
  27627. }
  27628. if (this.enablePixelPerfectMode) {
  27629. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  27630. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  27631. }
  27632. else {
  27633. this._scaleRatio.copyFromFloats(1, 1);
  27634. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  27635. }
  27636. this.onActivateObservable.notifyObservers(camera);
  27637. // Clear
  27638. if (this.clearColor) {
  27639. this._engine.clear(this.clearColor, true, true);
  27640. }
  27641. else {
  27642. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  27643. }
  27644. if (this._reusable) {
  27645. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  27646. }
  27647. };
  27648. Object.defineProperty(PostProcess.prototype, "isSupported", {
  27649. get: function () {
  27650. return this._effect.isSupported;
  27651. },
  27652. enumerable: true,
  27653. configurable: true
  27654. });
  27655. PostProcess.prototype.apply = function () {
  27656. // Check
  27657. if (!this._effect.isReady())
  27658. return null;
  27659. // States
  27660. this._engine.enableEffect(this._effect);
  27661. this._engine.setState(false);
  27662. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27663. this._engine.setDepthBuffer(false);
  27664. this._engine.setDepthWrite(false);
  27665. // Texture
  27666. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  27667. // Parameters
  27668. this._effect.setVector2("scale", this._scaleRatio);
  27669. this.onApplyObservable.notifyObservers(this._effect);
  27670. return this._effect;
  27671. };
  27672. PostProcess.prototype.dispose = function (camera) {
  27673. camera = camera || this._camera;
  27674. if (this._textures.length > 0) {
  27675. for (var i = 0; i < this._textures.length; i++) {
  27676. this._engine._releaseTexture(this._textures.data[i]);
  27677. }
  27678. this._textures.reset();
  27679. }
  27680. if (!camera) {
  27681. return;
  27682. }
  27683. camera.detachPostProcess(this);
  27684. var index = camera._postProcesses.indexOf(this);
  27685. if (index === 0 && camera._postProcesses.length > 0) {
  27686. this._camera._postProcesses[0].markTextureDirty();
  27687. }
  27688. this.onActivateObservable.clear();
  27689. this.onAfterRenderObservable.clear();
  27690. this.onApplyObservable.clear();
  27691. this.onBeforeRenderObservable.clear();
  27692. this.onSizeChangedObservable.clear();
  27693. };
  27694. return PostProcess;
  27695. })();
  27696. BABYLON.PostProcess = PostProcess;
  27697. })(BABYLON || (BABYLON = {}));
  27698. var BABYLON;
  27699. (function (BABYLON) {
  27700. var PostProcessManager = (function () {
  27701. function PostProcessManager(scene) {
  27702. this._vertexDeclaration = [2];
  27703. this._vertexStrideSize = 2 * 4;
  27704. this._scene = scene;
  27705. }
  27706. PostProcessManager.prototype._prepareBuffers = function () {
  27707. if (this._vertexBuffer) {
  27708. return;
  27709. }
  27710. // VBO
  27711. var vertices = [];
  27712. vertices.push(1, 1);
  27713. vertices.push(-1, 1);
  27714. vertices.push(-1, -1);
  27715. vertices.push(1, -1);
  27716. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  27717. // Indices
  27718. var indices = [];
  27719. indices.push(0);
  27720. indices.push(1);
  27721. indices.push(2);
  27722. indices.push(0);
  27723. indices.push(2);
  27724. indices.push(3);
  27725. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27726. };
  27727. // Methods
  27728. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27729. var postProcesses = this._scene.activeCamera._postProcesses;
  27730. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27731. return false;
  27732. }
  27733. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27734. return true;
  27735. };
  27736. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  27737. var engine = this._scene.getEngine();
  27738. for (var index = 0; index < postProcesses.length; index++) {
  27739. if (index < postProcesses.length - 1) {
  27740. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27741. }
  27742. else {
  27743. if (targetTexture) {
  27744. engine.bindFramebuffer(targetTexture);
  27745. }
  27746. else {
  27747. engine.restoreDefaultFramebuffer();
  27748. }
  27749. }
  27750. var pp = postProcesses[index];
  27751. var effect = pp.apply();
  27752. if (effect) {
  27753. pp.onBeforeRenderObservable.notifyObservers(effect);
  27754. // VBOs
  27755. this._prepareBuffers();
  27756. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  27757. // Draw order
  27758. engine.draw(true, 0, 6);
  27759. pp.onAfterRenderObservable.notifyObservers(effect);
  27760. }
  27761. }
  27762. // Restore depth buffer
  27763. engine.setDepthBuffer(true);
  27764. engine.setDepthWrite(true);
  27765. };
  27766. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27767. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27768. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27769. return;
  27770. }
  27771. var engine = this._scene.getEngine();
  27772. for (var index = 0, len = postProcesses.length; index < len; index++) {
  27773. if (index < len - 1) {
  27774. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27775. }
  27776. else {
  27777. if (targetTexture) {
  27778. engine.bindFramebuffer(targetTexture, faceIndex);
  27779. }
  27780. else {
  27781. engine.restoreDefaultFramebuffer();
  27782. }
  27783. }
  27784. if (doNotPresent) {
  27785. break;
  27786. }
  27787. var pp = postProcesses[index];
  27788. var effect = pp.apply();
  27789. if (effect) {
  27790. pp.onBeforeRenderObservable.notifyObservers(effect);
  27791. // VBOs
  27792. this._prepareBuffers();
  27793. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  27794. // Draw order
  27795. engine.draw(true, 0, 6);
  27796. pp.onAfterRenderObservable.notifyObservers(effect);
  27797. }
  27798. }
  27799. // Restore depth buffer
  27800. engine.setDepthBuffer(true);
  27801. engine.setDepthWrite(true);
  27802. };
  27803. PostProcessManager.prototype.dispose = function () {
  27804. if (this._vertexBuffer) {
  27805. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  27806. this._vertexBuffer = null;
  27807. }
  27808. if (this._indexBuffer) {
  27809. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27810. this._indexBuffer = null;
  27811. }
  27812. };
  27813. return PostProcessManager;
  27814. })();
  27815. BABYLON.PostProcessManager = PostProcessManager;
  27816. })(BABYLON || (BABYLON = {}));
  27817. var BABYLON;
  27818. (function (BABYLON) {
  27819. var PassPostProcess = (function (_super) {
  27820. __extends(PassPostProcess, _super);
  27821. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  27822. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  27823. }
  27824. return PassPostProcess;
  27825. })(BABYLON.PostProcess);
  27826. BABYLON.PassPostProcess = PassPostProcess;
  27827. })(BABYLON || (BABYLON = {}));
  27828. var BABYLON;
  27829. (function (BABYLON) {
  27830. /**
  27831. * This is a holder class for the physics joint created by the physics plugin.
  27832. * It holds a set of functions to control the underlying joint.
  27833. */
  27834. var PhysicsJoint = (function () {
  27835. function PhysicsJoint(type, jointData) {
  27836. this.type = type;
  27837. this.jointData = jointData;
  27838. jointData.nativeParams = jointData.nativeParams || {};
  27839. }
  27840. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  27841. get: function () {
  27842. return this._physicsJoint;
  27843. },
  27844. set: function (newJoint) {
  27845. if (this._physicsJoint) {
  27846. }
  27847. this._physicsJoint = newJoint;
  27848. },
  27849. enumerable: true,
  27850. configurable: true
  27851. });
  27852. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  27853. set: function (physicsPlugin) {
  27854. this._physicsPlugin = physicsPlugin;
  27855. },
  27856. enumerable: true,
  27857. configurable: true
  27858. });
  27859. /**
  27860. * Execute a function that is physics-plugin specific.
  27861. * @param {Function} func the function that will be executed.
  27862. * It accepts two parameters: the physics world and the physics joint.
  27863. */
  27864. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  27865. func(this._physicsPlugin.world, this._physicsJoint);
  27866. };
  27867. //TODO check if the native joints are the same
  27868. //Joint Types
  27869. PhysicsJoint.DistanceJoint = 0;
  27870. PhysicsJoint.HingeJoint = 1;
  27871. PhysicsJoint.BallAndSocketJoint = 2;
  27872. PhysicsJoint.WheelJoint = 3;
  27873. PhysicsJoint.SliderJoint = 4;
  27874. //OIMO
  27875. PhysicsJoint.PrismaticJoint = 5;
  27876. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  27877. PhysicsJoint.UniversalJoint = 6;
  27878. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  27879. //Cannon
  27880. //Similar to a Ball-Joint. Different in params
  27881. PhysicsJoint.PointToPointJoint = 8;
  27882. //Cannon only at the moment
  27883. PhysicsJoint.SpringJoint = 9;
  27884. return PhysicsJoint;
  27885. })();
  27886. BABYLON.PhysicsJoint = PhysicsJoint;
  27887. /**
  27888. * A class representing a physics distance joint.
  27889. */
  27890. var DistanceJoint = (function (_super) {
  27891. __extends(DistanceJoint, _super);
  27892. function DistanceJoint(jointData) {
  27893. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  27894. }
  27895. /**
  27896. * Update the predefined distance.
  27897. */
  27898. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  27899. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  27900. };
  27901. return DistanceJoint;
  27902. })(PhysicsJoint);
  27903. BABYLON.DistanceJoint = DistanceJoint;
  27904. var MotorEnabledJoint = (function (_super) {
  27905. __extends(MotorEnabledJoint, _super);
  27906. function MotorEnabledJoint(type, jointData) {
  27907. _super.call(this, type, jointData);
  27908. }
  27909. /**
  27910. * Set the motor values.
  27911. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27912. * @param {number} force the force to apply
  27913. * @param {number} maxForce max force for this motor.
  27914. */
  27915. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  27916. this._physicsPlugin.setMotor(this, force, maxForce);
  27917. };
  27918. /**
  27919. * Set the motor's limits.
  27920. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27921. */
  27922. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27923. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27924. };
  27925. return MotorEnabledJoint;
  27926. })(PhysicsJoint);
  27927. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  27928. /**
  27929. * This class represents a single hinge physics joint
  27930. */
  27931. var HingeJoint = (function (_super) {
  27932. __extends(HingeJoint, _super);
  27933. function HingeJoint(jointData) {
  27934. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  27935. }
  27936. /**
  27937. * Set the motor values.
  27938. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27939. * @param {number} force the force to apply
  27940. * @param {number} maxForce max force for this motor.
  27941. */
  27942. HingeJoint.prototype.setMotor = function (force, maxForce) {
  27943. this._physicsPlugin.setMotor(this, force, maxForce);
  27944. };
  27945. /**
  27946. * Set the motor's limits.
  27947. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27948. */
  27949. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27950. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27951. };
  27952. return HingeJoint;
  27953. })(MotorEnabledJoint);
  27954. BABYLON.HingeJoint = HingeJoint;
  27955. /**
  27956. * This class represents a dual hinge physics joint (same as wheel joint)
  27957. */
  27958. var Hinge2Joint = (function (_super) {
  27959. __extends(Hinge2Joint, _super);
  27960. function Hinge2Joint(jointData) {
  27961. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  27962. }
  27963. /**
  27964. * Set the motor values.
  27965. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27966. * @param {number} force the force to apply
  27967. * @param {number} maxForce max force for this motor.
  27968. * @param {motorIndex} the motor's index, 0 or 1.
  27969. */
  27970. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  27971. if (motorIndex === void 0) { motorIndex = 0; }
  27972. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  27973. };
  27974. /**
  27975. * Set the motor limits.
  27976. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27977. * @param {number} upperLimit the upper limit
  27978. * @param {number} lowerLimit lower limit
  27979. * @param {motorIndex} the motor's index, 0 or 1.
  27980. */
  27981. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  27982. if (motorIndex === void 0) { motorIndex = 0; }
  27983. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  27984. };
  27985. return Hinge2Joint;
  27986. })(MotorEnabledJoint);
  27987. BABYLON.Hinge2Joint = Hinge2Joint;
  27988. })(BABYLON || (BABYLON = {}));
  27989. var BABYLON;
  27990. (function (BABYLON) {
  27991. var PhysicsImpostor = (function () {
  27992. function PhysicsImpostor(object, type, _options, _scene) {
  27993. var _this = this;
  27994. if (_options === void 0) { _options = { mass: 0 }; }
  27995. this.object = object;
  27996. this.type = type;
  27997. this._options = _options;
  27998. this._scene = _scene;
  27999. this._bodyUpdateRequired = false;
  28000. this._onBeforePhysicsStepCallbacks = new Array();
  28001. this._onAfterPhysicsStepCallbacks = new Array();
  28002. this._onPhysicsCollideCallbacks = [];
  28003. this._deltaPosition = BABYLON.Vector3.Zero();
  28004. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  28005. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  28006. /**
  28007. * this function is executed by the physics engine.
  28008. */
  28009. this.beforeStep = function () {
  28010. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  28011. //conjugate deltaRotation
  28012. if (_this._deltaRotationConjugated) {
  28013. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  28014. }
  28015. else {
  28016. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  28017. }
  28018. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  28019. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  28020. func(_this);
  28021. });
  28022. };
  28023. /**
  28024. * this function is executed by the physics engine.
  28025. */
  28026. this.afterStep = function () {
  28027. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  28028. func(_this);
  28029. });
  28030. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  28031. _this.object.position.addInPlace(_this._deltaPosition);
  28032. if (_this._deltaRotation) {
  28033. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  28034. }
  28035. };
  28036. //event and body object due to cannon's event-based architecture.
  28037. this.onCollide = function (e) {
  28038. if (!_this._onPhysicsCollideCallbacks.length)
  28039. return;
  28040. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  28041. if (otherImpostor) {
  28042. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  28043. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  28044. }).forEach(function (obj) {
  28045. obj.callback(_this, otherImpostor);
  28046. });
  28047. }
  28048. };
  28049. //sanity check!
  28050. if (!this.object) {
  28051. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  28052. return;
  28053. }
  28054. //legacy support for old syntax.
  28055. if (!this._scene && object.getScene) {
  28056. this._scene = object.getScene();
  28057. }
  28058. this._physicsEngine = this._scene.getPhysicsEngine();
  28059. if (!this._physicsEngine) {
  28060. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  28061. }
  28062. else {
  28063. //set the object's quaternion, if not set
  28064. if (!this.object.rotationQuaternion) {
  28065. if (this.object.rotation) {
  28066. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  28067. }
  28068. else {
  28069. this.object.rotationQuaternion = new BABYLON.Quaternion();
  28070. }
  28071. }
  28072. //default options params
  28073. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  28074. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  28075. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  28076. this._joints = [];
  28077. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  28078. if (!this.object.parent) {
  28079. this._init();
  28080. }
  28081. }
  28082. }
  28083. /**
  28084. * This function will completly initialize this impostor.
  28085. * It will create a new body - but only if this mesh has no parent.
  28086. * If it has, this impostor will not be used other than to define the impostor
  28087. * of the child mesh.
  28088. */
  28089. PhysicsImpostor.prototype._init = function () {
  28090. this._physicsEngine.removeImpostor(this);
  28091. this.physicsBody = null;
  28092. this._parent = this._parent || this._getPhysicsParent();
  28093. if (!this.parent) {
  28094. this._physicsEngine.addImpostor(this);
  28095. }
  28096. };
  28097. PhysicsImpostor.prototype._getPhysicsParent = function () {
  28098. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  28099. var parentMesh = this.object.parent;
  28100. return parentMesh.physicsImpostor;
  28101. }
  28102. return;
  28103. };
  28104. /**
  28105. * Should a new body be generated.
  28106. */
  28107. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  28108. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  28109. };
  28110. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  28111. this.forceUpdate();
  28112. };
  28113. /**
  28114. * Force a regeneration of this or the parent's impostor's body.
  28115. * Use under cautious - This will remove all joints already implemented.
  28116. */
  28117. PhysicsImpostor.prototype.forceUpdate = function () {
  28118. this._init();
  28119. if (this.parent) {
  28120. this.parent.forceUpdate();
  28121. }
  28122. };
  28123. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  28124. /*public get mesh(): AbstractMesh {
  28125. return this._mesh;
  28126. }*/
  28127. /**
  28128. * Gets the body that holds this impostor. Either its own, or its parent.
  28129. */
  28130. get: function () {
  28131. return this._parent ? this._parent.physicsBody : this._physicsBody;
  28132. },
  28133. /**
  28134. * Set the physics body. Used mainly by the physics engine/plugin
  28135. */
  28136. set: function (physicsBody) {
  28137. if (this._physicsBody) {
  28138. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  28139. }
  28140. this._physicsBody = physicsBody;
  28141. this.resetUpdateFlags();
  28142. },
  28143. enumerable: true,
  28144. configurable: true
  28145. });
  28146. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  28147. get: function () {
  28148. return this._parent;
  28149. },
  28150. enumerable: true,
  28151. configurable: true
  28152. });
  28153. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  28154. this._bodyUpdateRequired = false;
  28155. };
  28156. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  28157. if (this.object.getBoundingInfo) {
  28158. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  28159. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  28160. }
  28161. else {
  28162. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  28163. }
  28164. };
  28165. PhysicsImpostor.prototype.getObjectCenter = function () {
  28166. if (this.object.getBoundingInfo) {
  28167. return this.object.getBoundingInfo().boundingBox.center;
  28168. }
  28169. else {
  28170. return this.object.position;
  28171. }
  28172. };
  28173. /**
  28174. * Get a specific parametes from the options parameter.
  28175. */
  28176. PhysicsImpostor.prototype.getParam = function (paramName) {
  28177. return this._options[paramName];
  28178. };
  28179. /**
  28180. * Sets a specific parameter in the options given to the physics plugin
  28181. */
  28182. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  28183. this._options[paramName] = value;
  28184. this._bodyUpdateRequired = true;
  28185. };
  28186. /**
  28187. * Specifically change the body's mass option. Won't recreate the physics body object
  28188. */
  28189. PhysicsImpostor.prototype.setMass = function (mass) {
  28190. if (this.getParam("mass") !== mass) {
  28191. this.setParam("mass", mass);
  28192. }
  28193. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  28194. };
  28195. PhysicsImpostor.prototype.getLinearVelocity = function () {
  28196. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  28197. };
  28198. /**
  28199. * Set the body's linear velocity.
  28200. */
  28201. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  28202. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  28203. };
  28204. PhysicsImpostor.prototype.getAngularVelocity = function () {
  28205. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  28206. };
  28207. /**
  28208. * Set the body's linear velocity.
  28209. */
  28210. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  28211. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  28212. };
  28213. /**
  28214. * Execute a function with the physics plugin native code.
  28215. * Provide a function the will have two variables - the world object and the physics body object.
  28216. */
  28217. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  28218. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  28219. };
  28220. /**
  28221. * Register a function that will be executed before the physics world is stepping forward.
  28222. */
  28223. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  28224. this._onBeforePhysicsStepCallbacks.push(func);
  28225. };
  28226. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  28227. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  28228. if (index > -1) {
  28229. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  28230. }
  28231. else {
  28232. BABYLON.Tools.Warn("Function to remove was not found");
  28233. }
  28234. };
  28235. /**
  28236. * Register a function that will be executed after the physics step
  28237. */
  28238. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  28239. this._onAfterPhysicsStepCallbacks.push(func);
  28240. };
  28241. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  28242. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  28243. if (index > -1) {
  28244. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  28245. }
  28246. else {
  28247. BABYLON.Tools.Warn("Function to remove was not found");
  28248. }
  28249. };
  28250. /**
  28251. * register a function that will be executed when this impostor collides against a different body.
  28252. */
  28253. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  28254. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28255. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  28256. };
  28257. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  28258. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28259. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  28260. if (index > -1) {
  28261. this._onPhysicsCollideCallbacks.splice(index, 1);
  28262. }
  28263. else {
  28264. BABYLON.Tools.Warn("Function to remove was not found");
  28265. }
  28266. };
  28267. /**
  28268. * Apply a force
  28269. */
  28270. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  28271. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  28272. };
  28273. /**
  28274. * Apply an impulse
  28275. */
  28276. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  28277. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  28278. };
  28279. /**
  28280. * A help function to create a joint.
  28281. */
  28282. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  28283. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  28284. this.addJoint(otherImpostor, joint);
  28285. };
  28286. /**
  28287. * Add a joint to this impostor with a different impostor.
  28288. */
  28289. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  28290. this._joints.push({
  28291. otherImpostor: otherImpostor,
  28292. joint: joint
  28293. });
  28294. this._physicsEngine.addJoint(this, otherImpostor, joint);
  28295. };
  28296. /**
  28297. * Will keep this body still, in a sleep mode.
  28298. */
  28299. PhysicsImpostor.prototype.sleep = function () {
  28300. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  28301. };
  28302. /**
  28303. * Wake the body up.
  28304. */
  28305. PhysicsImpostor.prototype.wakeUp = function () {
  28306. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  28307. };
  28308. PhysicsImpostor.prototype.clone = function (newObject) {
  28309. if (!newObject)
  28310. return null;
  28311. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  28312. };
  28313. PhysicsImpostor.prototype.dispose = function () {
  28314. var _this = this;
  28315. //no dispose if no physics engine is available.
  28316. if (!this._physicsEngine) {
  28317. return;
  28318. }
  28319. this._joints.forEach(function (j) {
  28320. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  28321. });
  28322. //dispose the physics body
  28323. this._physicsEngine.removeImpostor(this);
  28324. if (this.parent) {
  28325. this.parent.forceUpdate();
  28326. }
  28327. else {
  28328. }
  28329. };
  28330. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  28331. this._deltaPosition.copyFrom(position);
  28332. };
  28333. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  28334. if (!this._deltaRotation) {
  28335. this._deltaRotation = new BABYLON.Quaternion();
  28336. }
  28337. this._deltaRotation.copyFrom(rotation);
  28338. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  28339. };
  28340. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  28341. //Impostor types
  28342. PhysicsImpostor.NoImpostor = 0;
  28343. PhysicsImpostor.SphereImpostor = 1;
  28344. PhysicsImpostor.BoxImpostor = 2;
  28345. PhysicsImpostor.PlaneImpostor = 3;
  28346. PhysicsImpostor.MeshImpostor = 4;
  28347. PhysicsImpostor.CylinderImpostor = 7;
  28348. PhysicsImpostor.ParticleImpostor = 8;
  28349. PhysicsImpostor.HeightmapImpostor = 9;
  28350. return PhysicsImpostor;
  28351. })();
  28352. BABYLON.PhysicsImpostor = PhysicsImpostor;
  28353. })(BABYLON || (BABYLON = {}));
  28354. var BABYLON;
  28355. (function (BABYLON) {
  28356. var PhysicsEngine = (function () {
  28357. function PhysicsEngine(gravity, _physicsPlugin) {
  28358. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  28359. this._physicsPlugin = _physicsPlugin;
  28360. //new methods and parameters
  28361. this._impostors = [];
  28362. this._joints = [];
  28363. if (!this._physicsPlugin.isSupported()) {
  28364. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  28365. + "Please make sure it is included.");
  28366. }
  28367. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  28368. this.setGravity(gravity);
  28369. this.setTimeStep();
  28370. }
  28371. PhysicsEngine.prototype.setGravity = function (gravity) {
  28372. this.gravity = gravity;
  28373. this._physicsPlugin.setGravity(this.gravity);
  28374. };
  28375. /**
  28376. * Set the time step of the physics engine.
  28377. * default is 1/60.
  28378. * To slow it down, enter 1/600 for example.
  28379. * To speed it up, 1/30
  28380. * @param {number} newTimeStep the new timestep to apply to this world.
  28381. */
  28382. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  28383. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  28384. this._physicsPlugin.setTimeStep(newTimeStep);
  28385. };
  28386. PhysicsEngine.prototype.dispose = function () {
  28387. this._impostors.forEach(function (impostor) {
  28388. impostor.dispose();
  28389. });
  28390. this._physicsPlugin.dispose();
  28391. };
  28392. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  28393. return this._physicsPlugin.name;
  28394. };
  28395. /**
  28396. * Adding a new impostor for the impostor tracking.
  28397. * This will be done by the impostor itself.
  28398. * @param {PhysicsImpostor} impostor the impostor to add
  28399. */
  28400. PhysicsEngine.prototype.addImpostor = function (impostor) {
  28401. impostor.uniqueId = this._impostors.push(impostor);
  28402. //if no parent, generate the body
  28403. if (!impostor.parent) {
  28404. this._physicsPlugin.generatePhysicsBody(impostor);
  28405. }
  28406. };
  28407. /**
  28408. * Remove an impostor from the engine.
  28409. * This impostor and its mesh will not longer be updated by the physics engine.
  28410. * @param {PhysicsImpostor} impostor the impostor to remove
  28411. */
  28412. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  28413. var index = this._impostors.indexOf(impostor);
  28414. if (index > -1) {
  28415. var removed = this._impostors.splice(index, 1);
  28416. //Is it needed?
  28417. if (removed.length) {
  28418. //this will also remove it from the world.
  28419. removed[0].physicsBody = null;
  28420. }
  28421. }
  28422. };
  28423. /**
  28424. * Add a joint to the physics engine
  28425. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  28426. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  28427. * @param {PhysicsJoint} the joint that will connect both impostors.
  28428. */
  28429. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  28430. var impostorJoint = {
  28431. mainImpostor: mainImpostor,
  28432. connectedImpostor: connectedImpostor,
  28433. joint: joint
  28434. };
  28435. joint.physicsPlugin = this._physicsPlugin;
  28436. this._joints.push(impostorJoint);
  28437. this._physicsPlugin.generateJoint(impostorJoint);
  28438. };
  28439. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  28440. var matchingJoints = this._joints.filter(function (impostorJoint) {
  28441. return (impostorJoint.connectedImpostor === connectedImpostor
  28442. && impostorJoint.joint === joint
  28443. && impostorJoint.mainImpostor === mainImpostor);
  28444. });
  28445. if (matchingJoints.length) {
  28446. this._physicsPlugin.removeJoint(matchingJoints[0]);
  28447. }
  28448. };
  28449. /**
  28450. * Called by the scene. no need to call it.
  28451. */
  28452. PhysicsEngine.prototype._step = function (delta) {
  28453. var _this = this;
  28454. //check if any mesh has no body / requires an update
  28455. this._impostors.forEach(function (impostor) {
  28456. if (impostor.isBodyInitRequired()) {
  28457. _this._physicsPlugin.generatePhysicsBody(impostor);
  28458. }
  28459. });
  28460. if (delta > 0.1) {
  28461. delta = 0.1;
  28462. }
  28463. else if (delta <= 0) {
  28464. delta = 1.0 / 60.0;
  28465. }
  28466. this._physicsPlugin.executeStep(delta, this._impostors);
  28467. };
  28468. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  28469. return this._physicsPlugin;
  28470. };
  28471. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  28472. for (var i = 0; i < this._impostors.length; ++i) {
  28473. if (this._impostors[i].object === object) {
  28474. return this._impostors[i];
  28475. }
  28476. }
  28477. };
  28478. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  28479. for (var i = 0; i < this._impostors.length; ++i) {
  28480. if (this._impostors[i].physicsBody === body) {
  28481. return this._impostors[i];
  28482. }
  28483. }
  28484. };
  28485. // Statics, Legacy support.
  28486. /**
  28487. * @Deprecated
  28488. *
  28489. */
  28490. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  28491. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  28492. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  28493. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  28494. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  28495. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  28496. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  28497. PhysicsEngine.CapsuleImpostor = -1;
  28498. PhysicsEngine.ConeImpostor = -1;
  28499. PhysicsEngine.ConvexHullImpostor = -1;
  28500. PhysicsEngine.Epsilon = 0.001;
  28501. return PhysicsEngine;
  28502. })();
  28503. BABYLON.PhysicsEngine = PhysicsEngine;
  28504. })(BABYLON || (BABYLON = {}));
  28505. var BABYLON;
  28506. (function (BABYLON) {
  28507. var VertexData = (function () {
  28508. function VertexData() {
  28509. }
  28510. VertexData.prototype.set = function (data, kind) {
  28511. switch (kind) {
  28512. case BABYLON.VertexBuffer.PositionKind:
  28513. this.positions = data;
  28514. break;
  28515. case BABYLON.VertexBuffer.NormalKind:
  28516. this.normals = data;
  28517. break;
  28518. case BABYLON.VertexBuffer.UVKind:
  28519. this.uvs = data;
  28520. break;
  28521. case BABYLON.VertexBuffer.UV2Kind:
  28522. this.uvs2 = data;
  28523. break;
  28524. case BABYLON.VertexBuffer.UV3Kind:
  28525. this.uvs3 = data;
  28526. break;
  28527. case BABYLON.VertexBuffer.UV4Kind:
  28528. this.uvs4 = data;
  28529. break;
  28530. case BABYLON.VertexBuffer.UV5Kind:
  28531. this.uvs5 = data;
  28532. break;
  28533. case BABYLON.VertexBuffer.UV6Kind:
  28534. this.uvs6 = data;
  28535. break;
  28536. case BABYLON.VertexBuffer.ColorKind:
  28537. this.colors = data;
  28538. break;
  28539. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28540. this.matricesIndices = data;
  28541. break;
  28542. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28543. this.matricesWeights = data;
  28544. break;
  28545. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28546. this.matricesIndicesExtra = data;
  28547. break;
  28548. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28549. this.matricesWeightsExtra = data;
  28550. break;
  28551. }
  28552. };
  28553. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28554. this._applyTo(mesh, updatable);
  28555. };
  28556. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28557. this._applyTo(geometry, updatable);
  28558. };
  28559. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28560. this._update(mesh);
  28561. };
  28562. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28563. this._update(geometry);
  28564. };
  28565. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28566. if (this.positions) {
  28567. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28568. }
  28569. if (this.normals) {
  28570. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28571. }
  28572. if (this.uvs) {
  28573. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28574. }
  28575. if (this.uvs2) {
  28576. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28577. }
  28578. if (this.uvs3) {
  28579. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28580. }
  28581. if (this.uvs4) {
  28582. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28583. }
  28584. if (this.uvs5) {
  28585. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28586. }
  28587. if (this.uvs6) {
  28588. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28589. }
  28590. if (this.colors) {
  28591. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28592. }
  28593. if (this.matricesIndices) {
  28594. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28595. }
  28596. if (this.matricesWeights) {
  28597. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28598. }
  28599. if (this.matricesIndicesExtra) {
  28600. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28601. }
  28602. if (this.matricesWeightsExtra) {
  28603. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28604. }
  28605. if (this.indices) {
  28606. meshOrGeometry.setIndices(this.indices);
  28607. }
  28608. };
  28609. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28610. if (this.positions) {
  28611. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28612. }
  28613. if (this.normals) {
  28614. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28615. }
  28616. if (this.uvs) {
  28617. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28618. }
  28619. if (this.uvs2) {
  28620. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28621. }
  28622. if (this.uvs3) {
  28623. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28624. }
  28625. if (this.uvs4) {
  28626. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28627. }
  28628. if (this.uvs5) {
  28629. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28630. }
  28631. if (this.uvs6) {
  28632. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28633. }
  28634. if (this.colors) {
  28635. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28636. }
  28637. if (this.matricesIndices) {
  28638. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28639. }
  28640. if (this.matricesWeights) {
  28641. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28642. }
  28643. if (this.matricesIndicesExtra) {
  28644. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28645. }
  28646. if (this.matricesWeightsExtra) {
  28647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28648. }
  28649. if (this.indices) {
  28650. meshOrGeometry.setIndices(this.indices);
  28651. }
  28652. };
  28653. VertexData.prototype.transform = function (matrix) {
  28654. var transformed = BABYLON.Vector3.Zero();
  28655. var index;
  28656. if (this.positions) {
  28657. var position = BABYLON.Vector3.Zero();
  28658. for (index = 0; index < this.positions.length; index += 3) {
  28659. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28660. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28661. this.positions[index] = transformed.x;
  28662. this.positions[index + 1] = transformed.y;
  28663. this.positions[index + 2] = transformed.z;
  28664. }
  28665. }
  28666. if (this.normals) {
  28667. var normal = BABYLON.Vector3.Zero();
  28668. for (index = 0; index < this.normals.length; index += 3) {
  28669. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28670. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28671. this.normals[index] = transformed.x;
  28672. this.normals[index + 1] = transformed.y;
  28673. this.normals[index + 2] = transformed.z;
  28674. }
  28675. }
  28676. };
  28677. VertexData.prototype.merge = function (other) {
  28678. if (other.indices) {
  28679. if (!this.indices) {
  28680. this.indices = [];
  28681. }
  28682. var offset = this.positions ? this.positions.length / 3 : 0;
  28683. for (var index = 0; index < other.indices.length; index++) {
  28684. //TODO check type - if Int32Array!
  28685. this.indices.push(other.indices[index] + offset);
  28686. }
  28687. }
  28688. this.positions = this._mergeElement(this.positions, other.positions);
  28689. this.normals = this._mergeElement(this.normals, other.normals);
  28690. this.uvs = this._mergeElement(this.uvs, other.uvs);
  28691. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  28692. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  28693. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  28694. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  28695. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  28696. this.colors = this._mergeElement(this.colors, other.colors);
  28697. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  28698. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  28699. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  28700. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  28701. };
  28702. VertexData.prototype._mergeElement = function (source, other) {
  28703. if (!other)
  28704. return source;
  28705. if (!source)
  28706. return other;
  28707. var len = other.length + source.length;
  28708. var isSrcTypedArray = source instanceof Float32Array;
  28709. var isOthTypedArray = other instanceof Float32Array;
  28710. // use non-loop method when the source is Float32Array
  28711. if (isSrcTypedArray) {
  28712. var ret32 = new Float32Array(len);
  28713. ret32.set(source);
  28714. ret32.set(other, source.length);
  28715. return ret32;
  28716. }
  28717. else if (!isOthTypedArray) {
  28718. return source.concat(other);
  28719. }
  28720. else {
  28721. var ret = source.slice(0); // copy source to a separate array
  28722. for (var i = 0, len = other.length; i < len; i++) {
  28723. ret.push(other[i]);
  28724. }
  28725. return ret;
  28726. }
  28727. };
  28728. VertexData.prototype.serialize = function () {
  28729. var serializationObject = this.serialize();
  28730. if (this.positions) {
  28731. serializationObject.positions = this.positions;
  28732. }
  28733. if (this.normals) {
  28734. serializationObject.normals = this.normals;
  28735. }
  28736. if (this.uvs) {
  28737. serializationObject.uvs = this.uvs;
  28738. }
  28739. if (this.uvs2) {
  28740. serializationObject.uvs2 = this.uvs2;
  28741. }
  28742. if (this.uvs3) {
  28743. serializationObject.uvs3 = this.uvs3;
  28744. }
  28745. if (this.uvs4) {
  28746. serializationObject.uvs4 = this.uvs4;
  28747. }
  28748. if (this.uvs5) {
  28749. serializationObject.uvs5 = this.uvs5;
  28750. }
  28751. if (this.uvs6) {
  28752. serializationObject.uvs6 = this.uvs6;
  28753. }
  28754. if (this.colors) {
  28755. serializationObject.colors = this.colors;
  28756. }
  28757. if (this.matricesIndices) {
  28758. serializationObject.matricesIndices = this.matricesIndices;
  28759. serializationObject.matricesIndices._isExpanded = true;
  28760. }
  28761. if (this.matricesWeights) {
  28762. serializationObject.matricesWeights = this.matricesWeights;
  28763. }
  28764. if (this.matricesIndicesExtra) {
  28765. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28766. serializationObject.matricesIndicesExtra._isExpanded = true;
  28767. }
  28768. if (this.matricesWeightsExtra) {
  28769. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28770. }
  28771. serializationObject.indices = this.indices;
  28772. return serializationObject;
  28773. };
  28774. // Statics
  28775. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  28776. return VertexData._ExtractFrom(mesh, copyWhenShared);
  28777. };
  28778. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  28779. return VertexData._ExtractFrom(geometry, copyWhenShared);
  28780. };
  28781. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  28782. var result = new VertexData();
  28783. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28784. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  28785. }
  28786. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28787. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  28788. }
  28789. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28790. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  28791. }
  28792. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28793. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  28794. }
  28795. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28796. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  28797. }
  28798. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28799. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  28800. }
  28801. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28802. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  28803. }
  28804. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28805. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  28806. }
  28807. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28808. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  28809. }
  28810. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28811. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  28812. }
  28813. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28814. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  28815. }
  28816. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28817. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  28818. }
  28819. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28820. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  28821. }
  28822. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28823. return result;
  28824. };
  28825. VertexData.CreateRibbon = function (options) {
  28826. var pathArray = options.pathArray;
  28827. var closeArray = options.closeArray || false;
  28828. var closePath = options.closePath || false;
  28829. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28830. var offset = options.offset || defaultOffset;
  28831. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28832. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28833. var positions = [];
  28834. var indices = [];
  28835. var normals = [];
  28836. var uvs = [];
  28837. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28838. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28839. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28840. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28841. var minlg; // minimal length among all paths from pathArray
  28842. var lg = []; // array of path lengths : nb of vertex per path
  28843. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28844. var p; // path iterator
  28845. var i; // point iterator
  28846. var j; // point iterator
  28847. // if single path in pathArray
  28848. if (pathArray.length < 2) {
  28849. var ar1 = [];
  28850. var ar2 = [];
  28851. for (i = 0; i < pathArray[0].length - offset; i++) {
  28852. ar1.push(pathArray[0][i]);
  28853. ar2.push(pathArray[0][i + offset]);
  28854. }
  28855. pathArray = [ar1, ar2];
  28856. }
  28857. // positions and horizontal distances (u)
  28858. var idc = 0;
  28859. var closePathCorr = (closePath) ? 1 : 0;
  28860. var path;
  28861. var l;
  28862. minlg = pathArray[0].length;
  28863. var vectlg;
  28864. var dist;
  28865. for (p = 0; p < pathArray.length; p++) {
  28866. uTotalDistance[p] = 0;
  28867. us[p] = [0];
  28868. path = pathArray[p];
  28869. l = path.length;
  28870. minlg = (minlg < l) ? minlg : l;
  28871. j = 0;
  28872. while (j < l) {
  28873. positions.push(path[j].x, path[j].y, path[j].z);
  28874. if (j > 0) {
  28875. vectlg = path[j].subtract(path[j - 1]).length();
  28876. dist = vectlg + uTotalDistance[p];
  28877. us[p].push(dist);
  28878. uTotalDistance[p] = dist;
  28879. }
  28880. j++;
  28881. }
  28882. if (closePath) {
  28883. j--;
  28884. positions.push(path[0].x, path[0].y, path[0].z);
  28885. vectlg = path[j].subtract(path[0]).length();
  28886. dist = vectlg + uTotalDistance[p];
  28887. us[p].push(dist);
  28888. uTotalDistance[p] = dist;
  28889. }
  28890. lg[p] = l + closePathCorr;
  28891. idx[p] = idc;
  28892. idc += (l + closePathCorr);
  28893. }
  28894. // vertical distances (v)
  28895. var path1;
  28896. var path2;
  28897. var vertex1;
  28898. var vertex2;
  28899. for (i = 0; i < minlg + closePathCorr; i++) {
  28900. vTotalDistance[i] = 0;
  28901. vs[i] = [0];
  28902. for (p = 0; p < pathArray.length - 1; p++) {
  28903. path1 = pathArray[p];
  28904. path2 = pathArray[p + 1];
  28905. if (i === minlg) {
  28906. vertex1 = path1[0];
  28907. vertex2 = path2[0];
  28908. }
  28909. else {
  28910. vertex1 = path1[i];
  28911. vertex2 = path2[i];
  28912. }
  28913. vectlg = vertex2.subtract(vertex1).length();
  28914. dist = vectlg + vTotalDistance[i];
  28915. vs[i].push(dist);
  28916. vTotalDistance[i] = dist;
  28917. }
  28918. if (closeArray) {
  28919. path1 = pathArray[p];
  28920. path2 = pathArray[0];
  28921. if (i === minlg) {
  28922. vertex2 = path2[0];
  28923. }
  28924. vectlg = vertex2.subtract(vertex1).length();
  28925. dist = vectlg + vTotalDistance[i];
  28926. vTotalDistance[i] = dist;
  28927. }
  28928. }
  28929. // uvs
  28930. var u;
  28931. var v;
  28932. for (p = 0; p < pathArray.length; p++) {
  28933. for (i = 0; i < minlg + closePathCorr; i++) {
  28934. u = us[p][i] / uTotalDistance[p];
  28935. v = vs[i][p] / vTotalDistance[i];
  28936. uvs.push(u, v);
  28937. }
  28938. }
  28939. // indices
  28940. p = 0; // path index
  28941. var pi = 0; // positions array index
  28942. var l1 = lg[p] - 1; // path1 length
  28943. var l2 = lg[p + 1] - 1; // path2 length
  28944. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28945. var shft = idx[1] - idx[0]; // shift
  28946. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28947. while (pi <= min && p < path1nb) {
  28948. // 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
  28949. indices.push(pi, pi + shft, pi + 1);
  28950. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28951. pi += 1;
  28952. if (pi === min) {
  28953. p++;
  28954. if (p === lg.length - 1) {
  28955. shft = idx[0] - idx[p];
  28956. l1 = lg[p] - 1;
  28957. l2 = lg[0] - 1;
  28958. }
  28959. else {
  28960. shft = idx[p + 1] - idx[p];
  28961. l1 = lg[p] - 1;
  28962. l2 = lg[p + 1] - 1;
  28963. }
  28964. pi = idx[p];
  28965. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28966. }
  28967. }
  28968. // normals
  28969. VertexData.ComputeNormals(positions, indices, normals);
  28970. if (closePath) {
  28971. var indexFirst = 0;
  28972. var indexLast = 0;
  28973. for (p = 0; p < pathArray.length; p++) {
  28974. indexFirst = idx[p] * 3;
  28975. if (p + 1 < pathArray.length) {
  28976. indexLast = (idx[p + 1] - 1) * 3;
  28977. }
  28978. else {
  28979. indexLast = normals.length - 3;
  28980. }
  28981. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28982. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28983. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28984. normals[indexLast] = normals[indexFirst];
  28985. normals[indexLast + 1] = normals[indexFirst + 1];
  28986. normals[indexLast + 2] = normals[indexFirst + 2];
  28987. }
  28988. }
  28989. // sides
  28990. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28991. // Result
  28992. var vertexData = new VertexData();
  28993. vertexData.indices = indices;
  28994. vertexData.positions = positions;
  28995. vertexData.normals = normals;
  28996. vertexData.uvs = uvs;
  28997. if (closePath) {
  28998. vertexData._idx = idx;
  28999. }
  29000. return vertexData;
  29001. };
  29002. VertexData.CreateBox = function (options) {
  29003. var normalsSource = [
  29004. new BABYLON.Vector3(0, 0, 1),
  29005. new BABYLON.Vector3(0, 0, -1),
  29006. new BABYLON.Vector3(1, 0, 0),
  29007. new BABYLON.Vector3(-1, 0, 0),
  29008. new BABYLON.Vector3(0, 1, 0),
  29009. new BABYLON.Vector3(0, -1, 0)
  29010. ];
  29011. var indices = [];
  29012. var positions = [];
  29013. var normals = [];
  29014. var uvs = [];
  29015. var width = options.width || options.size || 1;
  29016. var height = options.height || options.size || 1;
  29017. var depth = options.depth || options.size || 1;
  29018. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29019. var faceUV = options.faceUV || new Array(6);
  29020. var faceColors = options.faceColors;
  29021. var colors = [];
  29022. // default face colors and UV if undefined
  29023. for (var f = 0; f < 6; f++) {
  29024. if (faceUV[f] === undefined) {
  29025. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29026. }
  29027. if (faceColors && faceColors[f] === undefined) {
  29028. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29029. }
  29030. }
  29031. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29032. // Create each face in turn.
  29033. for (var index = 0; index < normalsSource.length; index++) {
  29034. var normal = normalsSource[index];
  29035. // Get two vectors perpendicular to the face normal and to each other.
  29036. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29037. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29038. // Six indices (two triangles) per face.
  29039. var verticesLength = positions.length / 3;
  29040. indices.push(verticesLength);
  29041. indices.push(verticesLength + 1);
  29042. indices.push(verticesLength + 2);
  29043. indices.push(verticesLength);
  29044. indices.push(verticesLength + 2);
  29045. indices.push(verticesLength + 3);
  29046. // Four vertices per face.
  29047. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29048. positions.push(vertex.x, vertex.y, vertex.z);
  29049. normals.push(normal.x, normal.y, normal.z);
  29050. uvs.push(faceUV[index].z, faceUV[index].w);
  29051. if (faceColors) {
  29052. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29053. }
  29054. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29055. positions.push(vertex.x, vertex.y, vertex.z);
  29056. normals.push(normal.x, normal.y, normal.z);
  29057. uvs.push(faceUV[index].x, faceUV[index].w);
  29058. if (faceColors) {
  29059. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29060. }
  29061. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29062. positions.push(vertex.x, vertex.y, vertex.z);
  29063. normals.push(normal.x, normal.y, normal.z);
  29064. uvs.push(faceUV[index].x, faceUV[index].y);
  29065. if (faceColors) {
  29066. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29067. }
  29068. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29069. positions.push(vertex.x, vertex.y, vertex.z);
  29070. normals.push(normal.x, normal.y, normal.z);
  29071. uvs.push(faceUV[index].z, faceUV[index].y);
  29072. if (faceColors) {
  29073. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29074. }
  29075. }
  29076. // sides
  29077. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29078. // Result
  29079. var vertexData = new VertexData();
  29080. vertexData.indices = indices;
  29081. vertexData.positions = positions;
  29082. vertexData.normals = normals;
  29083. vertexData.uvs = uvs;
  29084. if (faceColors) {
  29085. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29086. vertexData.colors = totalColors;
  29087. }
  29088. return vertexData;
  29089. };
  29090. VertexData.CreateSphere = function (options) {
  29091. var segments = options.segments || 32;
  29092. var diameterX = options.diameterX || options.diameter || 1;
  29093. var diameterY = options.diameterY || options.diameter || 1;
  29094. var diameterZ = options.diameterZ || options.diameter || 1;
  29095. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29096. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29097. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29098. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29099. var totalZRotationSteps = 2 + segments;
  29100. var totalYRotationSteps = 2 * totalZRotationSteps;
  29101. var indices = [];
  29102. var positions = [];
  29103. var normals = [];
  29104. var uvs = [];
  29105. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29106. var normalizedZ = zRotationStep / totalZRotationSteps;
  29107. var angleZ = normalizedZ * Math.PI * slice;
  29108. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29109. var normalizedY = yRotationStep / totalYRotationSteps;
  29110. var angleY = normalizedY * Math.PI * 2 * arc;
  29111. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29112. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29113. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29114. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29115. var vertex = complete.multiply(radius);
  29116. var normal = complete.divide(radius).normalize();
  29117. positions.push(vertex.x, vertex.y, vertex.z);
  29118. normals.push(normal.x, normal.y, normal.z);
  29119. uvs.push(normalizedY, normalizedZ);
  29120. }
  29121. if (zRotationStep > 0) {
  29122. var verticesCount = positions.length / 3;
  29123. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29124. indices.push((firstIndex));
  29125. indices.push((firstIndex + 1));
  29126. indices.push(firstIndex + totalYRotationSteps + 1);
  29127. indices.push((firstIndex + totalYRotationSteps + 1));
  29128. indices.push((firstIndex + 1));
  29129. indices.push((firstIndex + totalYRotationSteps + 2));
  29130. }
  29131. }
  29132. }
  29133. // Sides
  29134. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29135. // Result
  29136. var vertexData = new VertexData();
  29137. vertexData.indices = indices;
  29138. vertexData.positions = positions;
  29139. vertexData.normals = normals;
  29140. vertexData.uvs = uvs;
  29141. return vertexData;
  29142. };
  29143. // Cylinder and cone
  29144. VertexData.CreateCylinder = function (options) {
  29145. var height = options.height || 2;
  29146. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29147. var diameterBottom = options.diameterBottom || options.diameter || 1;
  29148. var tessellation = options.tessellation || 24;
  29149. var subdivisions = options.subdivisions || 1;
  29150. var hasRings = options.hasRings;
  29151. var enclose = options.enclose;
  29152. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29153. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29154. var faceUV = options.faceUV || new Array(3);
  29155. var faceColors = options.faceColors;
  29156. // default face colors and UV if undefined
  29157. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29158. var ringNb = (hasRings) ? subdivisions : 1;
  29159. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29160. var f;
  29161. for (f = 0; f < surfaceNb; f++) {
  29162. if (faceColors && faceColors[f] === undefined) {
  29163. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29164. }
  29165. }
  29166. for (f = 0; f < surfaceNb; f++) {
  29167. if (faceUV && faceUV[f] === undefined) {
  29168. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29169. }
  29170. }
  29171. var indices = [];
  29172. var positions = [];
  29173. var normals = [];
  29174. var uvs = [];
  29175. var colors = [];
  29176. var angle_step = Math.PI * 2 * arc / tessellation;
  29177. var angle;
  29178. var h;
  29179. var radius;
  29180. var tan = (diameterBottom - diameterTop) / 2 / height;
  29181. var ringVertex = BABYLON.Vector3.Zero();
  29182. var ringNormal = BABYLON.Vector3.Zero();
  29183. var ringFirstVertex = BABYLON.Vector3.Zero();
  29184. var ringFirstNormal = BABYLON.Vector3.Zero();
  29185. var quadNormal = BABYLON.Vector3.Zero();
  29186. var Y = BABYLON.Axis.Y;
  29187. // positions, normals, uvs
  29188. var i;
  29189. var j;
  29190. var r;
  29191. var ringIdx = 1;
  29192. var s = 1; // surface index
  29193. var cs = 0;
  29194. var v = 0;
  29195. for (i = 0; i <= subdivisions; i++) {
  29196. h = i / subdivisions;
  29197. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29198. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29199. for (r = 0; r < ringIdx; r++) {
  29200. if (hasRings) {
  29201. s += r;
  29202. }
  29203. if (enclose) {
  29204. s += 2 * r;
  29205. }
  29206. for (j = 0; j <= tessellation; j++) {
  29207. angle = j * angle_step;
  29208. // position
  29209. ringVertex.x = Math.cos(-angle) * radius;
  29210. ringVertex.y = -height / 2 + h * height;
  29211. ringVertex.z = Math.sin(-angle) * radius;
  29212. // normal
  29213. if (diameterTop === 0 && i === subdivisions) {
  29214. // if no top cap, reuse former normals
  29215. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29216. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29217. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29218. }
  29219. else {
  29220. ringNormal.x = ringVertex.x;
  29221. ringNormal.z = ringVertex.z;
  29222. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29223. ringNormal.normalize();
  29224. }
  29225. // keep first ring vertex values for enclose
  29226. if (j === 0) {
  29227. ringFirstVertex.copyFrom(ringVertex);
  29228. ringFirstNormal.copyFrom(ringNormal);
  29229. }
  29230. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29231. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29232. if (hasRings) {
  29233. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29234. }
  29235. else {
  29236. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29237. }
  29238. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29239. if (faceColors) {
  29240. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29241. }
  29242. }
  29243. // if enclose, add four vertices and their dedicated normals
  29244. if (arc !== 1 && enclose) {
  29245. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29246. positions.push(0, ringVertex.y, 0);
  29247. positions.push(0, ringVertex.y, 0);
  29248. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29249. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29250. quadNormal.normalize();
  29251. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29252. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29253. quadNormal.normalize();
  29254. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29255. if (hasRings) {
  29256. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29257. }
  29258. else {
  29259. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29260. }
  29261. uvs.push(faceUV[s + 1].x, v);
  29262. uvs.push(faceUV[s + 1].z, v);
  29263. if (hasRings) {
  29264. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29265. }
  29266. else {
  29267. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29268. }
  29269. uvs.push(faceUV[s + 2].x, v);
  29270. uvs.push(faceUV[s + 2].z, v);
  29271. if (faceColors) {
  29272. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29273. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29274. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29275. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29276. }
  29277. }
  29278. if (cs !== s) {
  29279. cs = s;
  29280. }
  29281. }
  29282. }
  29283. // indices
  29284. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29285. var s;
  29286. i = 0;
  29287. for (s = 0; s < subdivisions; s++) {
  29288. for (j = 0; j < tessellation; j++) {
  29289. var i0 = i * (e + 1) + j;
  29290. var i1 = (i + 1) * (e + 1) + j;
  29291. var i2 = i * (e + 1) + (j + 1);
  29292. var i3 = (i + 1) * (e + 1) + (j + 1);
  29293. indices.push(i0, i1, i2);
  29294. indices.push(i3, i2, i1);
  29295. }
  29296. if (arc !== 1 && enclose) {
  29297. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29298. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29299. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29300. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29301. }
  29302. i = (hasRings) ? (i + 2) : (i + 1);
  29303. }
  29304. // Caps
  29305. var createCylinderCap = function (isTop) {
  29306. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29307. if (radius === 0) {
  29308. return;
  29309. }
  29310. // Cap positions, normals & uvs
  29311. var angle;
  29312. var circleVector;
  29313. var i;
  29314. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29315. var c;
  29316. if (faceColors) {
  29317. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29318. }
  29319. // cap center
  29320. var vbase = positions.length / 3;
  29321. var offset = isTop ? height / 2 : -height / 2;
  29322. var center = new BABYLON.Vector3(0, offset, 0);
  29323. positions.push(center.x, center.y, center.z);
  29324. normals.push(0, isTop ? 1 : -1, 0);
  29325. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29326. if (faceColors) {
  29327. colors.push(c.r, c.g, c.b, c.a);
  29328. }
  29329. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29330. for (i = 0; i <= tessellation; i++) {
  29331. angle = Math.PI * 2 * i * arc / tessellation;
  29332. var cos = Math.cos(-angle);
  29333. var sin = Math.sin(-angle);
  29334. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29335. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29336. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29337. normals.push(0, isTop ? 1 : -1, 0);
  29338. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29339. if (faceColors) {
  29340. colors.push(c.r, c.g, c.b, c.a);
  29341. }
  29342. }
  29343. // Cap indices
  29344. for (i = 0; i < tessellation; i++) {
  29345. if (!isTop) {
  29346. indices.push(vbase);
  29347. indices.push(vbase + (i + 1));
  29348. indices.push(vbase + (i + 2));
  29349. }
  29350. else {
  29351. indices.push(vbase);
  29352. indices.push(vbase + (i + 2));
  29353. indices.push(vbase + (i + 1));
  29354. }
  29355. }
  29356. };
  29357. // add caps to geometry
  29358. createCylinderCap(false);
  29359. createCylinderCap(true);
  29360. // Sides
  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. if (faceColors) {
  29368. vertexData.colors = colors;
  29369. }
  29370. return vertexData;
  29371. };
  29372. VertexData.CreateTorus = function (options) {
  29373. var indices = [];
  29374. var positions = [];
  29375. var normals = [];
  29376. var uvs = [];
  29377. var diameter = options.diameter || 1;
  29378. var thickness = options.thickness || 0.5;
  29379. var tessellation = options.tessellation || 16;
  29380. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29381. var stride = tessellation + 1;
  29382. for (var i = 0; i <= tessellation; i++) {
  29383. var u = i / tessellation;
  29384. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29385. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29386. for (var j = 0; j <= tessellation; j++) {
  29387. var v = 1 - j / tessellation;
  29388. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29389. var dx = Math.cos(innerAngle);
  29390. var dy = Math.sin(innerAngle);
  29391. // Create a vertex.
  29392. var normal = new BABYLON.Vector3(dx, dy, 0);
  29393. var position = normal.scale(thickness / 2);
  29394. var textureCoordinate = new BABYLON.Vector2(u, v);
  29395. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29396. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29397. positions.push(position.x, position.y, position.z);
  29398. normals.push(normal.x, normal.y, normal.z);
  29399. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29400. // And create indices for two triangles.
  29401. var nextI = (i + 1) % stride;
  29402. var nextJ = (j + 1) % stride;
  29403. indices.push(i * stride + j);
  29404. indices.push(i * stride + nextJ);
  29405. indices.push(nextI * stride + j);
  29406. indices.push(i * stride + nextJ);
  29407. indices.push(nextI * stride + nextJ);
  29408. indices.push(nextI * stride + j);
  29409. }
  29410. }
  29411. // Sides
  29412. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29413. // Result
  29414. var vertexData = new VertexData();
  29415. vertexData.indices = indices;
  29416. vertexData.positions = positions;
  29417. vertexData.normals = normals;
  29418. vertexData.uvs = uvs;
  29419. return vertexData;
  29420. };
  29421. VertexData.CreateLineSystem = function (options) {
  29422. var indices = [];
  29423. var positions = [];
  29424. var lines = options.lines;
  29425. var idx = 0;
  29426. for (var l = 0; l < lines.length; l++) {
  29427. var points = lines[l];
  29428. for (var index = 0; index < points.length; index++) {
  29429. positions.push(points[index].x, points[index].y, points[index].z);
  29430. if (index > 0) {
  29431. indices.push(idx - 1);
  29432. indices.push(idx);
  29433. }
  29434. idx++;
  29435. }
  29436. }
  29437. var vertexData = new VertexData();
  29438. vertexData.indices = indices;
  29439. vertexData.positions = positions;
  29440. return vertexData;
  29441. };
  29442. VertexData.CreateDashedLines = function (options) {
  29443. var dashSize = options.dashSize || 3;
  29444. var gapSize = options.gapSize || 1;
  29445. var dashNb = options.dashNb || 200;
  29446. var points = options.points;
  29447. var positions = new Array();
  29448. var indices = new Array();
  29449. var curvect = BABYLON.Vector3.Zero();
  29450. var lg = 0;
  29451. var nb = 0;
  29452. var shft = 0;
  29453. var dashshft = 0;
  29454. var curshft = 0;
  29455. var idx = 0;
  29456. var i = 0;
  29457. for (i = 0; i < points.length - 1; i++) {
  29458. points[i + 1].subtractToRef(points[i], curvect);
  29459. lg += curvect.length();
  29460. }
  29461. shft = lg / dashNb;
  29462. dashshft = dashSize * shft / (dashSize + gapSize);
  29463. for (i = 0; i < points.length - 1; i++) {
  29464. points[i + 1].subtractToRef(points[i], curvect);
  29465. nb = Math.floor(curvect.length() / shft);
  29466. curvect.normalize();
  29467. for (var j = 0; j < nb; j++) {
  29468. curshft = shft * j;
  29469. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29470. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29471. indices.push(idx, idx + 1);
  29472. idx += 2;
  29473. }
  29474. }
  29475. // Result
  29476. var vertexData = new VertexData();
  29477. vertexData.positions = positions;
  29478. vertexData.indices = indices;
  29479. return vertexData;
  29480. };
  29481. VertexData.CreateGround = function (options) {
  29482. var indices = [];
  29483. var positions = [];
  29484. var normals = [];
  29485. var uvs = [];
  29486. var row, col;
  29487. var width = options.width || 1;
  29488. var height = options.height || 1;
  29489. var subdivisions = options.subdivisions || 1;
  29490. for (row = 0; row <= subdivisions; row++) {
  29491. for (col = 0; col <= subdivisions; col++) {
  29492. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  29493. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29494. positions.push(position.x, position.y, position.z);
  29495. normals.push(normal.x, normal.y, normal.z);
  29496. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  29497. }
  29498. }
  29499. for (row = 0; row < subdivisions; row++) {
  29500. for (col = 0; col < subdivisions; col++) {
  29501. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29502. indices.push(col + 1 + row * (subdivisions + 1));
  29503. indices.push(col + row * (subdivisions + 1));
  29504. indices.push(col + (row + 1) * (subdivisions + 1));
  29505. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29506. indices.push(col + row * (subdivisions + 1));
  29507. }
  29508. }
  29509. // Result
  29510. var vertexData = new VertexData();
  29511. vertexData.indices = indices;
  29512. vertexData.positions = positions;
  29513. vertexData.normals = normals;
  29514. vertexData.uvs = uvs;
  29515. return vertexData;
  29516. };
  29517. VertexData.CreateTiledGround = function (options) {
  29518. var xmin = options.xmin;
  29519. var zmin = options.zmin;
  29520. var xmax = options.xmax;
  29521. var zmax = options.zmax;
  29522. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29523. var precision = options.precision || { w: 1, h: 1 };
  29524. var indices = [];
  29525. var positions = [];
  29526. var normals = [];
  29527. var uvs = [];
  29528. var row, col, tileRow, tileCol;
  29529. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  29530. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29531. precision.w = (precision.w < 1) ? 1 : precision.w;
  29532. precision.h = (precision.h < 1) ? 1 : precision.h;
  29533. var tileSize = {
  29534. 'w': (xmax - xmin) / subdivisions.w,
  29535. 'h': (zmax - zmin) / subdivisions.h
  29536. };
  29537. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29538. // Indices
  29539. var base = positions.length / 3;
  29540. var rowLength = precision.w + 1;
  29541. for (row = 0; row < precision.h; row++) {
  29542. for (col = 0; col < precision.w; col++) {
  29543. var square = [
  29544. base + col + row * rowLength,
  29545. base + (col + 1) + row * rowLength,
  29546. base + (col + 1) + (row + 1) * rowLength,
  29547. base + col + (row + 1) * rowLength
  29548. ];
  29549. indices.push(square[1]);
  29550. indices.push(square[2]);
  29551. indices.push(square[3]);
  29552. indices.push(square[0]);
  29553. indices.push(square[1]);
  29554. indices.push(square[3]);
  29555. }
  29556. }
  29557. // Position, normals and uvs
  29558. var position = BABYLON.Vector3.Zero();
  29559. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29560. for (row = 0; row <= precision.h; row++) {
  29561. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29562. for (col = 0; col <= precision.w; col++) {
  29563. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29564. position.y = 0;
  29565. positions.push(position.x, position.y, position.z);
  29566. normals.push(normal.x, normal.y, normal.z);
  29567. uvs.push(col / precision.w, row / precision.h);
  29568. }
  29569. }
  29570. }
  29571. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29572. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29573. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29574. }
  29575. }
  29576. // Result
  29577. var vertexData = new VertexData();
  29578. vertexData.indices = indices;
  29579. vertexData.positions = positions;
  29580. vertexData.normals = normals;
  29581. vertexData.uvs = uvs;
  29582. return vertexData;
  29583. };
  29584. VertexData.CreateGroundFromHeightMap = function (options) {
  29585. var indices = [];
  29586. var positions = [];
  29587. var normals = [];
  29588. var uvs = [];
  29589. var row, col;
  29590. // Vertices
  29591. for (row = 0; row <= options.subdivisions; row++) {
  29592. for (col = 0; col <= options.subdivisions; col++) {
  29593. 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));
  29594. // Compute height
  29595. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29596. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29597. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29598. var r = options.buffer[pos] / 255.0;
  29599. var g = options.buffer[pos + 1] / 255.0;
  29600. var b = options.buffer[pos + 2] / 255.0;
  29601. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29602. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29603. // Add vertex
  29604. positions.push(position.x, position.y, position.z);
  29605. normals.push(0, 0, 0);
  29606. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29607. }
  29608. }
  29609. // Indices
  29610. for (row = 0; row < options.subdivisions; row++) {
  29611. for (col = 0; col < options.subdivisions; col++) {
  29612. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29613. indices.push(col + 1 + row * (options.subdivisions + 1));
  29614. indices.push(col + row * (options.subdivisions + 1));
  29615. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29616. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29617. indices.push(col + row * (options.subdivisions + 1));
  29618. }
  29619. }
  29620. // Normals
  29621. VertexData.ComputeNormals(positions, indices, normals);
  29622. // Result
  29623. var vertexData = new VertexData();
  29624. vertexData.indices = indices;
  29625. vertexData.positions = positions;
  29626. vertexData.normals = normals;
  29627. vertexData.uvs = uvs;
  29628. return vertexData;
  29629. };
  29630. VertexData.CreatePlane = function (options) {
  29631. var indices = [];
  29632. var positions = [];
  29633. var normals = [];
  29634. var uvs = [];
  29635. var width = options.width || options.size || 1;
  29636. var height = options.height || options.size || 1;
  29637. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29638. // Vertices
  29639. var halfWidth = width / 2.0;
  29640. var halfHeight = height / 2.0;
  29641. positions.push(-halfWidth, -halfHeight, 0);
  29642. normals.push(0, 0, -1.0);
  29643. uvs.push(0.0, 0.0);
  29644. positions.push(halfWidth, -halfHeight, 0);
  29645. normals.push(0, 0, -1.0);
  29646. uvs.push(1.0, 0.0);
  29647. positions.push(halfWidth, halfHeight, 0);
  29648. normals.push(0, 0, -1.0);
  29649. uvs.push(1.0, 1.0);
  29650. positions.push(-halfWidth, halfHeight, 0);
  29651. normals.push(0, 0, -1.0);
  29652. uvs.push(0.0, 1.0);
  29653. // Indices
  29654. indices.push(0);
  29655. indices.push(1);
  29656. indices.push(2);
  29657. indices.push(0);
  29658. indices.push(2);
  29659. indices.push(3);
  29660. // Sides
  29661. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29662. // Result
  29663. var vertexData = new VertexData();
  29664. vertexData.indices = indices;
  29665. vertexData.positions = positions;
  29666. vertexData.normals = normals;
  29667. vertexData.uvs = uvs;
  29668. return vertexData;
  29669. };
  29670. VertexData.CreateDisc = function (options) {
  29671. var positions = [];
  29672. var indices = [];
  29673. var normals = [];
  29674. var uvs = [];
  29675. var radius = options.radius || 0.5;
  29676. var tessellation = options.tessellation || 64;
  29677. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29678. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29679. // positions and uvs
  29680. positions.push(0, 0, 0); // disc center first
  29681. uvs.push(0.5, 0.5);
  29682. var theta = Math.PI * 2 * arc;
  29683. var step = theta / tessellation;
  29684. for (var a = 0; a < theta; a += step) {
  29685. var x = Math.cos(a);
  29686. var y = Math.sin(a);
  29687. var u = (x + 1) / 2;
  29688. var v = (1 - y) / 2;
  29689. positions.push(radius * x, radius * y, 0);
  29690. uvs.push(u, v);
  29691. }
  29692. if (arc === 1) {
  29693. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29694. uvs.push(uvs[2], uvs[3]);
  29695. }
  29696. //indices
  29697. var vertexNb = positions.length / 3;
  29698. for (var i = 1; i < vertexNb - 1; i++) {
  29699. indices.push(i + 1, 0, i);
  29700. }
  29701. // result
  29702. VertexData.ComputeNormals(positions, indices, normals);
  29703. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29704. var vertexData = new VertexData();
  29705. vertexData.indices = indices;
  29706. vertexData.positions = positions;
  29707. vertexData.normals = normals;
  29708. vertexData.uvs = uvs;
  29709. return vertexData;
  29710. };
  29711. VertexData.CreateIcoSphere = function (options) {
  29712. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29713. var radius = options.radius || 1;
  29714. var flat = (options.flat === undefined) ? true : options.flat;
  29715. var subdivisions = options.subdivisions || 4;
  29716. var radiusX = options.radiusX || radius;
  29717. var radiusY = options.radiusY || radius;
  29718. var radiusZ = options.radiusZ || radius;
  29719. var t = (1 + Math.sqrt(5)) / 2;
  29720. // 12 vertex x,y,z
  29721. var ico_vertices = [
  29722. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29723. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29724. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29725. ];
  29726. // index of 3 vertex makes a face of icopshere
  29727. var ico_indices = [
  29728. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29729. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29730. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29731. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29732. ];
  29733. // vertex for uv have aliased position, not for UV
  29734. var vertices_unalias_id = [
  29735. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29736. // vertex alias
  29737. 0,
  29738. 2,
  29739. 3,
  29740. 3,
  29741. 3,
  29742. 4,
  29743. 7,
  29744. 8,
  29745. 9,
  29746. 9,
  29747. 10,
  29748. 11 // 23: B + 12
  29749. ];
  29750. // uv as integer step (not pixels !)
  29751. var ico_vertexuv = [
  29752. 5, 1, 3, 1, 6, 4, 0, 0,
  29753. 5, 3, 4, 2, 2, 2, 4, 0,
  29754. 2, 0, 1, 1, 6, 0, 6, 2,
  29755. // vertex alias (for same vertex on different faces)
  29756. 0, 4,
  29757. 3, 3,
  29758. 4, 4,
  29759. 3, 1,
  29760. 4, 2,
  29761. 4, 4,
  29762. 0, 2,
  29763. 1, 1,
  29764. 2, 2,
  29765. 3, 3,
  29766. 1, 3,
  29767. 2, 4 // 23: B + 12
  29768. ];
  29769. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29770. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29771. // First island of uv mapping
  29772. // v = 4h 3+ 2
  29773. // v = 3h 9+ 4
  29774. // v = 2h 9+ 5 B
  29775. // v = 1h 9 1 0
  29776. // v = 0h 3 8 7 A
  29777. // u = 0 1 2 3 4 5 6 *a
  29778. // Second island of uv mapping
  29779. // v = 4h 0+ B+ 4+
  29780. // v = 3h A+ 2+
  29781. // v = 2h 7+ 6 3+
  29782. // v = 1h 8+ 3+
  29783. // v = 0h
  29784. // u = 0 1 2 3 4 5 6 *a
  29785. // Face layout on texture UV mapping
  29786. // ============
  29787. // \ 4 /\ 16 / ======
  29788. // \ / \ / /\ 11 /
  29789. // \/ 7 \/ / \ /
  29790. // ======= / 10 \/
  29791. // /\ 17 /\ =======
  29792. // / \ / \ \ 15 /\
  29793. // / 8 \/ 12 \ \ / \
  29794. // ============ \/ 6 \
  29795. // \ 18 /\ ============
  29796. // \ / \ \ 5 /\ 0 /
  29797. // \/ 13 \ \ / \ /
  29798. // ======= \/ 1 \/
  29799. // =============
  29800. // /\ 19 /\ 2 /\
  29801. // / \ / \ / \
  29802. // / 14 \/ 9 \/ 3 \
  29803. // ===================
  29804. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29805. var ustep = 138 / 1024;
  29806. var vstep = 239 / 1024;
  29807. var uoffset = 60 / 1024;
  29808. var voffset = 26 / 1024;
  29809. // Second island should have margin, not to touch the first island
  29810. // avoid any borderline artefact in pixel rounding
  29811. var island_u_offset = -40 / 1024;
  29812. var island_v_offset = +20 / 1024;
  29813. // face is either island 0 or 1 :
  29814. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29815. var island = [
  29816. 0, 0, 0, 0, 1,
  29817. 0, 0, 1, 1, 0,
  29818. 0, 0, 1, 1, 0,
  29819. 0, 1, 1, 1, 0 // 15 - 19
  29820. ];
  29821. var indices = [];
  29822. var positions = [];
  29823. var normals = [];
  29824. var uvs = [];
  29825. var current_indice = 0;
  29826. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29827. var face_vertex_pos = new Array(3);
  29828. var face_vertex_uv = new Array(3);
  29829. var v012;
  29830. for (v012 = 0; v012 < 3; v012++) {
  29831. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29832. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29833. }
  29834. // create all with normals
  29835. for (var face = 0; face < 20; face++) {
  29836. // 3 vertex per face
  29837. for (v012 = 0; v012 < 3; v012++) {
  29838. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29839. var v_id = ico_indices[3 * face + v012];
  29840. // vertex have 3D position (x,y,z)
  29841. 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]);
  29842. // Normalize to get normal, then scale to radius
  29843. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29844. // uv Coordinates from vertex ID
  29845. 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);
  29846. }
  29847. // Subdivide the face (interpolate pos, norm, uv)
  29848. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29849. // - norm is linear interpolation of vertex corner normal
  29850. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29851. // - uv is linear interpolation
  29852. //
  29853. // Topology is as below for sub-divide by 2
  29854. // vertex shown as v0,v1,v2
  29855. // interp index is i1 to progress in range [v0,v1[
  29856. // interp index is i2 to progress in range [v0,v2[
  29857. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29858. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29859. //
  29860. //
  29861. // i2 v2
  29862. // ^ ^
  29863. // / / \
  29864. // / / \
  29865. // / / \
  29866. // / / (0,1) \
  29867. // / #---------\
  29868. // / / \ (0,0)'/ \
  29869. // / / \ / \
  29870. // / / \ / \
  29871. // / / (0,0) \ / (1,0) \
  29872. // / #---------#---------\
  29873. // v0 v1
  29874. //
  29875. // --------------------> i1
  29876. //
  29877. // interp of (i1,i2):
  29878. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29879. // along i1 : lerp(x0,x1, i1/(S-i2))
  29880. //
  29881. // centroid of triangle is needed to get help normal computation
  29882. // (c1,c2) are used for centroid location
  29883. var interp_vertex = function (i1, i2, c1, c2) {
  29884. // vertex is interpolated from
  29885. // - face_vertex_pos[0..2]
  29886. // - face_vertex_uv[0..2]
  29887. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29888. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29889. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29890. pos_interp.normalize();
  29891. var vertex_normal;
  29892. if (flat) {
  29893. // in flat mode, recalculate normal as face centroid normal
  29894. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29895. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29896. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29897. }
  29898. else {
  29899. // in smooth mode, recalculate normal from each single vertex position
  29900. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29901. }
  29902. // Vertex normal need correction due to X,Y,Z radius scaling
  29903. vertex_normal.x /= radiusX;
  29904. vertex_normal.y /= radiusY;
  29905. vertex_normal.z /= radiusZ;
  29906. vertex_normal.normalize();
  29907. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29908. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29909. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29910. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29911. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29912. uvs.push(uv_interp.x, uv_interp.y);
  29913. // push each vertex has member of a face
  29914. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29915. indices.push(current_indice);
  29916. current_indice++;
  29917. };
  29918. for (var i2 = 0; i2 < subdivisions; i2++) {
  29919. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29920. // face : (i1,i2) for /\ :
  29921. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29922. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29923. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29924. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29925. if (i1 + i2 + 1 < subdivisions) {
  29926. // face : (i1,i2)' for \/ :
  29927. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29928. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29929. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29930. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29931. }
  29932. }
  29933. }
  29934. }
  29935. // Sides
  29936. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29937. // Result
  29938. var vertexData = new VertexData();
  29939. vertexData.indices = indices;
  29940. vertexData.positions = positions;
  29941. vertexData.normals = normals;
  29942. vertexData.uvs = uvs;
  29943. return vertexData;
  29944. };
  29945. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29946. VertexData.CreatePolyhedron = function (options) {
  29947. // provided polyhedron types :
  29948. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29949. // 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)
  29950. var polyhedra = [];
  29951. 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]] };
  29952. 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]] };
  29953. polyhedra[2] = {
  29954. 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]],
  29955. 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]]
  29956. };
  29957. polyhedra[3] = {
  29958. 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]],
  29959. 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]]
  29960. };
  29961. polyhedra[4] = {
  29962. 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]],
  29963. 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]]
  29964. };
  29965. 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]] };
  29966. 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]] };
  29967. 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]] };
  29968. 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]] };
  29969. 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]] };
  29970. 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]] };
  29971. 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]] };
  29972. 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]] };
  29973. 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]] };
  29974. polyhedra[14] = {
  29975. 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]],
  29976. 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]]
  29977. };
  29978. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29979. var size = options.size;
  29980. var sizeX = options.sizeX || size || 1;
  29981. var sizeY = options.sizeY || size || 1;
  29982. var sizeZ = options.sizeZ || size || 1;
  29983. var data = options.custom || polyhedra[type];
  29984. var nbfaces = data.face.length;
  29985. var faceUV = options.faceUV || new Array(nbfaces);
  29986. var faceColors = options.faceColors;
  29987. var flat = (options.flat === undefined) ? true : options.flat;
  29988. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29989. var positions = [];
  29990. var indices = [];
  29991. var normals = [];
  29992. var uvs = [];
  29993. var colors = [];
  29994. var index = 0;
  29995. var faceIdx = 0; // face cursor in the array "indexes"
  29996. var indexes = [];
  29997. var i = 0;
  29998. var f = 0;
  29999. var u, v, ang, x, y, tmp;
  30000. // default face colors and UV if undefined
  30001. if (flat) {
  30002. for (f = 0; f < nbfaces; f++) {
  30003. if (faceColors && faceColors[f] === undefined) {
  30004. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30005. }
  30006. if (faceUV && faceUV[f] === undefined) {
  30007. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30008. }
  30009. }
  30010. }
  30011. if (!flat) {
  30012. for (i = 0; i < data.vertex.length; i++) {
  30013. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30014. uvs.push(0, 0);
  30015. }
  30016. for (f = 0; f < nbfaces; f++) {
  30017. for (i = 0; i < data.face[f].length - 2; i++) {
  30018. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30019. }
  30020. }
  30021. }
  30022. else {
  30023. for (f = 0; f < nbfaces; f++) {
  30024. var fl = data.face[f].length; // number of vertices of the current face
  30025. ang = 2 * Math.PI / fl;
  30026. x = 0.5 * Math.tan(ang / 2);
  30027. y = 0.5;
  30028. // positions, uvs, colors
  30029. for (i = 0; i < fl; i++) {
  30030. // positions
  30031. 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);
  30032. indexes.push(index);
  30033. index++;
  30034. // uvs
  30035. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30036. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30037. uvs.push(u, v);
  30038. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30039. y = x * Math.sin(ang) + y * Math.cos(ang);
  30040. x = tmp;
  30041. // colors
  30042. if (faceColors) {
  30043. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30044. }
  30045. }
  30046. // indices from indexes
  30047. for (i = 0; i < fl - 2; i++) {
  30048. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30049. }
  30050. faceIdx += fl;
  30051. }
  30052. }
  30053. VertexData.ComputeNormals(positions, indices, normals);
  30054. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30055. var vertexData = new VertexData();
  30056. vertexData.positions = positions;
  30057. vertexData.indices = indices;
  30058. vertexData.normals = normals;
  30059. vertexData.uvs = uvs;
  30060. if (faceColors && flat) {
  30061. vertexData.colors = colors;
  30062. }
  30063. return vertexData;
  30064. };
  30065. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30066. VertexData.CreateTorusKnot = function (options) {
  30067. var indices = [];
  30068. var positions = [];
  30069. var normals = [];
  30070. var uvs = [];
  30071. var radius = options.radius || 2;
  30072. var tube = options.tube || 0.5;
  30073. var radialSegments = options.radialSegments || 32;
  30074. var tubularSegments = options.tubularSegments || 32;
  30075. var p = options.p || 2;
  30076. var q = options.q || 3;
  30077. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30078. // Helper
  30079. var getPos = function (angle) {
  30080. var cu = Math.cos(angle);
  30081. var su = Math.sin(angle);
  30082. var quOverP = q / p * angle;
  30083. var cs = Math.cos(quOverP);
  30084. var tx = radius * (2 + cs) * 0.5 * cu;
  30085. var ty = radius * (2 + cs) * su * 0.5;
  30086. var tz = radius * Math.sin(quOverP) * 0.5;
  30087. return new BABYLON.Vector3(tx, ty, tz);
  30088. };
  30089. // Vertices
  30090. var i;
  30091. var j;
  30092. for (i = 0; i <= radialSegments; i++) {
  30093. var modI = i % radialSegments;
  30094. var u = modI / radialSegments * 2 * p * Math.PI;
  30095. var p1 = getPos(u);
  30096. var p2 = getPos(u + 0.01);
  30097. var tang = p2.subtract(p1);
  30098. var n = p2.add(p1);
  30099. var bitan = BABYLON.Vector3.Cross(tang, n);
  30100. n = BABYLON.Vector3.Cross(bitan, tang);
  30101. bitan.normalize();
  30102. n.normalize();
  30103. for (j = 0; j < tubularSegments; j++) {
  30104. var modJ = j % tubularSegments;
  30105. var v = modJ / tubularSegments * 2 * Math.PI;
  30106. var cx = -tube * Math.cos(v);
  30107. var cy = tube * Math.sin(v);
  30108. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30109. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30110. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30111. uvs.push(i / radialSegments);
  30112. uvs.push(j / tubularSegments);
  30113. }
  30114. }
  30115. for (i = 0; i < radialSegments; i++) {
  30116. for (j = 0; j < tubularSegments; j++) {
  30117. var jNext = (j + 1) % tubularSegments;
  30118. var a = i * tubularSegments + j;
  30119. var b = (i + 1) * tubularSegments + j;
  30120. var c = (i + 1) * tubularSegments + jNext;
  30121. var d = i * tubularSegments + jNext;
  30122. indices.push(d);
  30123. indices.push(b);
  30124. indices.push(a);
  30125. indices.push(d);
  30126. indices.push(c);
  30127. indices.push(b);
  30128. }
  30129. }
  30130. // Normals
  30131. VertexData.ComputeNormals(positions, indices, normals);
  30132. // Sides
  30133. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30134. // Result
  30135. var vertexData = new VertexData();
  30136. vertexData.indices = indices;
  30137. vertexData.positions = positions;
  30138. vertexData.normals = normals;
  30139. vertexData.uvs = uvs;
  30140. return vertexData;
  30141. };
  30142. // Tools
  30143. /**
  30144. * @param {any} - positions (number[] or Float32Array)
  30145. * @param {any} - indices (number[] or Uint16Array)
  30146. * @param {any} - normals (number[] or Float32Array)
  30147. */
  30148. VertexData.ComputeNormals = function (positions, indices, normals) {
  30149. var index = 0;
  30150. var p1p2x = 0.0;
  30151. var p1p2y = 0.0;
  30152. var p1p2z = 0.0;
  30153. var p3p2x = 0.0;
  30154. var p3p2y = 0.0;
  30155. var p3p2z = 0.0;
  30156. var faceNormalx = 0.0;
  30157. var faceNormaly = 0.0;
  30158. var faceNormalz = 0.0;
  30159. var length = 0.0;
  30160. var i1 = 0;
  30161. var i2 = 0;
  30162. var i3 = 0;
  30163. for (index = 0; index < positions.length; index++) {
  30164. normals[index] = 0.0;
  30165. }
  30166. // indice triplet = 1 face
  30167. var nbFaces = indices.length / 3;
  30168. for (index = 0; index < nbFaces; index++) {
  30169. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  30170. i2 = indices[index * 3 + 1];
  30171. i3 = indices[index * 3 + 2];
  30172. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  30173. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  30174. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  30175. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  30176. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  30177. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  30178. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  30179. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  30180. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  30181. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30182. length = (length === 0) ? 1.0 : length;
  30183. faceNormalx /= length; // normalize this normal
  30184. faceNormaly /= length;
  30185. faceNormalz /= length;
  30186. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  30187. normals[i1 * 3 + 1] += faceNormaly;
  30188. normals[i1 * 3 + 2] += faceNormalz;
  30189. normals[i2 * 3] += faceNormalx;
  30190. normals[i2 * 3 + 1] += faceNormaly;
  30191. normals[i2 * 3 + 2] += faceNormalz;
  30192. normals[i3 * 3] += faceNormalx;
  30193. normals[i3 * 3 + 1] += faceNormaly;
  30194. normals[i3 * 3 + 2] += faceNormalz;
  30195. }
  30196. // last normalization of each normal
  30197. for (index = 0; index < normals.length / 3; index++) {
  30198. faceNormalx = normals[index * 3];
  30199. faceNormaly = normals[index * 3 + 1];
  30200. faceNormalz = normals[index * 3 + 2];
  30201. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30202. length = (length === 0) ? 1.0 : length;
  30203. faceNormalx /= length;
  30204. faceNormaly /= length;
  30205. faceNormalz /= length;
  30206. normals[index * 3] = faceNormalx;
  30207. normals[index * 3 + 1] = faceNormaly;
  30208. normals[index * 3 + 2] = faceNormalz;
  30209. }
  30210. };
  30211. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  30212. var li = indices.length;
  30213. var ln = normals.length;
  30214. var i;
  30215. var n;
  30216. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30217. switch (sideOrientation) {
  30218. case BABYLON.Mesh.FRONTSIDE:
  30219. // nothing changed
  30220. break;
  30221. case BABYLON.Mesh.BACKSIDE:
  30222. var tmp;
  30223. // indices
  30224. for (i = 0; i < li; i += 3) {
  30225. tmp = indices[i];
  30226. indices[i] = indices[i + 2];
  30227. indices[i + 2] = tmp;
  30228. }
  30229. // normals
  30230. for (n = 0; n < ln; n++) {
  30231. normals[n] = -normals[n];
  30232. }
  30233. break;
  30234. case BABYLON.Mesh.DOUBLESIDE:
  30235. // positions
  30236. var lp = positions.length;
  30237. var l = lp / 3;
  30238. for (var p = 0; p < lp; p++) {
  30239. positions[lp + p] = positions[p];
  30240. }
  30241. // indices
  30242. for (i = 0; i < li; i += 3) {
  30243. indices[i + li] = indices[i + 2] + l;
  30244. indices[i + 1 + li] = indices[i + 1] + l;
  30245. indices[i + 2 + li] = indices[i] + l;
  30246. }
  30247. // normals
  30248. for (n = 0; n < ln; n++) {
  30249. normals[ln + n] = -normals[n];
  30250. }
  30251. // uvs
  30252. var lu = uvs.length;
  30253. for (var u = 0; u < lu; u++) {
  30254. uvs[u + lu] = uvs[u];
  30255. }
  30256. break;
  30257. }
  30258. };
  30259. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30260. var vertexData = new VertexData();
  30261. // positions
  30262. var positions = parsedVertexData.positions;
  30263. if (positions) {
  30264. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30265. }
  30266. // normals
  30267. var normals = parsedVertexData.normals;
  30268. if (normals) {
  30269. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30270. }
  30271. // uvs
  30272. var uvs = parsedVertexData.uvs;
  30273. if (uvs) {
  30274. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30275. }
  30276. // uv2s
  30277. var uv2s = parsedVertexData.uv2s;
  30278. if (uv2s) {
  30279. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30280. }
  30281. // uv3s
  30282. var uv3s = parsedVertexData.uv3s;
  30283. if (uv3s) {
  30284. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30285. }
  30286. // uv4s
  30287. var uv4s = parsedVertexData.uv4s;
  30288. if (uv4s) {
  30289. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30290. }
  30291. // uv5s
  30292. var uv5s = parsedVertexData.uv5s;
  30293. if (uv5s) {
  30294. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30295. }
  30296. // uv6s
  30297. var uv6s = parsedVertexData.uv6s;
  30298. if (uv6s) {
  30299. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30300. }
  30301. // colors
  30302. var colors = parsedVertexData.colors;
  30303. if (colors) {
  30304. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30305. }
  30306. // matricesIndices
  30307. var matricesIndices = parsedVertexData.matricesIndices;
  30308. if (matricesIndices) {
  30309. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30310. }
  30311. // matricesWeights
  30312. var matricesWeights = parsedVertexData.matricesWeights;
  30313. if (matricesWeights) {
  30314. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30315. }
  30316. // indices
  30317. var indices = parsedVertexData.indices;
  30318. if (indices) {
  30319. vertexData.indices = indices;
  30320. }
  30321. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30322. };
  30323. return VertexData;
  30324. })();
  30325. BABYLON.VertexData = VertexData;
  30326. })(BABYLON || (BABYLON = {}));
  30327. var BABYLON;
  30328. (function (BABYLON) {
  30329. var Tags = (function () {
  30330. function Tags() {
  30331. }
  30332. Tags.EnableFor = function (obj) {
  30333. obj._tags = obj._tags || {};
  30334. obj.hasTags = function () {
  30335. return Tags.HasTags(obj);
  30336. };
  30337. obj.addTags = function (tagsString) {
  30338. return Tags.AddTagsTo(obj, tagsString);
  30339. };
  30340. obj.removeTags = function (tagsString) {
  30341. return Tags.RemoveTagsFrom(obj, tagsString);
  30342. };
  30343. obj.matchesTagsQuery = function (tagsQuery) {
  30344. return Tags.MatchesQuery(obj, tagsQuery);
  30345. };
  30346. };
  30347. Tags.DisableFor = function (obj) {
  30348. delete obj._tags;
  30349. delete obj.hasTags;
  30350. delete obj.addTags;
  30351. delete obj.removeTags;
  30352. delete obj.matchesTagsQuery;
  30353. };
  30354. Tags.HasTags = function (obj) {
  30355. if (!obj._tags) {
  30356. return false;
  30357. }
  30358. return !BABYLON.Tools.IsEmpty(obj._tags);
  30359. };
  30360. Tags.GetTags = function (obj, asString) {
  30361. if (asString === void 0) { asString = true; }
  30362. if (!obj._tags) {
  30363. return null;
  30364. }
  30365. if (asString) {
  30366. var tagsArray = [];
  30367. for (var tag in obj._tags) {
  30368. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  30369. tagsArray.push(tag);
  30370. }
  30371. }
  30372. return tagsArray.join(" ");
  30373. }
  30374. else {
  30375. return obj._tags;
  30376. }
  30377. };
  30378. // the tags 'true' and 'false' are reserved and cannot be used as tags
  30379. // a tag cannot start with '||', '&&', and '!'
  30380. // it cannot contain whitespaces
  30381. Tags.AddTagsTo = function (obj, tagsString) {
  30382. if (!tagsString) {
  30383. return;
  30384. }
  30385. if (typeof tagsString !== "string") {
  30386. return;
  30387. }
  30388. var tags = tagsString.split(" ");
  30389. for (var t in tags) {
  30390. Tags._AddTagTo(obj, tags[t]);
  30391. }
  30392. };
  30393. Tags._AddTagTo = function (obj, tag) {
  30394. tag = tag.trim();
  30395. if (tag === "" || tag === "true" || tag === "false") {
  30396. return;
  30397. }
  30398. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  30399. return;
  30400. }
  30401. Tags.EnableFor(obj);
  30402. obj._tags[tag] = true;
  30403. };
  30404. Tags.RemoveTagsFrom = function (obj, tagsString) {
  30405. if (!Tags.HasTags(obj)) {
  30406. return;
  30407. }
  30408. var tags = tagsString.split(" ");
  30409. for (var t in tags) {
  30410. Tags._RemoveTagFrom(obj, tags[t]);
  30411. }
  30412. };
  30413. Tags._RemoveTagFrom = function (obj, tag) {
  30414. delete obj._tags[tag];
  30415. };
  30416. Tags.MatchesQuery = function (obj, tagsQuery) {
  30417. if (tagsQuery === undefined) {
  30418. return true;
  30419. }
  30420. if (tagsQuery === "") {
  30421. return Tags.HasTags(obj);
  30422. }
  30423. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  30424. };
  30425. return Tags;
  30426. })();
  30427. BABYLON.Tags = Tags;
  30428. })(BABYLON || (BABYLON = {}));
  30429. var BABYLON;
  30430. (function (BABYLON) {
  30431. var Internals;
  30432. (function (Internals) {
  30433. var AndOrNotEvaluator = (function () {
  30434. function AndOrNotEvaluator() {
  30435. }
  30436. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  30437. if (!query.match(/\([^\(\)]*\)/g)) {
  30438. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  30439. }
  30440. else {
  30441. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  30442. // remove parenthesis
  30443. r = r.slice(1, r.length - 1);
  30444. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  30445. });
  30446. }
  30447. if (query === "true") {
  30448. return true;
  30449. }
  30450. if (query === "false") {
  30451. return false;
  30452. }
  30453. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  30454. };
  30455. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  30456. evaluateCallback = evaluateCallback || (function (r) {
  30457. return r === "true" ? true : false;
  30458. });
  30459. var result;
  30460. var or = parenthesisContent.split("||");
  30461. for (var i in or) {
  30462. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  30463. var and = ori.split("&&");
  30464. if (and.length > 1) {
  30465. for (var j = 0; j < and.length; ++j) {
  30466. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  30467. if (andj !== "true" && andj !== "false") {
  30468. if (andj[0] === "!") {
  30469. result = !evaluateCallback(andj.substring(1));
  30470. }
  30471. else {
  30472. result = evaluateCallback(andj);
  30473. }
  30474. }
  30475. else {
  30476. result = andj === "true" ? true : false;
  30477. }
  30478. if (!result) {
  30479. ori = "false";
  30480. break;
  30481. }
  30482. }
  30483. }
  30484. if (result || ori === "true") {
  30485. result = true;
  30486. break;
  30487. }
  30488. // result equals false (or undefined)
  30489. if (ori !== "true" && ori !== "false") {
  30490. if (ori[0] === "!") {
  30491. result = !evaluateCallback(ori.substring(1));
  30492. }
  30493. else {
  30494. result = evaluateCallback(ori);
  30495. }
  30496. }
  30497. else {
  30498. result = ori === "true" ? true : false;
  30499. }
  30500. }
  30501. // the whole parenthesis scope is replaced by 'true' or 'false'
  30502. return result ? "true" : "false";
  30503. };
  30504. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  30505. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  30506. // remove whitespaces
  30507. r = r.replace(/[\s]/g, function () { return ""; });
  30508. return r.length % 2 ? "!" : "";
  30509. });
  30510. booleanString = booleanString.trim();
  30511. if (booleanString === "!true") {
  30512. booleanString = "false";
  30513. }
  30514. else if (booleanString === "!false") {
  30515. booleanString = "true";
  30516. }
  30517. return booleanString;
  30518. };
  30519. return AndOrNotEvaluator;
  30520. })();
  30521. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  30522. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30523. })(BABYLON || (BABYLON = {}));
  30524. var BABYLON;
  30525. (function (BABYLON) {
  30526. var PostProcessRenderPass = (function () {
  30527. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  30528. this._enabled = true;
  30529. this._refCount = 0;
  30530. this._name = name;
  30531. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  30532. this.setRenderList(renderList);
  30533. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  30534. this._renderTexture.onAfterRenderObservable.add(afterRender);
  30535. this._scene = scene;
  30536. this._renderList = renderList;
  30537. }
  30538. // private
  30539. PostProcessRenderPass.prototype._incRefCount = function () {
  30540. if (this._refCount === 0) {
  30541. this._scene.customRenderTargets.push(this._renderTexture);
  30542. }
  30543. return ++this._refCount;
  30544. };
  30545. PostProcessRenderPass.prototype._decRefCount = function () {
  30546. this._refCount--;
  30547. if (this._refCount <= 0) {
  30548. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  30549. }
  30550. return this._refCount;
  30551. };
  30552. PostProcessRenderPass.prototype._update = function () {
  30553. this.setRenderList(this._renderList);
  30554. };
  30555. // public
  30556. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  30557. this._renderTexture.renderList = renderList;
  30558. };
  30559. PostProcessRenderPass.prototype.getRenderTexture = function () {
  30560. return this._renderTexture;
  30561. };
  30562. return PostProcessRenderPass;
  30563. })();
  30564. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  30565. })(BABYLON || (BABYLON = {}));
  30566. var BABYLON;
  30567. (function (BABYLON) {
  30568. var PostProcessRenderEffect = (function () {
  30569. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  30570. this._engine = engine;
  30571. this._name = name;
  30572. this._singleInstance = singleInstance || true;
  30573. this._getPostProcess = getPostProcess;
  30574. this._cameras = [];
  30575. this._indicesForCamera = [];
  30576. this._postProcesses = {};
  30577. this._renderPasses = {};
  30578. this._renderEffectAsPasses = {};
  30579. }
  30580. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  30581. get: function () {
  30582. for (var index in this._postProcesses) {
  30583. if (!this._postProcesses[index].isSupported) {
  30584. return false;
  30585. }
  30586. }
  30587. return true;
  30588. },
  30589. enumerable: true,
  30590. configurable: true
  30591. });
  30592. PostProcessRenderEffect.prototype._update = function () {
  30593. for (var renderPassName in this._renderPasses) {
  30594. this._renderPasses[renderPassName]._update();
  30595. }
  30596. };
  30597. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  30598. this._renderPasses[renderPass._name] = renderPass;
  30599. this._linkParameters();
  30600. };
  30601. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  30602. delete this._renderPasses[renderPass._name];
  30603. this._linkParameters();
  30604. };
  30605. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  30606. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  30607. this._linkParameters();
  30608. };
  30609. PostProcessRenderEffect.prototype.getPass = function (passName) {
  30610. for (var renderPassName in this._renderPasses) {
  30611. if (renderPassName === passName) {
  30612. return this._renderPasses[passName];
  30613. }
  30614. }
  30615. };
  30616. PostProcessRenderEffect.prototype.emptyPasses = function () {
  30617. this._renderPasses = {};
  30618. this._linkParameters();
  30619. };
  30620. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  30621. var cameraKey;
  30622. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30623. for (var i = 0; i < _cam.length; i++) {
  30624. var camera = _cam[i];
  30625. var cameraName = camera.name;
  30626. if (this._singleInstance) {
  30627. cameraKey = 0;
  30628. }
  30629. else {
  30630. cameraKey = cameraName;
  30631. }
  30632. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  30633. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  30634. if (!this._indicesForCamera[cameraName]) {
  30635. this._indicesForCamera[cameraName] = [];
  30636. }
  30637. this._indicesForCamera[cameraName].push(index);
  30638. if (this._cameras.indexOf(camera) === -1) {
  30639. this._cameras[cameraName] = camera;
  30640. }
  30641. for (var passName in this._renderPasses) {
  30642. this._renderPasses[passName]._incRefCount();
  30643. }
  30644. }
  30645. this._linkParameters();
  30646. };
  30647. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  30648. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30649. for (var i = 0; i < _cam.length; i++) {
  30650. var camera = _cam[i];
  30651. var cameraName = camera.name;
  30652. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30653. var index = this._cameras.indexOf(cameraName);
  30654. this._indicesForCamera.splice(index, 1);
  30655. this._cameras.splice(index, 1);
  30656. for (var passName in this._renderPasses) {
  30657. this._renderPasses[passName]._decRefCount();
  30658. }
  30659. }
  30660. };
  30661. PostProcessRenderEffect.prototype._enable = function (cameras) {
  30662. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30663. for (var i = 0; i < _cam.length; i++) {
  30664. var camera = _cam[i];
  30665. var cameraName = camera.name;
  30666. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  30667. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  30668. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  30669. }
  30670. }
  30671. for (var passName in this._renderPasses) {
  30672. this._renderPasses[passName]._incRefCount();
  30673. }
  30674. }
  30675. };
  30676. PostProcessRenderEffect.prototype._disable = function (cameras) {
  30677. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30678. for (var i = 0; i < _cam.length; i++) {
  30679. var camera = _cam[i];
  30680. var cameraName = camera.Name;
  30681. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30682. for (var passName in this._renderPasses) {
  30683. this._renderPasses[passName]._decRefCount();
  30684. }
  30685. }
  30686. };
  30687. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  30688. if (this._singleInstance) {
  30689. return this._postProcesses[0];
  30690. }
  30691. else {
  30692. return this._postProcesses[camera.name];
  30693. }
  30694. };
  30695. PostProcessRenderEffect.prototype._linkParameters = function () {
  30696. var _this = this;
  30697. for (var index in this._postProcesses) {
  30698. if (this.applyParameters) {
  30699. this.applyParameters(this._postProcesses[index]);
  30700. }
  30701. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  30702. _this._linkTextures(effect);
  30703. });
  30704. }
  30705. };
  30706. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  30707. for (var renderPassName in this._renderPasses) {
  30708. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  30709. }
  30710. for (var renderEffectName in this._renderEffectAsPasses) {
  30711. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  30712. }
  30713. };
  30714. return PostProcessRenderEffect;
  30715. })();
  30716. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  30717. })(BABYLON || (BABYLON = {}));
  30718. var BABYLON;
  30719. (function (BABYLON) {
  30720. var PostProcessRenderPipeline = (function () {
  30721. function PostProcessRenderPipeline(engine, name) {
  30722. this._engine = engine;
  30723. this._name = name;
  30724. this._renderEffects = {};
  30725. this._renderEffectsForIsolatedPass = {};
  30726. this._cameras = [];
  30727. }
  30728. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  30729. get: function () {
  30730. for (var renderEffectName in this._renderEffects) {
  30731. if (!this._renderEffects[renderEffectName].isSupported) {
  30732. return false;
  30733. }
  30734. }
  30735. return true;
  30736. },
  30737. enumerable: true,
  30738. configurable: true
  30739. });
  30740. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  30741. this._renderEffects[renderEffect._name] = renderEffect;
  30742. };
  30743. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  30744. var renderEffects = this._renderEffects[renderEffectName];
  30745. if (!renderEffects) {
  30746. return;
  30747. }
  30748. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30749. };
  30750. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  30751. var renderEffects = this._renderEffects[renderEffectName];
  30752. if (!renderEffects) {
  30753. return;
  30754. }
  30755. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30756. };
  30757. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  30758. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30759. var indicesToDelete = [];
  30760. var i;
  30761. for (i = 0; i < _cam.length; i++) {
  30762. var camera = _cam[i];
  30763. var cameraName = camera.name;
  30764. if (this._cameras.indexOf(camera) === -1) {
  30765. this._cameras[cameraName] = camera;
  30766. }
  30767. else if (unique) {
  30768. indicesToDelete.push(i);
  30769. }
  30770. }
  30771. for (i = 0; i < indicesToDelete.length; i++) {
  30772. cameras.splice(indicesToDelete[i], 1);
  30773. }
  30774. for (var renderEffectName in this._renderEffects) {
  30775. this._renderEffects[renderEffectName]._attachCameras(_cam);
  30776. }
  30777. };
  30778. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  30779. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30780. for (var renderEffectName in this._renderEffects) {
  30781. this._renderEffects[renderEffectName]._detachCameras(_cam);
  30782. }
  30783. for (var i = 0; i < _cam.length; i++) {
  30784. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  30785. }
  30786. };
  30787. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  30788. var _this = this;
  30789. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30790. var pass = null;
  30791. var renderEffectName;
  30792. for (renderEffectName in this._renderEffects) {
  30793. pass = this._renderEffects[renderEffectName].getPass(passName);
  30794. if (pass != null) {
  30795. break;
  30796. }
  30797. }
  30798. if (pass === null) {
  30799. return;
  30800. }
  30801. for (renderEffectName in this._renderEffects) {
  30802. this._renderEffects[renderEffectName]._disable(_cam);
  30803. }
  30804. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  30805. for (var i = 0; i < _cam.length; i++) {
  30806. var camera = _cam[i];
  30807. var cameraName = camera.name;
  30808. 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); });
  30809. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  30810. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  30811. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  30812. }
  30813. };
  30814. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  30815. var _this = this;
  30816. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30817. for (var i = 0; i < _cam.length; i++) {
  30818. var camera = _cam[i];
  30819. var cameraName = camera.name;
  30820. 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); });
  30821. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  30822. }
  30823. for (var renderEffectName in this._renderEffects) {
  30824. this._renderEffects[renderEffectName]._enable(_cam);
  30825. }
  30826. };
  30827. PostProcessRenderPipeline.prototype._update = function () {
  30828. for (var renderEffectName in this._renderEffects) {
  30829. this._renderEffects[renderEffectName]._update();
  30830. }
  30831. for (var i = 0; i < this._cameras.length; i++) {
  30832. var cameraName = this._cameras[i].name;
  30833. if (this._renderEffectsForIsolatedPass[cameraName]) {
  30834. this._renderEffectsForIsolatedPass[cameraName]._update();
  30835. }
  30836. }
  30837. };
  30838. PostProcessRenderPipeline.prototype.dispose = function () {
  30839. // Must be implemented by children
  30840. };
  30841. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  30842. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  30843. return PostProcessRenderPipeline;
  30844. })();
  30845. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  30846. })(BABYLON || (BABYLON = {}));
  30847. var BABYLON;
  30848. (function (BABYLON) {
  30849. var PostProcessRenderPipelineManager = (function () {
  30850. function PostProcessRenderPipelineManager() {
  30851. this._renderPipelines = {};
  30852. }
  30853. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  30854. this._renderPipelines[renderPipeline._name] = renderPipeline;
  30855. };
  30856. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  30857. var renderPipeline = this._renderPipelines[renderPipelineName];
  30858. if (!renderPipeline) {
  30859. return;
  30860. }
  30861. renderPipeline._attachCameras(cameras, unique);
  30862. };
  30863. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  30864. var renderPipeline = this._renderPipelines[renderPipelineName];
  30865. if (!renderPipeline) {
  30866. return;
  30867. }
  30868. renderPipeline._detachCameras(cameras);
  30869. };
  30870. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30871. var renderPipeline = this._renderPipelines[renderPipelineName];
  30872. if (!renderPipeline) {
  30873. return;
  30874. }
  30875. renderPipeline._enableEffect(renderEffectName, cameras);
  30876. };
  30877. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30878. var renderPipeline = this._renderPipelines[renderPipelineName];
  30879. if (!renderPipeline) {
  30880. return;
  30881. }
  30882. renderPipeline._disableEffect(renderEffectName, cameras);
  30883. };
  30884. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  30885. var renderPipeline = this._renderPipelines[renderPipelineName];
  30886. if (!renderPipeline) {
  30887. return;
  30888. }
  30889. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  30890. };
  30891. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  30892. var renderPipeline = this._renderPipelines[renderPipelineName];
  30893. if (!renderPipeline) {
  30894. return;
  30895. }
  30896. renderPipeline._disableDisplayOnlyPass(cameras);
  30897. };
  30898. PostProcessRenderPipelineManager.prototype.update = function () {
  30899. for (var renderPipelineName in this._renderPipelines) {
  30900. var pipeline = this._renderPipelines[renderPipelineName];
  30901. if (!pipeline.isSupported) {
  30902. pipeline.dispose();
  30903. delete this._renderPipelines[renderPipelineName];
  30904. }
  30905. else {
  30906. pipeline._update();
  30907. }
  30908. }
  30909. };
  30910. return PostProcessRenderPipelineManager;
  30911. })();
  30912. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  30913. })(BABYLON || (BABYLON = {}));
  30914. var BABYLON;
  30915. (function (BABYLON) {
  30916. var BoundingBoxRenderer = (function () {
  30917. function BoundingBoxRenderer(scene) {
  30918. this.frontColor = new BABYLON.Color3(1, 1, 1);
  30919. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  30920. this.showBackLines = true;
  30921. this.renderList = new BABYLON.SmartArray(32);
  30922. this._scene = scene;
  30923. }
  30924. BoundingBoxRenderer.prototype._prepareRessources = function () {
  30925. if (this._colorShader) {
  30926. return;
  30927. }
  30928. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  30929. attributes: ["position"],
  30930. uniforms: ["worldViewProjection", "color"]
  30931. });
  30932. var engine = this._scene.getEngine();
  30933. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  30934. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  30935. 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]);
  30936. };
  30937. BoundingBoxRenderer.prototype.reset = function () {
  30938. this.renderList.reset();
  30939. };
  30940. BoundingBoxRenderer.prototype.render = function () {
  30941. if (this.renderList.length === 0) {
  30942. return;
  30943. }
  30944. this._prepareRessources();
  30945. if (!this._colorShader.isReady()) {
  30946. return;
  30947. }
  30948. var engine = this._scene.getEngine();
  30949. engine.setDepthWrite(false);
  30950. this._colorShader._preBind();
  30951. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  30952. var boundingBox = this.renderList.data[boundingBoxIndex];
  30953. var min = boundingBox.minimum;
  30954. var max = boundingBox.maximum;
  30955. var diff = max.subtract(min);
  30956. var median = min.add(diff.scale(0.5));
  30957. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  30958. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  30959. .multiply(boundingBox.getWorldMatrix());
  30960. // VBOs
  30961. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  30962. if (this.showBackLines) {
  30963. // Back
  30964. engine.setDepthFunctionToGreaterOrEqual();
  30965. this._scene.resetCachedMaterial();
  30966. this._colorShader.setColor4("color", this.backColor.toColor4());
  30967. this._colorShader.bind(worldMatrix);
  30968. // Draw order
  30969. engine.draw(false, 0, 24);
  30970. }
  30971. // Front
  30972. engine.setDepthFunctionToLess();
  30973. this._scene.resetCachedMaterial();
  30974. this._colorShader.setColor4("color", this.frontColor.toColor4());
  30975. this._colorShader.bind(worldMatrix);
  30976. // Draw order
  30977. engine.draw(false, 0, 24);
  30978. }
  30979. this._colorShader.unbind();
  30980. engine.setDepthFunctionToLessOrEqual();
  30981. engine.setDepthWrite(true);
  30982. };
  30983. BoundingBoxRenderer.prototype.dispose = function () {
  30984. if (!this._colorShader) {
  30985. return;
  30986. }
  30987. this._colorShader.dispose();
  30988. this._vb.dispose();
  30989. this._scene.getEngine()._releaseBuffer(this._ib);
  30990. };
  30991. return BoundingBoxRenderer;
  30992. })();
  30993. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  30994. })(BABYLON || (BABYLON = {}));
  30995. var BABYLON;
  30996. (function (BABYLON) {
  30997. var Condition = (function () {
  30998. function Condition(actionManager) {
  30999. this._actionManager = actionManager;
  31000. }
  31001. Condition.prototype.isValid = function () {
  31002. return true;
  31003. };
  31004. Condition.prototype._getProperty = function (propertyPath) {
  31005. return this._actionManager._getProperty(propertyPath);
  31006. };
  31007. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  31008. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31009. };
  31010. Condition.prototype.serialize = function () {
  31011. };
  31012. Condition.prototype._serialize = function (serializedCondition) {
  31013. return {
  31014. type: 2,
  31015. children: [],
  31016. name: serializedCondition.name,
  31017. properties: serializedCondition.properties
  31018. };
  31019. };
  31020. return Condition;
  31021. })();
  31022. BABYLON.Condition = Condition;
  31023. var ValueCondition = (function (_super) {
  31024. __extends(ValueCondition, _super);
  31025. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  31026. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  31027. _super.call(this, actionManager);
  31028. this.propertyPath = propertyPath;
  31029. this.value = value;
  31030. this.operator = operator;
  31031. this._target = target;
  31032. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  31033. this._property = this._getProperty(this.propertyPath);
  31034. }
  31035. Object.defineProperty(ValueCondition, "IsEqual", {
  31036. get: function () {
  31037. return ValueCondition._IsEqual;
  31038. },
  31039. enumerable: true,
  31040. configurable: true
  31041. });
  31042. Object.defineProperty(ValueCondition, "IsDifferent", {
  31043. get: function () {
  31044. return ValueCondition._IsDifferent;
  31045. },
  31046. enumerable: true,
  31047. configurable: true
  31048. });
  31049. Object.defineProperty(ValueCondition, "IsGreater", {
  31050. get: function () {
  31051. return ValueCondition._IsGreater;
  31052. },
  31053. enumerable: true,
  31054. configurable: true
  31055. });
  31056. Object.defineProperty(ValueCondition, "IsLesser", {
  31057. get: function () {
  31058. return ValueCondition._IsLesser;
  31059. },
  31060. enumerable: true,
  31061. configurable: true
  31062. });
  31063. // Methods
  31064. ValueCondition.prototype.isValid = function () {
  31065. switch (this.operator) {
  31066. case ValueCondition.IsGreater:
  31067. return this._effectiveTarget[this._property] > this.value;
  31068. case ValueCondition.IsLesser:
  31069. return this._effectiveTarget[this._property] < this.value;
  31070. case ValueCondition.IsEqual:
  31071. case ValueCondition.IsDifferent:
  31072. var check;
  31073. if (this.value.equals) {
  31074. check = this.value.equals(this._effectiveTarget[this._property]);
  31075. }
  31076. else {
  31077. check = this.value === this._effectiveTarget[this._property];
  31078. }
  31079. return this.operator === ValueCondition.IsEqual ? check : !check;
  31080. }
  31081. return false;
  31082. };
  31083. ValueCondition.prototype.serialize = function () {
  31084. return this._serialize({
  31085. name: "ValueCondition",
  31086. properties: [
  31087. BABYLON.Action._GetTargetProperty(this._target),
  31088. { name: "propertyPath", value: this.propertyPath },
  31089. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31090. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  31091. ]
  31092. });
  31093. };
  31094. ValueCondition.GetOperatorName = function (operator) {
  31095. switch (operator) {
  31096. case ValueCondition._IsEqual: return "IsEqual";
  31097. case ValueCondition._IsDifferent: return "IsDifferent";
  31098. case ValueCondition._IsGreater: return "IsGreater";
  31099. case ValueCondition._IsLesser: return "IsLesser";
  31100. default: return "";
  31101. }
  31102. };
  31103. // Statics
  31104. ValueCondition._IsEqual = 0;
  31105. ValueCondition._IsDifferent = 1;
  31106. ValueCondition._IsGreater = 2;
  31107. ValueCondition._IsLesser = 3;
  31108. return ValueCondition;
  31109. })(Condition);
  31110. BABYLON.ValueCondition = ValueCondition;
  31111. var PredicateCondition = (function (_super) {
  31112. __extends(PredicateCondition, _super);
  31113. function PredicateCondition(actionManager, predicate) {
  31114. _super.call(this, actionManager);
  31115. this.predicate = predicate;
  31116. }
  31117. PredicateCondition.prototype.isValid = function () {
  31118. return this.predicate();
  31119. };
  31120. return PredicateCondition;
  31121. })(Condition);
  31122. BABYLON.PredicateCondition = PredicateCondition;
  31123. var StateCondition = (function (_super) {
  31124. __extends(StateCondition, _super);
  31125. function StateCondition(actionManager, target, value) {
  31126. _super.call(this, actionManager);
  31127. this.value = value;
  31128. this._target = target;
  31129. }
  31130. // Methods
  31131. StateCondition.prototype.isValid = function () {
  31132. return this._target.state === this.value;
  31133. };
  31134. StateCondition.prototype.serialize = function () {
  31135. return this._serialize({
  31136. name: "StateCondition",
  31137. properties: [
  31138. BABYLON.Action._GetTargetProperty(this._target),
  31139. { name: "value", value: this.value }
  31140. ]
  31141. });
  31142. };
  31143. return StateCondition;
  31144. })(Condition);
  31145. BABYLON.StateCondition = StateCondition;
  31146. })(BABYLON || (BABYLON = {}));
  31147. var BABYLON;
  31148. (function (BABYLON) {
  31149. var Action = (function () {
  31150. function Action(triggerOptions, condition) {
  31151. this.triggerOptions = triggerOptions;
  31152. if (triggerOptions.parameter) {
  31153. this.trigger = triggerOptions.trigger;
  31154. this._triggerParameter = triggerOptions.parameter;
  31155. }
  31156. else {
  31157. this.trigger = triggerOptions;
  31158. }
  31159. this._nextActiveAction = this;
  31160. this._condition = condition;
  31161. }
  31162. // Methods
  31163. Action.prototype._prepare = function () {
  31164. };
  31165. Action.prototype.getTriggerParameter = function () {
  31166. return this._triggerParameter;
  31167. };
  31168. Action.prototype._executeCurrent = function (evt) {
  31169. if (this._nextActiveAction._condition) {
  31170. var condition = this._nextActiveAction._condition;
  31171. var currentRenderId = this._actionManager.getScene().getRenderId();
  31172. // We cache the current evaluation for the current frame
  31173. if (condition._evaluationId === currentRenderId) {
  31174. if (!condition._currentResult) {
  31175. return;
  31176. }
  31177. }
  31178. else {
  31179. condition._evaluationId = currentRenderId;
  31180. if (!condition.isValid()) {
  31181. condition._currentResult = false;
  31182. return;
  31183. }
  31184. condition._currentResult = true;
  31185. }
  31186. }
  31187. this._nextActiveAction.execute(evt);
  31188. this.skipToNextActiveAction();
  31189. };
  31190. Action.prototype.execute = function (evt) {
  31191. };
  31192. Action.prototype.skipToNextActiveAction = function () {
  31193. if (this._nextActiveAction._child) {
  31194. if (!this._nextActiveAction._child._actionManager) {
  31195. this._nextActiveAction._child._actionManager = this._actionManager;
  31196. }
  31197. this._nextActiveAction = this._nextActiveAction._child;
  31198. }
  31199. else {
  31200. this._nextActiveAction = this;
  31201. }
  31202. };
  31203. Action.prototype.then = function (action) {
  31204. this._child = action;
  31205. action._actionManager = this._actionManager;
  31206. action._prepare();
  31207. return action;
  31208. };
  31209. Action.prototype._getProperty = function (propertyPath) {
  31210. return this._actionManager._getProperty(propertyPath);
  31211. };
  31212. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  31213. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31214. };
  31215. Action.prototype.serialize = function (parent) {
  31216. };
  31217. // Called by BABYLON.Action objects in serialize(...). Internal use
  31218. Action.prototype._serialize = function (serializedAction, parent) {
  31219. var serializationObject = {
  31220. type: 1,
  31221. children: [],
  31222. name: serializedAction.name,
  31223. properties: serializedAction.properties || []
  31224. };
  31225. // Serialize child
  31226. if (this._child) {
  31227. this._child.serialize(serializationObject);
  31228. }
  31229. // Check if "this" has a condition
  31230. if (this._condition) {
  31231. var serializedCondition = this._condition.serialize();
  31232. serializedCondition.children.push(serializationObject);
  31233. if (parent) {
  31234. parent.children.push(serializedCondition);
  31235. }
  31236. return serializedCondition;
  31237. }
  31238. if (parent) {
  31239. parent.children.push(serializationObject);
  31240. }
  31241. return serializationObject;
  31242. };
  31243. Action._SerializeValueAsString = function (value) {
  31244. if (typeof value === "number") {
  31245. return value.toString();
  31246. }
  31247. if (typeof value === "boolean") {
  31248. return value ? "true" : "false";
  31249. }
  31250. if (value instanceof BABYLON.Vector2) {
  31251. return value.x + ", " + value.y;
  31252. }
  31253. if (value instanceof BABYLON.Vector3) {
  31254. return value.x + ", " + value.y + ", " + value.z;
  31255. }
  31256. if (value instanceof BABYLON.Color3) {
  31257. return value.r + ", " + value.g + ", " + value.b;
  31258. }
  31259. if (value instanceof BABYLON.Color4) {
  31260. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  31261. }
  31262. return value; // string
  31263. };
  31264. Action._GetTargetProperty = function (target) {
  31265. return {
  31266. name: "target",
  31267. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  31268. : target instanceof BABYLON.Light ? "LightProperties"
  31269. : target instanceof BABYLON.Camera ? "CameraProperties"
  31270. : "SceneProperties",
  31271. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  31272. };
  31273. };
  31274. return Action;
  31275. })();
  31276. BABYLON.Action = Action;
  31277. })(BABYLON || (BABYLON = {}));
  31278. var BABYLON;
  31279. (function (BABYLON) {
  31280. /**
  31281. * ActionEvent is the event beint sent when an action is triggered.
  31282. */
  31283. var ActionEvent = (function () {
  31284. /**
  31285. * @constructor
  31286. * @param source The mesh or sprite that triggered the action.
  31287. * @param pointerX The X mouse cursor position at the time of the event
  31288. * @param pointerY The Y mouse cursor position at the time of the event
  31289. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  31290. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  31291. */
  31292. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  31293. this.source = source;
  31294. this.pointerX = pointerX;
  31295. this.pointerY = pointerY;
  31296. this.meshUnderPointer = meshUnderPointer;
  31297. this.sourceEvent = sourceEvent;
  31298. this.additionalData = additionalData;
  31299. }
  31300. /**
  31301. * Helper function to auto-create an ActionEvent from a source mesh.
  31302. * @param source The source mesh that triggered the event
  31303. * @param evt {Event} The original (browser) event
  31304. */
  31305. ActionEvent.CreateNew = function (source, evt, additionalData) {
  31306. var scene = source.getScene();
  31307. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31308. };
  31309. /**
  31310. * Helper function to auto-create an ActionEvent from a source mesh.
  31311. * @param source The source sprite that triggered the event
  31312. * @param scene Scene associated with the sprite
  31313. * @param evt {Event} The original (browser) event
  31314. */
  31315. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  31316. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31317. };
  31318. /**
  31319. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  31320. * @param scene the scene where the event occurred
  31321. * @param evt {Event} The original (browser) event
  31322. */
  31323. ActionEvent.CreateNewFromScene = function (scene, evt) {
  31324. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  31325. };
  31326. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  31327. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  31328. };
  31329. return ActionEvent;
  31330. })();
  31331. BABYLON.ActionEvent = ActionEvent;
  31332. /**
  31333. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  31334. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  31335. */
  31336. var ActionManager = (function () {
  31337. function ActionManager(scene) {
  31338. // Members
  31339. this.actions = new Array();
  31340. this._scene = scene;
  31341. scene._actionManagers.push(this);
  31342. }
  31343. Object.defineProperty(ActionManager, "NothingTrigger", {
  31344. get: function () {
  31345. return ActionManager._NothingTrigger;
  31346. },
  31347. enumerable: true,
  31348. configurable: true
  31349. });
  31350. Object.defineProperty(ActionManager, "OnPickTrigger", {
  31351. get: function () {
  31352. return ActionManager._OnPickTrigger;
  31353. },
  31354. enumerable: true,
  31355. configurable: true
  31356. });
  31357. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  31358. get: function () {
  31359. return ActionManager._OnLeftPickTrigger;
  31360. },
  31361. enumerable: true,
  31362. configurable: true
  31363. });
  31364. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  31365. get: function () {
  31366. return ActionManager._OnRightPickTrigger;
  31367. },
  31368. enumerable: true,
  31369. configurable: true
  31370. });
  31371. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  31372. get: function () {
  31373. return ActionManager._OnCenterPickTrigger;
  31374. },
  31375. enumerable: true,
  31376. configurable: true
  31377. });
  31378. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  31379. get: function () {
  31380. return ActionManager._OnPickDownTrigger;
  31381. },
  31382. enumerable: true,
  31383. configurable: true
  31384. });
  31385. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  31386. get: function () {
  31387. return ActionManager._OnPickUpTrigger;
  31388. },
  31389. enumerable: true,
  31390. configurable: true
  31391. });
  31392. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  31393. /// This trigger will only be raised if you also declared a OnPickDown
  31394. get: function () {
  31395. return ActionManager._OnPickOutTrigger;
  31396. },
  31397. enumerable: true,
  31398. configurable: true
  31399. });
  31400. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  31401. get: function () {
  31402. return ActionManager._OnLongPressTrigger;
  31403. },
  31404. enumerable: true,
  31405. configurable: true
  31406. });
  31407. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  31408. get: function () {
  31409. return ActionManager._OnPointerOverTrigger;
  31410. },
  31411. enumerable: true,
  31412. configurable: true
  31413. });
  31414. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  31415. get: function () {
  31416. return ActionManager._OnPointerOutTrigger;
  31417. },
  31418. enumerable: true,
  31419. configurable: true
  31420. });
  31421. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  31422. get: function () {
  31423. return ActionManager._OnEveryFrameTrigger;
  31424. },
  31425. enumerable: true,
  31426. configurable: true
  31427. });
  31428. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  31429. get: function () {
  31430. return ActionManager._OnIntersectionEnterTrigger;
  31431. },
  31432. enumerable: true,
  31433. configurable: true
  31434. });
  31435. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  31436. get: function () {
  31437. return ActionManager._OnIntersectionExitTrigger;
  31438. },
  31439. enumerable: true,
  31440. configurable: true
  31441. });
  31442. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  31443. get: function () {
  31444. return ActionManager._OnKeyDownTrigger;
  31445. },
  31446. enumerable: true,
  31447. configurable: true
  31448. });
  31449. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  31450. get: function () {
  31451. return ActionManager._OnKeyUpTrigger;
  31452. },
  31453. enumerable: true,
  31454. configurable: true
  31455. });
  31456. // Methods
  31457. ActionManager.prototype.dispose = function () {
  31458. var index = this._scene._actionManagers.indexOf(this);
  31459. if (index > -1) {
  31460. this._scene._actionManagers.splice(index, 1);
  31461. }
  31462. };
  31463. ActionManager.prototype.getScene = function () {
  31464. return this._scene;
  31465. };
  31466. /**
  31467. * Does this action manager handles actions of any of the given triggers
  31468. * @param {number[]} triggers - the triggers to be tested
  31469. * @return {boolean} whether one (or more) of the triggers is handeled
  31470. */
  31471. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  31472. for (var index = 0; index < this.actions.length; index++) {
  31473. var action = this.actions[index];
  31474. if (triggers.indexOf(action.trigger) > -1) {
  31475. return true;
  31476. }
  31477. }
  31478. return false;
  31479. };
  31480. /**
  31481. * Does this action manager handles actions of a given trigger
  31482. * @param {number} trigger - the trigger to be tested
  31483. * @return {boolean} whether the trigger is handeled
  31484. */
  31485. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  31486. for (var index = 0; index < this.actions.length; index++) {
  31487. var action = this.actions[index];
  31488. if (action.trigger === trigger) {
  31489. return true;
  31490. }
  31491. }
  31492. return false;
  31493. };
  31494. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  31495. /**
  31496. * Does this action manager has pointer triggers
  31497. * @return {boolean} whether or not it has pointer triggers
  31498. */
  31499. get: function () {
  31500. for (var index = 0; index < this.actions.length; index++) {
  31501. var action = this.actions[index];
  31502. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  31503. return true;
  31504. }
  31505. }
  31506. return false;
  31507. },
  31508. enumerable: true,
  31509. configurable: true
  31510. });
  31511. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  31512. /**
  31513. * Does this action manager has pick triggers
  31514. * @return {boolean} whether or not it has pick triggers
  31515. */
  31516. get: function () {
  31517. for (var index = 0; index < this.actions.length; index++) {
  31518. var action = this.actions[index];
  31519. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  31520. return true;
  31521. }
  31522. }
  31523. return false;
  31524. },
  31525. enumerable: true,
  31526. configurable: true
  31527. });
  31528. /**
  31529. * Registers an action to this action manager
  31530. * @param {BABYLON.Action} action - the action to be registered
  31531. * @return {BABYLON.Action} the action amended (prepared) after registration
  31532. */
  31533. ActionManager.prototype.registerAction = function (action) {
  31534. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  31535. if (this.getScene().actionManager !== this) {
  31536. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  31537. return null;
  31538. }
  31539. }
  31540. this.actions.push(action);
  31541. action._actionManager = this;
  31542. action._prepare();
  31543. return action;
  31544. };
  31545. /**
  31546. * Process a specific trigger
  31547. * @param {number} trigger - the trigger to process
  31548. * @param evt {BABYLON.ActionEvent} the event details to be processed
  31549. */
  31550. ActionManager.prototype.processTrigger = function (trigger, evt) {
  31551. for (var index = 0; index < this.actions.length; index++) {
  31552. var action = this.actions[index];
  31553. if (action.trigger === trigger) {
  31554. if (trigger === ActionManager.OnKeyUpTrigger
  31555. || trigger === ActionManager.OnKeyDownTrigger) {
  31556. var parameter = action.getTriggerParameter();
  31557. if (parameter) {
  31558. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  31559. var actualkey = String.fromCharCode(unicode).toLowerCase();
  31560. if (actualkey !== parameter.toLowerCase()) {
  31561. continue;
  31562. }
  31563. }
  31564. }
  31565. action._executeCurrent(evt);
  31566. }
  31567. }
  31568. };
  31569. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  31570. var properties = propertyPath.split(".");
  31571. for (var index = 0; index < properties.length - 1; index++) {
  31572. target = target[properties[index]];
  31573. }
  31574. return target;
  31575. };
  31576. ActionManager.prototype._getProperty = function (propertyPath) {
  31577. var properties = propertyPath.split(".");
  31578. return properties[properties.length - 1];
  31579. };
  31580. ActionManager.prototype.serialize = function (name) {
  31581. var root = {
  31582. children: [],
  31583. name: name,
  31584. type: 3,
  31585. properties: [] // Empty for root but required
  31586. };
  31587. for (var i = 0; i < this.actions.length; i++) {
  31588. var triggerObject = {
  31589. type: 0,
  31590. children: [],
  31591. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  31592. properties: []
  31593. };
  31594. var triggerOptions = this.actions[i].triggerOptions;
  31595. if (triggerOptions && typeof triggerOptions !== "number") {
  31596. if (triggerOptions.parameter instanceof BABYLON.Node) {
  31597. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  31598. }
  31599. else {
  31600. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  31601. }
  31602. }
  31603. // Serialize child action, recursively
  31604. this.actions[i].serialize(triggerObject);
  31605. // Add serialized trigger
  31606. root.children.push(triggerObject);
  31607. }
  31608. return root;
  31609. };
  31610. ActionManager.Parse = function (parsedActions, object, scene) {
  31611. var actionManager = new BABYLON.ActionManager(scene);
  31612. if (object === null)
  31613. scene.actionManager = actionManager;
  31614. else
  31615. object.actionManager = actionManager;
  31616. // instanciate a new object
  31617. var instanciate = function (name, params) {
  31618. var newInstance = Object.create(BABYLON[name].prototype);
  31619. newInstance.constructor.apply(newInstance, params);
  31620. return newInstance;
  31621. };
  31622. var parseParameter = function (name, value, target, propertyPath) {
  31623. if (propertyPath === null) {
  31624. // String, boolean or float
  31625. var floatValue = parseFloat(value);
  31626. if (value === "true" || value === "false")
  31627. return value === "true";
  31628. else
  31629. return isNaN(floatValue) ? value : floatValue;
  31630. }
  31631. var effectiveTarget = propertyPath.split(".");
  31632. var values = value.split(",");
  31633. // Get effective Target
  31634. for (var i = 0; i < effectiveTarget.length; i++) {
  31635. target = target[effectiveTarget[i]];
  31636. }
  31637. // Return appropriate value with its type
  31638. if (typeof (target) === "boolean")
  31639. return values[0] === "true";
  31640. if (typeof (target) === "string")
  31641. return values[0];
  31642. // Parameters with multiple values such as Vector3 etc.
  31643. var split = new Array();
  31644. for (var i = 0; i < values.length; i++)
  31645. split.push(parseFloat(values[i]));
  31646. if (target instanceof BABYLON.Vector3)
  31647. return BABYLON.Vector3.FromArray(split);
  31648. if (target instanceof BABYLON.Vector4)
  31649. return BABYLON.Vector4.FromArray(split);
  31650. if (target instanceof BABYLON.Color3)
  31651. return BABYLON.Color3.FromArray(split);
  31652. if (target instanceof BABYLON.Color4)
  31653. return BABYLON.Color4.FromArray(split);
  31654. return parseFloat(values[0]);
  31655. };
  31656. // traverse graph per trigger
  31657. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  31658. if (combineArray === void 0) { combineArray = null; }
  31659. if (parsedAction.detached)
  31660. return;
  31661. var parameters = new Array();
  31662. var target = null;
  31663. var propertyPath = null;
  31664. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  31665. // Parameters
  31666. if (parsedAction.type === 2)
  31667. parameters.push(actionManager);
  31668. else
  31669. parameters.push(trigger);
  31670. if (combine) {
  31671. var actions = new Array();
  31672. for (var j = 0; j < parsedAction.combine.length; j++) {
  31673. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  31674. }
  31675. parameters.push(actions);
  31676. }
  31677. else {
  31678. for (var i = 0; i < parsedAction.properties.length; i++) {
  31679. var value = parsedAction.properties[i].value;
  31680. var name = parsedAction.properties[i].name;
  31681. var targetType = parsedAction.properties[i].targetType;
  31682. if (name === "target")
  31683. if (targetType !== null && targetType === "SceneProperties")
  31684. value = target = scene;
  31685. else
  31686. value = target = scene.getNodeByName(value);
  31687. else if (name === "parent")
  31688. value = scene.getNodeByName(value);
  31689. else if (name === "sound")
  31690. value = scene.getSoundByName(value);
  31691. else if (name !== "propertyPath") {
  31692. if (parsedAction.type === 2 && name === "operator")
  31693. value = BABYLON.ValueCondition[value];
  31694. else
  31695. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  31696. }
  31697. else {
  31698. propertyPath = value;
  31699. }
  31700. parameters.push(value);
  31701. }
  31702. }
  31703. if (combineArray === null) {
  31704. parameters.push(condition);
  31705. }
  31706. else {
  31707. parameters.push(null);
  31708. }
  31709. // If interpolate value action
  31710. if (parsedAction.name === "InterpolateValueAction") {
  31711. var param = parameters[parameters.length - 2];
  31712. parameters[parameters.length - 1] = param;
  31713. parameters[parameters.length - 2] = condition;
  31714. }
  31715. // Action or condition(s) and not CombineAction
  31716. var newAction = instanciate(parsedAction.name, parameters);
  31717. if (newAction instanceof BABYLON.Condition && condition !== null) {
  31718. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  31719. if (action)
  31720. action.then(nothing);
  31721. else
  31722. actionManager.registerAction(nothing);
  31723. action = nothing;
  31724. }
  31725. if (combineArray === null) {
  31726. if (newAction instanceof BABYLON.Condition) {
  31727. condition = newAction;
  31728. newAction = action;
  31729. }
  31730. else {
  31731. condition = null;
  31732. if (action)
  31733. action.then(newAction);
  31734. else
  31735. actionManager.registerAction(newAction);
  31736. }
  31737. }
  31738. else {
  31739. combineArray.push(newAction);
  31740. }
  31741. for (var i = 0; i < parsedAction.children.length; i++)
  31742. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  31743. };
  31744. // triggers
  31745. for (var i = 0; i < parsedActions.children.length; i++) {
  31746. var triggerParams;
  31747. var trigger = parsedActions.children[i];
  31748. if (trigger.properties.length > 0) {
  31749. var param = trigger.properties[0].value;
  31750. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  31751. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  31752. }
  31753. else
  31754. triggerParams = BABYLON.ActionManager[trigger.name];
  31755. for (var j = 0; j < trigger.children.length; j++) {
  31756. if (!trigger.detached)
  31757. traverse(trigger.children[j], triggerParams, null, null);
  31758. }
  31759. }
  31760. };
  31761. ActionManager.GetTriggerName = function (trigger) {
  31762. switch (trigger) {
  31763. case 0: return "NothingTrigger";
  31764. case 1: return "OnPickTrigger";
  31765. case 2: return "OnLeftPickTrigger";
  31766. case 3: return "OnRightPickTrigger";
  31767. case 4: return "OnCenterPickTrigger";
  31768. case 5: return "OnPickDownTrigger";
  31769. case 6: return "OnPickUpTrigger";
  31770. case 7: return "OnLongPressTrigger";
  31771. case 8: return "OnPointerOverTrigger";
  31772. case 9: return "OnPointerOutTrigger";
  31773. case 10: return "OnEveryFrameTrigger";
  31774. case 11: return "OnIntersectionEnterTrigger";
  31775. case 12: return "OnIntersectionExitTrigger";
  31776. case 13: return "OnKeyDownTrigger";
  31777. case 14: return "OnKeyUpTrigger";
  31778. case 15: return "OnPickOutTrigger";
  31779. default: return "";
  31780. }
  31781. };
  31782. // Statics
  31783. ActionManager._NothingTrigger = 0;
  31784. ActionManager._OnPickTrigger = 1;
  31785. ActionManager._OnLeftPickTrigger = 2;
  31786. ActionManager._OnRightPickTrigger = 3;
  31787. ActionManager._OnCenterPickTrigger = 4;
  31788. ActionManager._OnPickDownTrigger = 5;
  31789. ActionManager._OnPickUpTrigger = 6;
  31790. ActionManager._OnLongPressTrigger = 7;
  31791. ActionManager._OnPointerOverTrigger = 8;
  31792. ActionManager._OnPointerOutTrigger = 9;
  31793. ActionManager._OnEveryFrameTrigger = 10;
  31794. ActionManager._OnIntersectionEnterTrigger = 11;
  31795. ActionManager._OnIntersectionExitTrigger = 12;
  31796. ActionManager._OnKeyDownTrigger = 13;
  31797. ActionManager._OnKeyUpTrigger = 14;
  31798. ActionManager._OnPickOutTrigger = 15;
  31799. ActionManager.DragMovementThreshold = 10; // in pixels
  31800. ActionManager.LongPressDelay = 500; // in milliseconds
  31801. return ActionManager;
  31802. })();
  31803. BABYLON.ActionManager = ActionManager;
  31804. })(BABYLON || (BABYLON = {}));
  31805. var BABYLON;
  31806. (function (BABYLON) {
  31807. var InterpolateValueAction = (function (_super) {
  31808. __extends(InterpolateValueAction, _super);
  31809. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  31810. if (duration === void 0) { duration = 1000; }
  31811. _super.call(this, triggerOptions, condition);
  31812. this.propertyPath = propertyPath;
  31813. this.value = value;
  31814. this.duration = duration;
  31815. this.stopOtherAnimations = stopOtherAnimations;
  31816. this.onInterpolationDone = onInterpolationDone;
  31817. this._target = this._effectiveTarget = target;
  31818. }
  31819. InterpolateValueAction.prototype._prepare = function () {
  31820. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31821. this._property = this._getProperty(this.propertyPath);
  31822. };
  31823. InterpolateValueAction.prototype.execute = function () {
  31824. var scene = this._actionManager.getScene();
  31825. var keys = [
  31826. {
  31827. frame: 0,
  31828. value: this._effectiveTarget[this._property]
  31829. }, {
  31830. frame: 100,
  31831. value: this.value
  31832. }
  31833. ];
  31834. var dataType;
  31835. if (typeof this.value === "number") {
  31836. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  31837. }
  31838. else if (this.value instanceof BABYLON.Color3) {
  31839. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  31840. }
  31841. else if (this.value instanceof BABYLON.Vector3) {
  31842. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  31843. }
  31844. else if (this.value instanceof BABYLON.Matrix) {
  31845. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  31846. }
  31847. else if (this.value instanceof BABYLON.Quaternion) {
  31848. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  31849. }
  31850. else {
  31851. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  31852. return;
  31853. }
  31854. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  31855. animation.setKeys(keys);
  31856. if (this.stopOtherAnimations) {
  31857. scene.stopAnimation(this._effectiveTarget);
  31858. }
  31859. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  31860. };
  31861. InterpolateValueAction.prototype.serialize = function (parent) {
  31862. return _super.prototype._serialize.call(this, {
  31863. name: "InterpolateValueAction",
  31864. properties: [
  31865. BABYLON.Action._GetTargetProperty(this._target),
  31866. { name: "propertyPath", value: this.propertyPath },
  31867. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31868. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  31869. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  31870. ]
  31871. }, parent);
  31872. };
  31873. return InterpolateValueAction;
  31874. })(BABYLON.Action);
  31875. BABYLON.InterpolateValueAction = InterpolateValueAction;
  31876. })(BABYLON || (BABYLON = {}));
  31877. var BABYLON;
  31878. (function (BABYLON) {
  31879. var SwitchBooleanAction = (function (_super) {
  31880. __extends(SwitchBooleanAction, _super);
  31881. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  31882. _super.call(this, triggerOptions, condition);
  31883. this.propertyPath = propertyPath;
  31884. this._target = this._effectiveTarget = target;
  31885. }
  31886. SwitchBooleanAction.prototype._prepare = function () {
  31887. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31888. this._property = this._getProperty(this.propertyPath);
  31889. };
  31890. SwitchBooleanAction.prototype.execute = function () {
  31891. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  31892. };
  31893. SwitchBooleanAction.prototype.serialize = function (parent) {
  31894. return _super.prototype._serialize.call(this, {
  31895. name: "SwitchBooleanAction",
  31896. properties: [
  31897. BABYLON.Action._GetTargetProperty(this._target),
  31898. { name: "propertyPath", value: this.propertyPath }
  31899. ]
  31900. }, parent);
  31901. };
  31902. return SwitchBooleanAction;
  31903. })(BABYLON.Action);
  31904. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  31905. var SetStateAction = (function (_super) {
  31906. __extends(SetStateAction, _super);
  31907. function SetStateAction(triggerOptions, target, value, condition) {
  31908. _super.call(this, triggerOptions, condition);
  31909. this.value = value;
  31910. this._target = target;
  31911. }
  31912. SetStateAction.prototype.execute = function () {
  31913. this._target.state = this.value;
  31914. };
  31915. SetStateAction.prototype.serialize = function (parent) {
  31916. return _super.prototype._serialize.call(this, {
  31917. name: "SetStateAction",
  31918. properties: [
  31919. BABYLON.Action._GetTargetProperty(this._target),
  31920. { name: "value", value: this.value }
  31921. ]
  31922. }, parent);
  31923. };
  31924. return SetStateAction;
  31925. })(BABYLON.Action);
  31926. BABYLON.SetStateAction = SetStateAction;
  31927. var SetValueAction = (function (_super) {
  31928. __extends(SetValueAction, _super);
  31929. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  31930. _super.call(this, triggerOptions, condition);
  31931. this.propertyPath = propertyPath;
  31932. this.value = value;
  31933. this._target = this._effectiveTarget = target;
  31934. }
  31935. SetValueAction.prototype._prepare = function () {
  31936. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31937. this._property = this._getProperty(this.propertyPath);
  31938. };
  31939. SetValueAction.prototype.execute = function () {
  31940. this._effectiveTarget[this._property] = this.value;
  31941. if (this._target.markAsDirty) {
  31942. this._target.markAsDirty(this._property);
  31943. }
  31944. };
  31945. SetValueAction.prototype.serialize = function (parent) {
  31946. return _super.prototype._serialize.call(this, {
  31947. name: "SetValueAction",
  31948. properties: [
  31949. BABYLON.Action._GetTargetProperty(this._target),
  31950. { name: "propertyPath", value: this.propertyPath },
  31951. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31952. ]
  31953. }, parent);
  31954. };
  31955. return SetValueAction;
  31956. })(BABYLON.Action);
  31957. BABYLON.SetValueAction = SetValueAction;
  31958. var IncrementValueAction = (function (_super) {
  31959. __extends(IncrementValueAction, _super);
  31960. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  31961. _super.call(this, triggerOptions, condition);
  31962. this.propertyPath = propertyPath;
  31963. this.value = value;
  31964. this._target = this._effectiveTarget = target;
  31965. }
  31966. IncrementValueAction.prototype._prepare = function () {
  31967. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31968. this._property = this._getProperty(this.propertyPath);
  31969. if (typeof this._effectiveTarget[this._property] !== "number") {
  31970. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  31971. }
  31972. };
  31973. IncrementValueAction.prototype.execute = function () {
  31974. this._effectiveTarget[this._property] += this.value;
  31975. if (this._target.markAsDirty) {
  31976. this._target.markAsDirty(this._property);
  31977. }
  31978. };
  31979. IncrementValueAction.prototype.serialize = function (parent) {
  31980. return _super.prototype._serialize.call(this, {
  31981. name: "IncrementValueAction",
  31982. properties: [
  31983. BABYLON.Action._GetTargetProperty(this._target),
  31984. { name: "propertyPath", value: this.propertyPath },
  31985. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31986. ]
  31987. }, parent);
  31988. };
  31989. return IncrementValueAction;
  31990. })(BABYLON.Action);
  31991. BABYLON.IncrementValueAction = IncrementValueAction;
  31992. var PlayAnimationAction = (function (_super) {
  31993. __extends(PlayAnimationAction, _super);
  31994. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  31995. _super.call(this, triggerOptions, condition);
  31996. this.from = from;
  31997. this.to = to;
  31998. this.loop = loop;
  31999. this._target = target;
  32000. }
  32001. PlayAnimationAction.prototype._prepare = function () {
  32002. };
  32003. PlayAnimationAction.prototype.execute = function () {
  32004. var scene = this._actionManager.getScene();
  32005. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  32006. };
  32007. PlayAnimationAction.prototype.serialize = function (parent) {
  32008. return _super.prototype._serialize.call(this, {
  32009. name: "PlayAnimationAction",
  32010. properties: [
  32011. BABYLON.Action._GetTargetProperty(this._target),
  32012. { name: "from", value: String(this.from) },
  32013. { name: "to", value: String(this.to) },
  32014. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  32015. ]
  32016. }, parent);
  32017. };
  32018. return PlayAnimationAction;
  32019. })(BABYLON.Action);
  32020. BABYLON.PlayAnimationAction = PlayAnimationAction;
  32021. var StopAnimationAction = (function (_super) {
  32022. __extends(StopAnimationAction, _super);
  32023. function StopAnimationAction(triggerOptions, target, condition) {
  32024. _super.call(this, triggerOptions, condition);
  32025. this._target = target;
  32026. }
  32027. StopAnimationAction.prototype._prepare = function () {
  32028. };
  32029. StopAnimationAction.prototype.execute = function () {
  32030. var scene = this._actionManager.getScene();
  32031. scene.stopAnimation(this._target);
  32032. };
  32033. StopAnimationAction.prototype.serialize = function (parent) {
  32034. return _super.prototype._serialize.call(this, {
  32035. name: "StopAnimationAction",
  32036. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  32037. }, parent);
  32038. };
  32039. return StopAnimationAction;
  32040. })(BABYLON.Action);
  32041. BABYLON.StopAnimationAction = StopAnimationAction;
  32042. var DoNothingAction = (function (_super) {
  32043. __extends(DoNothingAction, _super);
  32044. function DoNothingAction(triggerOptions, condition) {
  32045. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  32046. _super.call(this, triggerOptions, condition);
  32047. }
  32048. DoNothingAction.prototype.execute = function () {
  32049. };
  32050. DoNothingAction.prototype.serialize = function (parent) {
  32051. return _super.prototype._serialize.call(this, {
  32052. name: "DoNothingAction",
  32053. properties: []
  32054. }, parent);
  32055. };
  32056. return DoNothingAction;
  32057. })(BABYLON.Action);
  32058. BABYLON.DoNothingAction = DoNothingAction;
  32059. var CombineAction = (function (_super) {
  32060. __extends(CombineAction, _super);
  32061. function CombineAction(triggerOptions, children, condition) {
  32062. _super.call(this, triggerOptions, condition);
  32063. this.children = children;
  32064. }
  32065. CombineAction.prototype._prepare = function () {
  32066. for (var index = 0; index < this.children.length; index++) {
  32067. this.children[index]._actionManager = this._actionManager;
  32068. this.children[index]._prepare();
  32069. }
  32070. };
  32071. CombineAction.prototype.execute = function (evt) {
  32072. for (var index = 0; index < this.children.length; index++) {
  32073. this.children[index].execute(evt);
  32074. }
  32075. };
  32076. CombineAction.prototype.serialize = function (parent) {
  32077. var serializationObject = _super.prototype._serialize.call(this, {
  32078. name: "CombineAction",
  32079. properties: [],
  32080. combine: []
  32081. }, parent);
  32082. for (var i = 0; i < this.children.length; i++) {
  32083. serializationObject.combine.push(this.children[i].serialize(null));
  32084. }
  32085. return serializationObject;
  32086. };
  32087. return CombineAction;
  32088. })(BABYLON.Action);
  32089. BABYLON.CombineAction = CombineAction;
  32090. var ExecuteCodeAction = (function (_super) {
  32091. __extends(ExecuteCodeAction, _super);
  32092. function ExecuteCodeAction(triggerOptions, func, condition) {
  32093. _super.call(this, triggerOptions, condition);
  32094. this.func = func;
  32095. }
  32096. ExecuteCodeAction.prototype.execute = function (evt) {
  32097. this.func(evt);
  32098. };
  32099. return ExecuteCodeAction;
  32100. })(BABYLON.Action);
  32101. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  32102. var SetParentAction = (function (_super) {
  32103. __extends(SetParentAction, _super);
  32104. function SetParentAction(triggerOptions, target, parent, condition) {
  32105. _super.call(this, triggerOptions, condition);
  32106. this._target = target;
  32107. this._parent = parent;
  32108. }
  32109. SetParentAction.prototype._prepare = function () {
  32110. };
  32111. SetParentAction.prototype.execute = function () {
  32112. if (this._target.parent === this._parent) {
  32113. return;
  32114. }
  32115. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  32116. invertParentWorldMatrix.invert();
  32117. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  32118. this._target.parent = this._parent;
  32119. };
  32120. SetParentAction.prototype.serialize = function (parent) {
  32121. return _super.prototype._serialize.call(this, {
  32122. name: "SetParentAction",
  32123. properties: [
  32124. BABYLON.Action._GetTargetProperty(this._target),
  32125. BABYLON.Action._GetTargetProperty(this._parent),
  32126. ]
  32127. }, parent);
  32128. };
  32129. return SetParentAction;
  32130. })(BABYLON.Action);
  32131. BABYLON.SetParentAction = SetParentAction;
  32132. var PlaySoundAction = (function (_super) {
  32133. __extends(PlaySoundAction, _super);
  32134. function PlaySoundAction(triggerOptions, sound, condition) {
  32135. _super.call(this, triggerOptions, condition);
  32136. this._sound = sound;
  32137. }
  32138. PlaySoundAction.prototype._prepare = function () {
  32139. };
  32140. PlaySoundAction.prototype.execute = function () {
  32141. if (this._sound !== undefined)
  32142. this._sound.play();
  32143. };
  32144. PlaySoundAction.prototype.serialize = function (parent) {
  32145. return _super.prototype._serialize.call(this, {
  32146. name: "PlaySoundAction",
  32147. properties: [{ name: "sound", value: this._sound.name }]
  32148. }, parent);
  32149. };
  32150. return PlaySoundAction;
  32151. })(BABYLON.Action);
  32152. BABYLON.PlaySoundAction = PlaySoundAction;
  32153. var StopSoundAction = (function (_super) {
  32154. __extends(StopSoundAction, _super);
  32155. function StopSoundAction(triggerOptions, sound, condition) {
  32156. _super.call(this, triggerOptions, condition);
  32157. this._sound = sound;
  32158. }
  32159. StopSoundAction.prototype._prepare = function () {
  32160. };
  32161. StopSoundAction.prototype.execute = function () {
  32162. if (this._sound !== undefined)
  32163. this._sound.stop();
  32164. };
  32165. StopSoundAction.prototype.serialize = function (parent) {
  32166. return _super.prototype._serialize.call(this, {
  32167. name: "StopSoundAction",
  32168. properties: [{ name: "sound", value: this._sound.name }]
  32169. }, parent);
  32170. };
  32171. return StopSoundAction;
  32172. })(BABYLON.Action);
  32173. BABYLON.StopSoundAction = StopSoundAction;
  32174. })(BABYLON || (BABYLON = {}));
  32175. var BABYLON;
  32176. (function (BABYLON) {
  32177. var Geometry = (function () {
  32178. function Geometry(id, scene, vertexData, updatable, mesh) {
  32179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32180. this._totalVertices = 0;
  32181. this._isDisposed = false;
  32182. this.id = id;
  32183. this._engine = scene.getEngine();
  32184. this._meshes = [];
  32185. this._scene = scene;
  32186. //Init vertex buffer cache
  32187. this._vertexBuffers = {};
  32188. this._indices = [];
  32189. // vertexData
  32190. if (vertexData) {
  32191. this.setAllVerticesData(vertexData, updatable);
  32192. }
  32193. else {
  32194. this._totalVertices = 0;
  32195. this._indices = [];
  32196. }
  32197. // applyToMesh
  32198. if (mesh) {
  32199. if (mesh instanceof BABYLON.LinesMesh) {
  32200. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32201. this.updateExtend();
  32202. }
  32203. this.applyToMesh(mesh);
  32204. mesh.computeWorldMatrix(true);
  32205. }
  32206. }
  32207. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32208. /**
  32209. * 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
  32210. * @returns The Bias Vector
  32211. */
  32212. get: function () {
  32213. return this._boundingBias;
  32214. },
  32215. set: function (value) {
  32216. if (this._boundingBias && this._boundingBias.equals(value)) {
  32217. return;
  32218. }
  32219. this._boundingBias = value.clone();
  32220. this.updateBoundingInfo(true, null);
  32221. },
  32222. enumerable: true,
  32223. configurable: true
  32224. });
  32225. Object.defineProperty(Geometry.prototype, "extend", {
  32226. get: function () {
  32227. return this._extend;
  32228. },
  32229. enumerable: true,
  32230. configurable: true
  32231. });
  32232. Geometry.prototype.getScene = function () {
  32233. return this._scene;
  32234. };
  32235. Geometry.prototype.getEngine = function () {
  32236. return this._engine;
  32237. };
  32238. Geometry.prototype.isReady = function () {
  32239. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32240. };
  32241. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32242. vertexData.applyToGeometry(this, updatable);
  32243. this.notifyUpdate();
  32244. };
  32245. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32246. if (this._vertexBuffers[kind]) {
  32247. this._vertexBuffers[kind].dispose();
  32248. }
  32249. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32250. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32251. stride = this._vertexBuffers[kind].getStrideSize();
  32252. this._totalVertices = data.length / stride;
  32253. this.updateExtend(data);
  32254. var meshes = this._meshes;
  32255. var numOfMeshes = meshes.length;
  32256. for (var index = 0; index < numOfMeshes; index++) {
  32257. var mesh = meshes[index];
  32258. mesh._resetPointsArrayCache();
  32259. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32260. mesh._createGlobalSubMesh();
  32261. mesh.computeWorldMatrix(true);
  32262. }
  32263. }
  32264. this.notifyUpdate(kind);
  32265. };
  32266. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32267. var vertexBuffer = this.getVertexBuffer(kind);
  32268. if (!vertexBuffer) {
  32269. return;
  32270. }
  32271. vertexBuffer.updateDirectly(data, offset);
  32272. this.notifyUpdate(kind);
  32273. };
  32274. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32275. var vertexBuffer = this.getVertexBuffer(kind);
  32276. if (!vertexBuffer) {
  32277. return;
  32278. }
  32279. vertexBuffer.update(data);
  32280. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32281. var stride = vertexBuffer.getStrideSize();
  32282. this._totalVertices = data.length / stride;
  32283. this.updateBoundingInfo(updateExtends, data);
  32284. }
  32285. this.notifyUpdate(kind);
  32286. };
  32287. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32288. if (updateExtends) {
  32289. this.updateExtend(data);
  32290. }
  32291. var meshes = this._meshes;
  32292. var numOfMeshes = meshes.length;
  32293. for (var index = 0; index < numOfMeshes; index++) {
  32294. var mesh = meshes[index];
  32295. mesh._resetPointsArrayCache();
  32296. if (updateExtends) {
  32297. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32298. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32299. var subMesh = mesh.subMeshes[subIndex];
  32300. subMesh.refreshBoundingInfo();
  32301. }
  32302. }
  32303. }
  32304. };
  32305. Geometry.prototype.getTotalVertices = function () {
  32306. if (!this.isReady()) {
  32307. return 0;
  32308. }
  32309. return this._totalVertices;
  32310. };
  32311. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  32312. var vertexBuffer = this.getVertexBuffer(kind);
  32313. if (!vertexBuffer) {
  32314. return null;
  32315. }
  32316. var orig = vertexBuffer.getData();
  32317. if (!copyWhenShared || this._meshes.length === 1) {
  32318. return orig;
  32319. }
  32320. else {
  32321. var len = orig.length;
  32322. var copy = [];
  32323. for (var i = 0; i < len; i++) {
  32324. copy.push(orig[i]);
  32325. }
  32326. return copy;
  32327. }
  32328. };
  32329. Geometry.prototype.getVertexBuffer = function (kind) {
  32330. if (!this.isReady()) {
  32331. return null;
  32332. }
  32333. return this._vertexBuffers[kind];
  32334. };
  32335. Geometry.prototype.getVertexBuffers = function () {
  32336. if (!this.isReady()) {
  32337. return null;
  32338. }
  32339. return this._vertexBuffers;
  32340. };
  32341. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32342. if (!this._vertexBuffers) {
  32343. if (this._delayInfo) {
  32344. return this._delayInfo.indexOf(kind) !== -1;
  32345. }
  32346. return false;
  32347. }
  32348. return this._vertexBuffers[kind] !== undefined;
  32349. };
  32350. Geometry.prototype.getVerticesDataKinds = function () {
  32351. var result = [];
  32352. var kind;
  32353. if (!this._vertexBuffers && this._delayInfo) {
  32354. for (kind in this._delayInfo) {
  32355. result.push(kind);
  32356. }
  32357. }
  32358. else {
  32359. for (kind in this._vertexBuffers) {
  32360. result.push(kind);
  32361. }
  32362. }
  32363. return result;
  32364. };
  32365. Geometry.prototype.setIndices = function (indices, totalVertices) {
  32366. if (this._indexBuffer) {
  32367. this._engine._releaseBuffer(this._indexBuffer);
  32368. }
  32369. this._indices = indices;
  32370. if (this._meshes.length !== 0 && this._indices) {
  32371. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32372. }
  32373. if (totalVertices !== undefined) {
  32374. this._totalVertices = totalVertices;
  32375. }
  32376. var meshes = this._meshes;
  32377. var numOfMeshes = meshes.length;
  32378. for (var index = 0; index < numOfMeshes; index++) {
  32379. meshes[index]._createGlobalSubMesh();
  32380. }
  32381. this.notifyUpdate();
  32382. };
  32383. Geometry.prototype.getTotalIndices = function () {
  32384. if (!this.isReady()) {
  32385. return 0;
  32386. }
  32387. return this._indices.length;
  32388. };
  32389. Geometry.prototype.getIndices = function (copyWhenShared) {
  32390. if (!this.isReady()) {
  32391. return null;
  32392. }
  32393. var orig = this._indices;
  32394. if (!copyWhenShared || this._meshes.length === 1) {
  32395. return orig;
  32396. }
  32397. else {
  32398. var len = orig.length;
  32399. var copy = [];
  32400. for (var i = 0; i < len; i++) {
  32401. copy.push(orig[i]);
  32402. }
  32403. return copy;
  32404. }
  32405. };
  32406. Geometry.prototype.getIndexBuffer = function () {
  32407. if (!this.isReady()) {
  32408. return null;
  32409. }
  32410. return this._indexBuffer;
  32411. };
  32412. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32413. var meshes = this._meshes;
  32414. var index = meshes.indexOf(mesh);
  32415. if (index === -1) {
  32416. return;
  32417. }
  32418. for (var kind in this._vertexBuffers) {
  32419. this._vertexBuffers[kind].dispose();
  32420. }
  32421. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  32422. this._indexBuffer = null;
  32423. }
  32424. meshes.splice(index, 1);
  32425. mesh._geometry = null;
  32426. if (meshes.length === 0 && shouldDispose) {
  32427. this.dispose();
  32428. }
  32429. };
  32430. Geometry.prototype.applyToMesh = function (mesh) {
  32431. if (mesh._geometry === this) {
  32432. return;
  32433. }
  32434. var previousGeometry = mesh._geometry;
  32435. if (previousGeometry) {
  32436. previousGeometry.releaseForMesh(mesh);
  32437. }
  32438. var meshes = this._meshes;
  32439. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32440. mesh._geometry = this;
  32441. this._scene.pushGeometry(this);
  32442. meshes.push(mesh);
  32443. if (this.isReady()) {
  32444. this._applyToMesh(mesh);
  32445. }
  32446. else {
  32447. mesh._boundingInfo = this._boundingInfo;
  32448. }
  32449. };
  32450. Geometry.prototype.updateExtend = function (data) {
  32451. if (data === void 0) { data = null; }
  32452. if (!data) {
  32453. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32454. }
  32455. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  32456. };
  32457. Geometry.prototype._applyToMesh = function (mesh) {
  32458. var numOfMeshes = this._meshes.length;
  32459. // vertexBuffers
  32460. for (var kind in this._vertexBuffers) {
  32461. if (numOfMeshes === 1) {
  32462. this._vertexBuffers[kind].create();
  32463. }
  32464. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  32465. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32466. mesh._resetPointsArrayCache();
  32467. if (!this._extend) {
  32468. this.updateExtend(this._vertexBuffers[kind].getData());
  32469. }
  32470. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32471. mesh._createGlobalSubMesh();
  32472. //bounding info was just created again, world matrix should be applied again.
  32473. mesh._updateBoundingInfo();
  32474. }
  32475. }
  32476. // indexBuffer
  32477. if (numOfMeshes === 1 && this._indices) {
  32478. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32479. }
  32480. if (this._indexBuffer) {
  32481. this._indexBuffer.references = numOfMeshes;
  32482. }
  32483. };
  32484. Geometry.prototype.notifyUpdate = function (kind) {
  32485. if (this.onGeometryUpdated) {
  32486. this.onGeometryUpdated(this, kind);
  32487. }
  32488. };
  32489. Geometry.prototype.load = function (scene, onLoaded) {
  32490. var _this = this;
  32491. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32492. return;
  32493. }
  32494. if (this.isReady()) {
  32495. if (onLoaded) {
  32496. onLoaded();
  32497. }
  32498. return;
  32499. }
  32500. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32501. scene._addPendingData(this);
  32502. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32503. _this._delayLoadingFunction(JSON.parse(data), _this);
  32504. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32505. _this._delayInfo = [];
  32506. scene._removePendingData(_this);
  32507. var meshes = _this._meshes;
  32508. var numOfMeshes = meshes.length;
  32509. for (var index = 0; index < numOfMeshes; index++) {
  32510. _this._applyToMesh(meshes[index]);
  32511. }
  32512. if (onLoaded) {
  32513. onLoaded();
  32514. }
  32515. }, function () { }, scene.database);
  32516. };
  32517. /**
  32518. * Invert the geometry to move from a right handed system to a left handed one.
  32519. */
  32520. Geometry.prototype.toLeftHanded = function () {
  32521. // Flip faces
  32522. var tIndices = this.getIndices(false);
  32523. if (tIndices != null && tIndices.length > 0) {
  32524. for (var i = 0; i < tIndices.length; i += 3) {
  32525. var tTemp = tIndices[i + 0];
  32526. tIndices[i + 0] = tIndices[i + 2];
  32527. tIndices[i + 2] = tTemp;
  32528. }
  32529. this.setIndices(tIndices);
  32530. }
  32531. // Negate position.z
  32532. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32533. if (tPositions != null && tPositions.length > 0) {
  32534. for (var i = 0; i < tPositions.length; i += 3) {
  32535. tPositions[i + 2] = -tPositions[i + 2];
  32536. }
  32537. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32538. }
  32539. // Negate normal.z
  32540. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32541. if (tNormals != null && tNormals.length > 0) {
  32542. for (var i = 0; i < tNormals.length; i += 3) {
  32543. tNormals[i + 2] = -tNormals[i + 2];
  32544. }
  32545. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32546. }
  32547. };
  32548. Geometry.prototype.isDisposed = function () {
  32549. return this._isDisposed;
  32550. };
  32551. Geometry.prototype.dispose = function () {
  32552. var meshes = this._meshes;
  32553. var numOfMeshes = meshes.length;
  32554. var index;
  32555. for (index = 0; index < numOfMeshes; index++) {
  32556. this.releaseForMesh(meshes[index]);
  32557. }
  32558. this._meshes = [];
  32559. for (var kind in this._vertexBuffers) {
  32560. this._vertexBuffers[kind].dispose();
  32561. }
  32562. this._vertexBuffers = [];
  32563. this._totalVertices = 0;
  32564. if (this._indexBuffer) {
  32565. this._engine._releaseBuffer(this._indexBuffer);
  32566. }
  32567. this._indexBuffer = null;
  32568. this._indices = [];
  32569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32570. this.delayLoadingFile = null;
  32571. this._delayLoadingFunction = null;
  32572. this._delayInfo = [];
  32573. this._boundingInfo = null;
  32574. this._scene.removeGeometry(this);
  32575. this._isDisposed = true;
  32576. };
  32577. Geometry.prototype.copy = function (id) {
  32578. var vertexData = new BABYLON.VertexData();
  32579. vertexData.indices = [];
  32580. var indices = this.getIndices();
  32581. for (var index = 0; index < indices.length; index++) {
  32582. vertexData.indices.push(indices[index]);
  32583. }
  32584. var updatable = false;
  32585. var stopChecking = false;
  32586. var kind;
  32587. for (kind in this._vertexBuffers) {
  32588. // using slice() to make a copy of the array and not just reference it
  32589. var data = this.getVerticesData(kind);
  32590. if (data instanceof Float32Array) {
  32591. vertexData.set(new Float32Array(data), kind);
  32592. }
  32593. else {
  32594. vertexData.set(data.slice(0), kind);
  32595. }
  32596. if (!stopChecking) {
  32597. updatable = this.getVertexBuffer(kind).isUpdatable();
  32598. stopChecking = !updatable;
  32599. }
  32600. }
  32601. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  32602. geometry.delayLoadState = this.delayLoadState;
  32603. geometry.delayLoadingFile = this.delayLoadingFile;
  32604. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32605. for (kind in this._delayInfo) {
  32606. geometry._delayInfo = geometry._delayInfo || [];
  32607. geometry._delayInfo.push(kind);
  32608. }
  32609. // Bounding info
  32610. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32611. return geometry;
  32612. };
  32613. Geometry.prototype.serialize = function () {
  32614. var serializationObject = {};
  32615. serializationObject.id = this.id;
  32616. if (BABYLON.Tags.HasTags(this)) {
  32617. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32618. }
  32619. return serializationObject;
  32620. };
  32621. Geometry.prototype.serializeVerticeData = function () {
  32622. var serializationObject = this.serialize();
  32623. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32624. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32625. }
  32626. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32627. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32628. }
  32629. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32630. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32631. }
  32632. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32633. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  32634. }
  32635. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32636. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  32637. }
  32638. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32639. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  32640. }
  32641. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32642. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  32643. }
  32644. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32645. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  32646. }
  32647. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32648. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32649. }
  32650. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32651. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32652. serializationObject.matricesIndices._isExpanded = true;
  32653. }
  32654. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32655. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32656. }
  32657. serializationObject.indices = this.getIndices();
  32658. return serializationObject;
  32659. };
  32660. // Statics
  32661. Geometry.ExtractFromMesh = function (mesh, id) {
  32662. var geometry = mesh._geometry;
  32663. if (!geometry) {
  32664. return null;
  32665. }
  32666. return geometry.copy(id);
  32667. };
  32668. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32669. // be aware Math.random() could cause collisions
  32670. Geometry.RandomId = function () {
  32671. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  32672. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  32673. return v.toString(16);
  32674. });
  32675. };
  32676. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32677. var scene = mesh.getScene();
  32678. // Geometry
  32679. var geometryId = parsedGeometry.geometryId;
  32680. if (geometryId) {
  32681. var geometry = scene.getGeometryByID(geometryId);
  32682. if (geometry) {
  32683. geometry.applyToMesh(mesh);
  32684. }
  32685. }
  32686. else if (parsedGeometry instanceof ArrayBuffer) {
  32687. var binaryInfo = mesh._binaryInfo;
  32688. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32689. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32690. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32691. }
  32692. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32693. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32694. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32695. }
  32696. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32697. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32698. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32699. }
  32700. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32701. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32702. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32703. }
  32704. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32705. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32706. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32707. }
  32708. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32709. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32710. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32711. }
  32712. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32713. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32714. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32715. }
  32716. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32717. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32718. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32719. }
  32720. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32721. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32722. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32723. }
  32724. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32725. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32726. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32727. }
  32728. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32729. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32730. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32731. }
  32732. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32733. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32734. mesh.setIndices(indicesData);
  32735. }
  32736. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32737. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32738. mesh.subMeshes = [];
  32739. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32740. var materialIndex = subMeshesData[(i * 5) + 0];
  32741. var verticesStart = subMeshesData[(i * 5) + 1];
  32742. var verticesCount = subMeshesData[(i * 5) + 2];
  32743. var indexStart = subMeshesData[(i * 5) + 3];
  32744. var indexCount = subMeshesData[(i * 5) + 4];
  32745. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32746. }
  32747. }
  32748. }
  32749. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32750. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  32751. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  32752. if (parsedGeometry.uvs) {
  32753. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  32754. }
  32755. if (parsedGeometry.uvs2) {
  32756. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  32757. }
  32758. if (parsedGeometry.uvs3) {
  32759. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  32760. }
  32761. if (parsedGeometry.uvs4) {
  32762. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  32763. }
  32764. if (parsedGeometry.uvs5) {
  32765. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  32766. }
  32767. if (parsedGeometry.uvs6) {
  32768. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  32769. }
  32770. if (parsedGeometry.colors) {
  32771. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  32772. }
  32773. if (parsedGeometry.matricesIndices) {
  32774. if (!parsedGeometry.matricesIndices._isExpanded) {
  32775. var floatIndices = [];
  32776. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32777. var matricesIndex = parsedGeometry.matricesIndices[i];
  32778. floatIndices.push(matricesIndex & 0x000000FF);
  32779. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32780. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32781. floatIndices.push(matricesIndex >> 24);
  32782. }
  32783. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  32784. }
  32785. else {
  32786. delete parsedGeometry.matricesIndices._isExpanded;
  32787. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  32788. }
  32789. }
  32790. if (parsedGeometry.matricesIndicesExtra) {
  32791. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32792. var floatIndices = [];
  32793. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32794. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32795. floatIndices.push(matricesIndex & 0x000000FF);
  32796. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32797. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32798. floatIndices.push(matricesIndex >> 24);
  32799. }
  32800. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  32801. }
  32802. else {
  32803. delete parsedGeometry.matricesIndices._isExpanded;
  32804. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  32805. }
  32806. }
  32807. if (parsedGeometry.matricesWeights) {
  32808. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  32809. }
  32810. if (parsedGeometry.matricesWeightsExtra) {
  32811. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  32812. }
  32813. mesh.setIndices(parsedGeometry.indices);
  32814. }
  32815. // SubMeshes
  32816. if (parsedGeometry.subMeshes) {
  32817. mesh.subMeshes = [];
  32818. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32819. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32820. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32821. }
  32822. }
  32823. // Flat shading
  32824. if (mesh._shouldGenerateFlatShading) {
  32825. mesh.convertToFlatShadedMesh();
  32826. delete mesh._shouldGenerateFlatShading;
  32827. }
  32828. // Update
  32829. mesh.computeWorldMatrix(true);
  32830. // Octree
  32831. if (scene['_selectionOctree']) {
  32832. scene['_selectionOctree'].addMesh(mesh);
  32833. }
  32834. };
  32835. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32836. if (scene.getGeometryByID(parsedVertexData.id)) {
  32837. return null; // null since geometry could be something else than a box...
  32838. }
  32839. var geometry = new Geometry(parsedVertexData.id, scene);
  32840. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32841. if (parsedVertexData.delayLoadingFile) {
  32842. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32843. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32844. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32845. geometry._delayInfo = [];
  32846. if (parsedVertexData.hasUVs) {
  32847. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32848. }
  32849. if (parsedVertexData.hasUVs2) {
  32850. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32851. }
  32852. if (parsedVertexData.hasUVs3) {
  32853. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32854. }
  32855. if (parsedVertexData.hasUVs4) {
  32856. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32857. }
  32858. if (parsedVertexData.hasUVs5) {
  32859. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32860. }
  32861. if (parsedVertexData.hasUVs6) {
  32862. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32863. }
  32864. if (parsedVertexData.hasColors) {
  32865. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32866. }
  32867. if (parsedVertexData.hasMatricesIndices) {
  32868. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32869. }
  32870. if (parsedVertexData.hasMatricesWeights) {
  32871. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32872. }
  32873. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32874. }
  32875. else {
  32876. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32877. }
  32878. scene.pushGeometry(geometry, true);
  32879. return geometry;
  32880. };
  32881. return Geometry;
  32882. })();
  32883. BABYLON.Geometry = Geometry;
  32884. /////// Primitives //////////////////////////////////////////////
  32885. var Geometry;
  32886. (function (Geometry) {
  32887. var Primitives;
  32888. (function (Primitives) {
  32889. /// Abstract class
  32890. var _Primitive = (function (_super) {
  32891. __extends(_Primitive, _super);
  32892. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  32893. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  32894. this._canBeRegenerated = _canBeRegenerated;
  32895. this._beingRegenerated = true;
  32896. this.regenerate();
  32897. this._beingRegenerated = false;
  32898. }
  32899. _Primitive.prototype.canBeRegenerated = function () {
  32900. return this._canBeRegenerated;
  32901. };
  32902. _Primitive.prototype.regenerate = function () {
  32903. if (!this._canBeRegenerated) {
  32904. return;
  32905. }
  32906. this._beingRegenerated = true;
  32907. this.setAllVerticesData(this._regenerateVertexData(), false);
  32908. this._beingRegenerated = false;
  32909. };
  32910. _Primitive.prototype.asNewGeometry = function (id) {
  32911. return _super.prototype.copy.call(this, id);
  32912. };
  32913. // overrides
  32914. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  32915. if (!this._beingRegenerated) {
  32916. return;
  32917. }
  32918. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32919. };
  32920. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  32921. if (!this._beingRegenerated) {
  32922. return;
  32923. }
  32924. _super.prototype.setVerticesData.call(this, kind, data, false);
  32925. };
  32926. // to override
  32927. // protected
  32928. _Primitive.prototype._regenerateVertexData = function () {
  32929. throw new Error("Abstract method");
  32930. };
  32931. _Primitive.prototype.copy = function (id) {
  32932. throw new Error("Must be overriden in sub-classes.");
  32933. };
  32934. _Primitive.prototype.serialize = function () {
  32935. var serializationObject = _super.prototype.serialize.call(this);
  32936. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32937. return serializationObject;
  32938. };
  32939. return _Primitive;
  32940. })(Geometry);
  32941. Primitives._Primitive = _Primitive;
  32942. var Ribbon = (function (_super) {
  32943. __extends(Ribbon, _super);
  32944. // Members
  32945. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32946. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32947. _super.call(this, id, scene, canBeRegenerated, mesh);
  32948. this.pathArray = pathArray;
  32949. this.closeArray = closeArray;
  32950. this.closePath = closePath;
  32951. this.offset = offset;
  32952. this.side = side;
  32953. }
  32954. Ribbon.prototype._regenerateVertexData = function () {
  32955. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32956. };
  32957. Ribbon.prototype.copy = function (id) {
  32958. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  32959. };
  32960. return Ribbon;
  32961. })(_Primitive);
  32962. Primitives.Ribbon = Ribbon;
  32963. var Box = (function (_super) {
  32964. __extends(Box, _super);
  32965. // Members
  32966. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32967. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32968. _super.call(this, id, scene, canBeRegenerated, mesh);
  32969. this.size = size;
  32970. this.side = side;
  32971. }
  32972. Box.prototype._regenerateVertexData = function () {
  32973. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32974. };
  32975. Box.prototype.copy = function (id) {
  32976. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32977. };
  32978. Box.prototype.serialize = function () {
  32979. var serializationObject = _super.prototype.serialize.call(this);
  32980. serializationObject.size = this.size;
  32981. return serializationObject;
  32982. };
  32983. Box.Parse = function (parsedBox, scene) {
  32984. if (scene.getGeometryByID(parsedBox.id)) {
  32985. return null; // null since geometry could be something else than a box...
  32986. }
  32987. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32988. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32989. scene.pushGeometry(box, true);
  32990. return box;
  32991. };
  32992. return Box;
  32993. })(_Primitive);
  32994. Primitives.Box = Box;
  32995. var Sphere = (function (_super) {
  32996. __extends(Sphere, _super);
  32997. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32998. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32999. _super.call(this, id, scene, canBeRegenerated, mesh);
  33000. this.segments = segments;
  33001. this.diameter = diameter;
  33002. this.side = side;
  33003. }
  33004. Sphere.prototype._regenerateVertexData = function () {
  33005. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33006. };
  33007. Sphere.prototype.copy = function (id) {
  33008. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33009. };
  33010. Sphere.prototype.serialize = function () {
  33011. var serializationObject = _super.prototype.serialize.call(this);
  33012. serializationObject.segments = this.segments;
  33013. serializationObject.diameter = this.diameter;
  33014. return serializationObject;
  33015. };
  33016. Sphere.Parse = function (parsedSphere, scene) {
  33017. if (scene.getGeometryByID(parsedSphere.id)) {
  33018. return null; // null since geometry could be something else than a sphere...
  33019. }
  33020. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33021. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33022. scene.pushGeometry(sphere, true);
  33023. return sphere;
  33024. };
  33025. return Sphere;
  33026. })(_Primitive);
  33027. Primitives.Sphere = Sphere;
  33028. var Disc = (function (_super) {
  33029. __extends(Disc, _super);
  33030. // Members
  33031. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  33032. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33033. _super.call(this, id, scene, canBeRegenerated, mesh);
  33034. this.radius = radius;
  33035. this.tessellation = tessellation;
  33036. this.side = side;
  33037. }
  33038. Disc.prototype._regenerateVertexData = function () {
  33039. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33040. };
  33041. Disc.prototype.copy = function (id) {
  33042. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33043. };
  33044. return Disc;
  33045. })(_Primitive);
  33046. Primitives.Disc = Disc;
  33047. var Cylinder = (function (_super) {
  33048. __extends(Cylinder, _super);
  33049. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  33050. if (subdivisions === void 0) { subdivisions = 1; }
  33051. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33052. _super.call(this, id, scene, canBeRegenerated, mesh);
  33053. this.height = height;
  33054. this.diameterTop = diameterTop;
  33055. this.diameterBottom = diameterBottom;
  33056. this.tessellation = tessellation;
  33057. this.subdivisions = subdivisions;
  33058. this.side = side;
  33059. }
  33060. Cylinder.prototype._regenerateVertexData = function () {
  33061. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33062. };
  33063. Cylinder.prototype.copy = function (id) {
  33064. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33065. };
  33066. Cylinder.prototype.serialize = function () {
  33067. var serializationObject = _super.prototype.serialize.call(this);
  33068. serializationObject.height = this.height;
  33069. serializationObject.diameterTop = this.diameterTop;
  33070. serializationObject.diameterBottom = this.diameterBottom;
  33071. serializationObject.tessellation = this.tessellation;
  33072. return serializationObject;
  33073. };
  33074. Cylinder.Parse = function (parsedCylinder, scene) {
  33075. if (scene.getGeometryByID(parsedCylinder.id)) {
  33076. return null; // null since geometry could be something else than a cylinder...
  33077. }
  33078. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33079. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33080. scene.pushGeometry(cylinder, true);
  33081. return cylinder;
  33082. };
  33083. return Cylinder;
  33084. })(_Primitive);
  33085. Primitives.Cylinder = Cylinder;
  33086. var Torus = (function (_super) {
  33087. __extends(Torus, _super);
  33088. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  33089. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33090. _super.call(this, id, scene, canBeRegenerated, mesh);
  33091. this.diameter = diameter;
  33092. this.thickness = thickness;
  33093. this.tessellation = tessellation;
  33094. this.side = side;
  33095. }
  33096. Torus.prototype._regenerateVertexData = function () {
  33097. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33098. };
  33099. Torus.prototype.copy = function (id) {
  33100. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33101. };
  33102. Torus.prototype.serialize = function () {
  33103. var serializationObject = _super.prototype.serialize.call(this);
  33104. serializationObject.diameter = this.diameter;
  33105. serializationObject.thickness = this.thickness;
  33106. serializationObject.tessellation = this.tessellation;
  33107. return serializationObject;
  33108. };
  33109. Torus.Parse = function (parsedTorus, scene) {
  33110. if (scene.getGeometryByID(parsedTorus.id)) {
  33111. return null; // null since geometry could be something else than a torus...
  33112. }
  33113. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33114. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33115. scene.pushGeometry(torus, true);
  33116. return torus;
  33117. };
  33118. return Torus;
  33119. })(_Primitive);
  33120. Primitives.Torus = Torus;
  33121. var Ground = (function (_super) {
  33122. __extends(Ground, _super);
  33123. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  33124. _super.call(this, id, scene, canBeRegenerated, mesh);
  33125. this.width = width;
  33126. this.height = height;
  33127. this.subdivisions = subdivisions;
  33128. }
  33129. Ground.prototype._regenerateVertexData = function () {
  33130. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33131. };
  33132. Ground.prototype.copy = function (id) {
  33133. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33134. };
  33135. Ground.prototype.serialize = function () {
  33136. var serializationObject = _super.prototype.serialize.call(this);
  33137. serializationObject.width = this.width;
  33138. serializationObject.height = this.height;
  33139. serializationObject.subdivisions = this.subdivisions;
  33140. return serializationObject;
  33141. };
  33142. Ground.Parse = function (parsedGround, scene) {
  33143. if (scene.getGeometryByID(parsedGround.id)) {
  33144. return null; // null since geometry could be something else than a ground...
  33145. }
  33146. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33147. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33148. scene.pushGeometry(ground, true);
  33149. return ground;
  33150. };
  33151. return Ground;
  33152. })(_Primitive);
  33153. Primitives.Ground = Ground;
  33154. var TiledGround = (function (_super) {
  33155. __extends(TiledGround, _super);
  33156. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  33157. _super.call(this, id, scene, canBeRegenerated, mesh);
  33158. this.xmin = xmin;
  33159. this.zmin = zmin;
  33160. this.xmax = xmax;
  33161. this.zmax = zmax;
  33162. this.subdivisions = subdivisions;
  33163. this.precision = precision;
  33164. }
  33165. TiledGround.prototype._regenerateVertexData = function () {
  33166. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33167. };
  33168. TiledGround.prototype.copy = function (id) {
  33169. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33170. };
  33171. return TiledGround;
  33172. })(_Primitive);
  33173. Primitives.TiledGround = TiledGround;
  33174. var Plane = (function (_super) {
  33175. __extends(Plane, _super);
  33176. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  33177. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33178. _super.call(this, id, scene, canBeRegenerated, mesh);
  33179. this.size = size;
  33180. this.side = side;
  33181. }
  33182. Plane.prototype._regenerateVertexData = function () {
  33183. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33184. };
  33185. Plane.prototype.copy = function (id) {
  33186. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33187. };
  33188. Plane.prototype.serialize = function () {
  33189. var serializationObject = _super.prototype.serialize.call(this);
  33190. serializationObject.size = this.size;
  33191. return serializationObject;
  33192. };
  33193. Plane.Parse = function (parsedPlane, scene) {
  33194. if (scene.getGeometryByID(parsedPlane.id)) {
  33195. return null; // null since geometry could be something else than a ground...
  33196. }
  33197. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33198. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33199. scene.pushGeometry(plane, true);
  33200. return plane;
  33201. };
  33202. return Plane;
  33203. })(_Primitive);
  33204. Primitives.Plane = Plane;
  33205. var TorusKnot = (function (_super) {
  33206. __extends(TorusKnot, _super);
  33207. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  33208. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33209. _super.call(this, id, scene, canBeRegenerated, mesh);
  33210. this.radius = radius;
  33211. this.tube = tube;
  33212. this.radialSegments = radialSegments;
  33213. this.tubularSegments = tubularSegments;
  33214. this.p = p;
  33215. this.q = q;
  33216. this.side = side;
  33217. }
  33218. TorusKnot.prototype._regenerateVertexData = function () {
  33219. 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 });
  33220. };
  33221. TorusKnot.prototype.copy = function (id) {
  33222. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33223. };
  33224. TorusKnot.prototype.serialize = function () {
  33225. var serializationObject = _super.prototype.serialize.call(this);
  33226. serializationObject.radius = this.radius;
  33227. serializationObject.tube = this.tube;
  33228. serializationObject.radialSegments = this.radialSegments;
  33229. serializationObject.tubularSegments = this.tubularSegments;
  33230. serializationObject.p = this.p;
  33231. serializationObject.q = this.q;
  33232. return serializationObject;
  33233. };
  33234. ;
  33235. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  33236. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33237. return null; // null since geometry could be something else than a ground...
  33238. }
  33239. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33240. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33241. scene.pushGeometry(torusKnot, true);
  33242. return torusKnot;
  33243. };
  33244. return TorusKnot;
  33245. })(_Primitive);
  33246. Primitives.TorusKnot = TorusKnot;
  33247. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  33248. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  33249. })(BABYLON || (BABYLON = {}));
  33250. var BABYLON;
  33251. (function (BABYLON) {
  33252. var GroundMesh = (function (_super) {
  33253. __extends(GroundMesh, _super);
  33254. function GroundMesh(name, scene) {
  33255. _super.call(this, name, scene);
  33256. this.generateOctree = false;
  33257. this._worldInverse = new BABYLON.Matrix();
  33258. }
  33259. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  33260. get: function () {
  33261. return this._subdivisions;
  33262. },
  33263. enumerable: true,
  33264. configurable: true
  33265. });
  33266. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  33267. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  33268. this._subdivisions = chunksCount;
  33269. this.subdivide(this._subdivisions);
  33270. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  33271. };
  33272. /**
  33273. * Returns a height (y) value in the Worl system :
  33274. * the ground altitude at the coordinates (x, z) expressed in the World system.
  33275. * Returns the ground y position if (x, z) are outside the ground surface.
  33276. * Not pertinent if the ground is rotated.
  33277. */
  33278. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  33279. // express x and y in the ground local system
  33280. x -= this.position.x;
  33281. z -= this.position.z;
  33282. x /= this.scaling.x;
  33283. z /= this.scaling.z;
  33284. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33285. return this.position.y;
  33286. }
  33287. if (!this._heightQuads || this._heightQuads.length == 0) {
  33288. this._initHeightQuads();
  33289. this._computeHeightQuads();
  33290. }
  33291. var facet = this._getFacetAt(x, z);
  33292. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  33293. // return y in the World system
  33294. return y * this.scaling.y + this.position.y;
  33295. };
  33296. /**
  33297. * Returns a normalized vector (Vector3) orthogonal to the ground
  33298. * at the ground coordinates (x, z) expressed in the World system.
  33299. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  33300. * Not pertinent if the ground is rotated.
  33301. */
  33302. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  33303. var normal = new BABYLON.Vector3(0, 1, 0);
  33304. this.getNormalAtCoordinatesToRef(x, z, normal);
  33305. return normal;
  33306. };
  33307. /**
  33308. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  33309. * at the ground coordinates (x, z) expressed in the World system.
  33310. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  33311. * Not pertinent if the ground is rotated.
  33312. */
  33313. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  33314. // express x and y in the ground local system
  33315. x -= this.position.x;
  33316. z -= this.position.z;
  33317. x /= this.scaling.x;
  33318. z /= this.scaling.z;
  33319. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33320. return;
  33321. }
  33322. if (!this._heightQuads || this._heightQuads.length == 0) {
  33323. this._initHeightQuads();
  33324. this._computeHeightQuads();
  33325. }
  33326. var facet = this._getFacetAt(x, z);
  33327. ref.x = facet.x;
  33328. ref.y = facet.y;
  33329. ref.z = facet.z;
  33330. };
  33331. /**
  33332. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  33333. * if the ground has been updated.
  33334. * This can be used in the render loop
  33335. */
  33336. GroundMesh.prototype.updateCoordinateHeights = function () {
  33337. if (!this._heightQuads || this._heightQuads.length == 0) {
  33338. this._initHeightQuads();
  33339. }
  33340. this._computeHeightQuads();
  33341. };
  33342. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  33343. GroundMesh.prototype._getFacetAt = function (x, z) {
  33344. // retrieve col and row from x, z coordinates in the ground local system
  33345. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  33346. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  33347. var quad = this._heightQuads[row * this._subdivisions + col];
  33348. var facet;
  33349. if (z < quad.slope.x * x + quad.slope.y) {
  33350. facet = quad.facet1;
  33351. }
  33352. else {
  33353. facet = quad.facet2;
  33354. }
  33355. return facet;
  33356. };
  33357. // Creates and populates the heightMap array with "facet" elements :
  33358. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  33359. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  33360. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  33361. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  33362. GroundMesh.prototype._initHeightQuads = function () {
  33363. this._heightQuads = new Array();
  33364. for (var row = 0; row < this._subdivisions; row++) {
  33365. for (var col = 0; col < this._subdivisions; col++) {
  33366. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  33367. this._heightQuads[row * this._subdivisions + col] = quad;
  33368. }
  33369. }
  33370. };
  33371. // Compute each quad element values and update the the heightMap array :
  33372. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  33373. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  33374. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  33375. GroundMesh.prototype._computeHeightQuads = function () {
  33376. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33377. var v1 = BABYLON.Tmp.Vector3[0];
  33378. var v2 = BABYLON.Tmp.Vector3[1];
  33379. var v3 = BABYLON.Tmp.Vector3[2];
  33380. var v4 = BABYLON.Tmp.Vector3[3];
  33381. var v1v2 = BABYLON.Tmp.Vector3[4];
  33382. var v1v3 = BABYLON.Tmp.Vector3[5];
  33383. var v1v4 = BABYLON.Tmp.Vector3[6];
  33384. var norm1 = BABYLON.Tmp.Vector3[7];
  33385. var norm2 = BABYLON.Tmp.Vector3[8];
  33386. var i = 0;
  33387. var j = 0;
  33388. var k = 0;
  33389. var cd = 0; // 2D slope coefficient : z = cd * x + h
  33390. var h = 0;
  33391. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  33392. var d2 = 0;
  33393. for (var row = 0; row < this._subdivisions; row++) {
  33394. for (var col = 0; col < this._subdivisions; col++) {
  33395. i = col * 3;
  33396. j = row * (this._subdivisions + 1) * 3;
  33397. k = (row + 1) * (this._subdivisions + 1) * 3;
  33398. v1.x = positions[j + i];
  33399. v1.y = positions[j + i + 1];
  33400. v1.z = positions[j + i + 2];
  33401. v2.x = positions[j + i + 3];
  33402. v2.y = positions[j + i + 4];
  33403. v2.z = positions[j + i + 5];
  33404. v3.x = positions[k + i];
  33405. v3.y = positions[k + i + 1];
  33406. v3.z = positions[k + i + 2];
  33407. v4.x = positions[k + i + 3];
  33408. v4.y = positions[k + i + 4];
  33409. v4.z = positions[k + i + 5];
  33410. // 2D slope V1V4
  33411. cd = (v4.z - v1.z) / (v4.x - v1.x);
  33412. h = v1.z - cd * v1.x; // v1 belongs to the slope
  33413. // facet equations :
  33414. // we compute each facet normal vector
  33415. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  33416. // we compute the value d by applying the equation to v1 which belongs to the plane
  33417. // then we store the facet equation in a Vector4
  33418. v2.subtractToRef(v1, v1v2);
  33419. v3.subtractToRef(v1, v1v3);
  33420. v4.subtractToRef(v1, v1v4);
  33421. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  33422. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  33423. norm1.normalize();
  33424. norm2.normalize();
  33425. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  33426. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  33427. var quad = this._heightQuads[row * this._subdivisions + col];
  33428. quad.slope.copyFromFloats(cd, h);
  33429. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  33430. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  33431. }
  33432. }
  33433. };
  33434. return GroundMesh;
  33435. })(BABYLON.Mesh);
  33436. BABYLON.GroundMesh = GroundMesh;
  33437. })(BABYLON || (BABYLON = {}));
  33438. var BABYLON;
  33439. (function (BABYLON) {
  33440. var LinesMesh = (function (_super) {
  33441. __extends(LinesMesh, _super);
  33442. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  33443. if (parent === void 0) { parent = null; }
  33444. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  33445. this.color = new BABYLON.Color3(1, 1, 1);
  33446. this.alpha = 1;
  33447. if (source) {
  33448. this.color = source.color.clone();
  33449. this.alpha = source.alpha;
  33450. }
  33451. this._intersectionThreshold = 0.1;
  33452. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  33453. attributes: ["position"],
  33454. uniforms: ["worldViewProjection", "color"],
  33455. needAlphaBlending: true
  33456. });
  33457. }
  33458. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  33459. /**
  33460. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33461. * This margin is expressed in world space coordinates, so its value may vary.
  33462. * Default value is 0.1
  33463. * @returns the intersection Threshold value.
  33464. */
  33465. get: function () {
  33466. return this._intersectionThreshold;
  33467. },
  33468. /**
  33469. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33470. * This margin is expressed in world space coordinates, so its value may vary.
  33471. * @param value the new threshold to apply
  33472. */
  33473. set: function (value) {
  33474. if (this._intersectionThreshold === value) {
  33475. return;
  33476. }
  33477. this._intersectionThreshold = value;
  33478. if (this.geometry) {
  33479. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  33480. }
  33481. },
  33482. enumerable: true,
  33483. configurable: true
  33484. });
  33485. Object.defineProperty(LinesMesh.prototype, "material", {
  33486. get: function () {
  33487. return this._colorShader;
  33488. },
  33489. enumerable: true,
  33490. configurable: true
  33491. });
  33492. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  33493. get: function () {
  33494. return false;
  33495. },
  33496. enumerable: true,
  33497. configurable: true
  33498. });
  33499. LinesMesh.prototype.createInstance = function (name) {
  33500. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  33501. return null;
  33502. };
  33503. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  33504. var engine = this.getScene().getEngine();
  33505. var indexToBind = this._geometry.getIndexBuffer();
  33506. // VBOs
  33507. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  33508. // Color
  33509. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  33510. };
  33511. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  33512. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  33513. return;
  33514. }
  33515. var engine = this.getScene().getEngine();
  33516. // Draw order
  33517. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  33518. };
  33519. LinesMesh.prototype.dispose = function (doNotRecurse) {
  33520. this._colorShader.dispose();
  33521. _super.prototype.dispose.call(this, doNotRecurse);
  33522. };
  33523. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  33524. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  33525. };
  33526. return LinesMesh;
  33527. })(BABYLON.Mesh);
  33528. BABYLON.LinesMesh = LinesMesh;
  33529. })(BABYLON || (BABYLON = {}));
  33530. var BABYLON;
  33531. (function (BABYLON) {
  33532. var DefaultLoadingScreen = (function () {
  33533. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33534. var _this = this;
  33535. if (_loadingText === void 0) { _loadingText = ""; }
  33536. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33537. this._renderingCanvas = _renderingCanvas;
  33538. this._loadingText = _loadingText;
  33539. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33540. // Resize
  33541. this._resizeLoadingUI = function () {
  33542. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33543. _this._loadingDiv.style.position = "absolute";
  33544. _this._loadingDiv.style.left = canvasRect.left + "px";
  33545. _this._loadingDiv.style.top = canvasRect.top + "px";
  33546. _this._loadingDiv.style.width = canvasRect.width + "px";
  33547. _this._loadingDiv.style.height = canvasRect.height + "px";
  33548. };
  33549. }
  33550. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33551. var _this = this;
  33552. if (this._loadingDiv) {
  33553. // Do not add a loading screen if there is already one
  33554. return;
  33555. }
  33556. this._loadingDiv = document.createElement("div");
  33557. this._loadingDiv.id = "babylonjsLoadingDiv";
  33558. this._loadingDiv.style.opacity = "0";
  33559. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33560. // Loading text
  33561. this._loadingTextDiv = document.createElement("div");
  33562. this._loadingTextDiv.style.position = "absolute";
  33563. this._loadingTextDiv.style.left = "0";
  33564. this._loadingTextDiv.style.top = "50%";
  33565. this._loadingTextDiv.style.marginTop = "80px";
  33566. this._loadingTextDiv.style.width = "100%";
  33567. this._loadingTextDiv.style.height = "20px";
  33568. this._loadingTextDiv.style.fontFamily = "Arial";
  33569. this._loadingTextDiv.style.fontSize = "14px";
  33570. this._loadingTextDiv.style.color = "white";
  33571. this._loadingTextDiv.style.textAlign = "center";
  33572. this._loadingTextDiv.innerHTML = "Loading";
  33573. this._loadingDiv.appendChild(this._loadingTextDiv);
  33574. //set the predefined text
  33575. this._loadingTextDiv.innerHTML = this._loadingText;
  33576. // Loading img
  33577. var imgBack = new Image();
  33578. 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==";
  33579. imgBack.style.position = "absolute";
  33580. imgBack.style.left = "50%";
  33581. imgBack.style.top = "50%";
  33582. imgBack.style.marginLeft = "-50px";
  33583. imgBack.style.marginTop = "-50px";
  33584. imgBack.style.transition = "transform 1.0s ease";
  33585. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33586. var deg = 360;
  33587. var onTransitionEnd = function () {
  33588. deg += 360;
  33589. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33590. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33591. };
  33592. imgBack.addEventListener("transitionend", onTransitionEnd);
  33593. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33594. this._loadingDiv.appendChild(imgBack);
  33595. // front image
  33596. var imgFront = new Image();
  33597. 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=";
  33598. imgFront.style.position = "absolute";
  33599. imgFront.style.left = "50%";
  33600. imgFront.style.top = "50%";
  33601. imgFront.style.marginLeft = "-50px";
  33602. imgFront.style.marginTop = "-50px";
  33603. this._loadingDiv.appendChild(imgFront);
  33604. this._resizeLoadingUI();
  33605. window.addEventListener("resize", this._resizeLoadingUI);
  33606. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33607. document.body.appendChild(this._loadingDiv);
  33608. setTimeout(function () {
  33609. _this._loadingDiv.style.opacity = "1";
  33610. imgBack.style.transform = "rotateZ(360deg)";
  33611. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33612. }, 0);
  33613. };
  33614. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33615. var _this = this;
  33616. if (!this._loadingDiv) {
  33617. return;
  33618. }
  33619. var onTransitionEnd = function () {
  33620. if (!_this._loadingDiv) {
  33621. return;
  33622. }
  33623. document.body.removeChild(_this._loadingDiv);
  33624. window.removeEventListener("resize", _this._resizeLoadingUI);
  33625. _this._loadingDiv = null;
  33626. };
  33627. this._loadingDiv.style.opacity = "0";
  33628. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33629. };
  33630. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33631. set: function (text) {
  33632. this._loadingText = text;
  33633. if (this._loadingTextDiv) {
  33634. this._loadingTextDiv.innerHTML = this._loadingText;
  33635. }
  33636. },
  33637. enumerable: true,
  33638. configurable: true
  33639. });
  33640. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33641. get: function () {
  33642. return this._loadingDivBackgroundColor;
  33643. },
  33644. set: function (color) {
  33645. this._loadingDivBackgroundColor = color;
  33646. if (!this._loadingDiv) {
  33647. return;
  33648. }
  33649. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33650. },
  33651. enumerable: true,
  33652. configurable: true
  33653. });
  33654. return DefaultLoadingScreen;
  33655. })();
  33656. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33657. })(BABYLON || (BABYLON = {}));
  33658. var BABYLON;
  33659. (function (BABYLON) {
  33660. var AudioEngine = (function () {
  33661. function AudioEngine() {
  33662. this._audioContext = null;
  33663. this._audioContextInitialized = false;
  33664. this.canUseWebAudio = false;
  33665. this.WarnedWebAudioUnsupported = false;
  33666. this.unlocked = false;
  33667. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33668. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33669. this.canUseWebAudio = true;
  33670. }
  33671. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33672. this._unlockiOSaudio();
  33673. }
  33674. else {
  33675. this.unlocked = true;
  33676. }
  33677. }
  33678. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33679. get: function () {
  33680. if (!this._audioContextInitialized) {
  33681. this._initializeAudioContext();
  33682. }
  33683. return this._audioContext;
  33684. },
  33685. enumerable: true,
  33686. configurable: true
  33687. });
  33688. AudioEngine.prototype._unlockiOSaudio = function () {
  33689. var _this = this;
  33690. var unlockaudio = function () {
  33691. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33692. var source = _this.audioContext.createBufferSource();
  33693. source.buffer = buffer;
  33694. source.connect(_this.audioContext.destination);
  33695. source.start(0);
  33696. setTimeout(function () {
  33697. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33698. _this.unlocked = true;
  33699. window.removeEventListener('touchend', unlockaudio, false);
  33700. if (_this.onAudioUnlocked) {
  33701. _this.onAudioUnlocked();
  33702. }
  33703. }
  33704. }, 0);
  33705. };
  33706. window.addEventListener('touchend', unlockaudio, false);
  33707. };
  33708. AudioEngine.prototype._initializeAudioContext = function () {
  33709. try {
  33710. if (this.canUseWebAudio) {
  33711. this._audioContext = new AudioContext();
  33712. // create a global volume gain node
  33713. this.masterGain = this._audioContext.createGain();
  33714. this.masterGain.gain.value = 1;
  33715. this.masterGain.connect(this._audioContext.destination);
  33716. this._audioContextInitialized = true;
  33717. }
  33718. }
  33719. catch (e) {
  33720. this.canUseWebAudio = false;
  33721. BABYLON.Tools.Error("Web Audio: " + e.message);
  33722. }
  33723. };
  33724. AudioEngine.prototype.dispose = function () {
  33725. if (this.canUseWebAudio && this._audioContextInitialized) {
  33726. if (this._connectedAnalyser) {
  33727. this._connectedAnalyser.stopDebugCanvas();
  33728. this._connectedAnalyser.dispose();
  33729. this.masterGain.disconnect();
  33730. this.masterGain.connect(this._audioContext.destination);
  33731. this._connectedAnalyser = null;
  33732. }
  33733. this.masterGain.gain.value = 1;
  33734. }
  33735. this.WarnedWebAudioUnsupported = false;
  33736. };
  33737. AudioEngine.prototype.getGlobalVolume = function () {
  33738. if (this.canUseWebAudio && this._audioContextInitialized) {
  33739. return this.masterGain.gain.value;
  33740. }
  33741. else {
  33742. return -1;
  33743. }
  33744. };
  33745. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33746. if (this.canUseWebAudio && this._audioContextInitialized) {
  33747. this.masterGain.gain.value = newVolume;
  33748. }
  33749. };
  33750. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33751. if (this._connectedAnalyser) {
  33752. this._connectedAnalyser.stopDebugCanvas();
  33753. }
  33754. if (this.canUseWebAudio && this._audioContextInitialized) {
  33755. this._connectedAnalyser = analyser;
  33756. this.masterGain.disconnect();
  33757. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33758. }
  33759. };
  33760. return AudioEngine;
  33761. })();
  33762. BABYLON.AudioEngine = AudioEngine;
  33763. })(BABYLON || (BABYLON = {}));
  33764. var BABYLON;
  33765. (function (BABYLON) {
  33766. var Sound = (function () {
  33767. /**
  33768. * Create a sound and attach it to a scene
  33769. * @param name Name of your sound
  33770. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33771. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33772. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33773. */
  33774. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33775. var _this = this;
  33776. this.autoplay = false;
  33777. this.loop = false;
  33778. this.useCustomAttenuation = false;
  33779. this.spatialSound = false;
  33780. this.refDistance = 1;
  33781. this.rolloffFactor = 1;
  33782. this.maxDistance = 100;
  33783. this.distanceModel = "linear";
  33784. this._panningModel = "equalpower";
  33785. this._playbackRate = 1;
  33786. this._streaming = false;
  33787. this._startTime = 0;
  33788. this._startOffset = 0;
  33789. this._position = BABYLON.Vector3.Zero();
  33790. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33791. this._volume = 1;
  33792. this._isLoaded = false;
  33793. this._isReadyToPlay = false;
  33794. this.isPlaying = false;
  33795. this.isPaused = false;
  33796. this._isDirectional = false;
  33797. // Used if you'd like to create a directional sound.
  33798. // If not set, the sound will be omnidirectional
  33799. this._coneInnerAngle = 360;
  33800. this._coneOuterAngle = 360;
  33801. this._coneOuterGain = 0;
  33802. this._isOutputConnected = false;
  33803. this.name = name;
  33804. this._scene = scene;
  33805. this._readyToPlayCallback = readyToPlayCallback;
  33806. // Default custom attenuation function is a linear attenuation
  33807. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33808. if (currentDistance < maxDistance) {
  33809. return currentVolume * (1 - currentDistance / maxDistance);
  33810. }
  33811. else {
  33812. return 0;
  33813. }
  33814. };
  33815. if (options) {
  33816. this.autoplay = options.autoplay || false;
  33817. this.loop = options.loop || false;
  33818. // if volume === 0, we need another way to check this option
  33819. if (options.volume !== undefined) {
  33820. this._volume = options.volume;
  33821. }
  33822. this.spatialSound = options.spatialSound || false;
  33823. this.maxDistance = options.maxDistance || 100;
  33824. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33825. this.rolloffFactor = options.rolloffFactor || 1;
  33826. this.refDistance = options.refDistance || 1;
  33827. this.distanceModel = options.distanceModel || "linear";
  33828. this._playbackRate = options.playbackRate || 1;
  33829. this._streaming = options.streaming || false;
  33830. }
  33831. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33832. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33833. this._soundGain.gain.value = this._volume;
  33834. this._inputAudioNode = this._soundGain;
  33835. this._ouputAudioNode = this._soundGain;
  33836. if (this.spatialSound) {
  33837. this._createSpatialParameters();
  33838. }
  33839. this._scene.mainSoundTrack.AddSound(this);
  33840. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33841. if (urlOrArrayBuffer) {
  33842. // If it's an URL
  33843. if (typeof (urlOrArrayBuffer) === "string") {
  33844. // Loading sound using XHR2
  33845. if (!this._streaming) {
  33846. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33847. }
  33848. else {
  33849. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33850. this._htmlAudioElement.controls = false;
  33851. this._htmlAudioElement.loop = this.loop;
  33852. this._htmlAudioElement.crossOrigin = "anonymous";
  33853. this._htmlAudioElement.preload = "auto";
  33854. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33855. _this._isReadyToPlay = true;
  33856. if (_this.autoplay) {
  33857. _this.play();
  33858. }
  33859. if (_this._readyToPlayCallback) {
  33860. _this._readyToPlayCallback();
  33861. }
  33862. });
  33863. document.body.appendChild(this._htmlAudioElement);
  33864. }
  33865. }
  33866. else {
  33867. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33868. if (urlOrArrayBuffer.byteLength > 0) {
  33869. this._soundLoaded(urlOrArrayBuffer);
  33870. }
  33871. }
  33872. else {
  33873. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33874. }
  33875. }
  33876. }
  33877. }
  33878. else {
  33879. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33880. this._scene.mainSoundTrack.AddSound(this);
  33881. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33882. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33883. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33884. }
  33885. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33886. if (this._readyToPlayCallback) {
  33887. window.setTimeout(function () {
  33888. _this._readyToPlayCallback();
  33889. }, 1000);
  33890. }
  33891. }
  33892. }
  33893. Sound.prototype.dispose = function () {
  33894. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33895. if (this.isPlaying) {
  33896. this.stop();
  33897. }
  33898. this._isReadyToPlay = false;
  33899. if (this.soundTrackId === -1) {
  33900. this._scene.mainSoundTrack.RemoveSound(this);
  33901. }
  33902. else {
  33903. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33904. }
  33905. if (this._soundGain) {
  33906. this._soundGain.disconnect();
  33907. this._soundGain = null;
  33908. }
  33909. if (this._soundPanner) {
  33910. this._soundPanner.disconnect();
  33911. this._soundPanner = null;
  33912. }
  33913. if (this._soundSource) {
  33914. this._soundSource.disconnect();
  33915. this._soundSource = null;
  33916. }
  33917. this._audioBuffer = null;
  33918. if (this._htmlAudioElement) {
  33919. this._htmlAudioElement.pause();
  33920. this._htmlAudioElement.src = "";
  33921. document.body.removeChild(this._htmlAudioElement);
  33922. }
  33923. if (this._connectedMesh) {
  33924. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33925. this._connectedMesh = null;
  33926. }
  33927. }
  33928. };
  33929. Sound.prototype._soundLoaded = function (audioData) {
  33930. var _this = this;
  33931. this._isLoaded = true;
  33932. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33933. _this._audioBuffer = buffer;
  33934. _this._isReadyToPlay = true;
  33935. if (_this.autoplay) {
  33936. _this.play();
  33937. }
  33938. if (_this._readyToPlayCallback) {
  33939. _this._readyToPlayCallback();
  33940. }
  33941. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33942. };
  33943. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33944. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33945. this._audioBuffer = audioBuffer;
  33946. this._isReadyToPlay = true;
  33947. }
  33948. };
  33949. Sound.prototype.updateOptions = function (options) {
  33950. if (options) {
  33951. this.loop = options.loop || this.loop;
  33952. this.maxDistance = options.maxDistance || this.maxDistance;
  33953. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33954. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33955. this.refDistance = options.refDistance || this.refDistance;
  33956. this.distanceModel = options.distanceModel || this.distanceModel;
  33957. this._playbackRate = options.playbackRate || this._playbackRate;
  33958. this._updateSpatialParameters();
  33959. if (this.isPlaying) {
  33960. if (this._streaming) {
  33961. this._htmlAudioElement.playbackRate = this._playbackRate;
  33962. }
  33963. else {
  33964. this._soundSource.playbackRate.value = this._playbackRate;
  33965. }
  33966. }
  33967. }
  33968. };
  33969. Sound.prototype._createSpatialParameters = function () {
  33970. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33971. if (this._scene.headphone) {
  33972. this._panningModel = "HRTF";
  33973. }
  33974. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33975. this._updateSpatialParameters();
  33976. this._soundPanner.connect(this._ouputAudioNode);
  33977. this._inputAudioNode = this._soundPanner;
  33978. }
  33979. };
  33980. Sound.prototype._updateSpatialParameters = function () {
  33981. if (this.spatialSound) {
  33982. if (this.useCustomAttenuation) {
  33983. // Tricks to disable in a way embedded Web Audio attenuation
  33984. this._soundPanner.distanceModel = "linear";
  33985. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33986. this._soundPanner.refDistance = 1;
  33987. this._soundPanner.rolloffFactor = 1;
  33988. this._soundPanner.panningModel = this._panningModel;
  33989. }
  33990. else {
  33991. this._soundPanner.distanceModel = this.distanceModel;
  33992. this._soundPanner.maxDistance = this.maxDistance;
  33993. this._soundPanner.refDistance = this.refDistance;
  33994. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33995. this._soundPanner.panningModel = this._panningModel;
  33996. }
  33997. }
  33998. };
  33999. Sound.prototype.switchPanningModelToHRTF = function () {
  34000. this._panningModel = "HRTF";
  34001. this._switchPanningModel();
  34002. };
  34003. Sound.prototype.switchPanningModelToEqualPower = function () {
  34004. this._panningModel = "equalpower";
  34005. this._switchPanningModel();
  34006. };
  34007. Sound.prototype._switchPanningModel = function () {
  34008. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34009. this._soundPanner.panningModel = this._panningModel;
  34010. }
  34011. };
  34012. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34013. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34014. if (this._isOutputConnected) {
  34015. this._ouputAudioNode.disconnect();
  34016. }
  34017. this._ouputAudioNode.connect(soundTrackAudioNode);
  34018. this._isOutputConnected = true;
  34019. }
  34020. };
  34021. /**
  34022. * Transform this sound into a directional source
  34023. * @param coneInnerAngle Size of the inner cone in degree
  34024. * @param coneOuterAngle Size of the outer cone in degree
  34025. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34026. */
  34027. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34028. if (coneOuterAngle < coneInnerAngle) {
  34029. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34030. return;
  34031. }
  34032. this._coneInnerAngle = coneInnerAngle;
  34033. this._coneOuterAngle = coneOuterAngle;
  34034. this._coneOuterGain = coneOuterGain;
  34035. this._isDirectional = true;
  34036. if (this.isPlaying && this.loop) {
  34037. this.stop();
  34038. this.play();
  34039. }
  34040. };
  34041. Sound.prototype.setPosition = function (newPosition) {
  34042. this._position = newPosition;
  34043. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34044. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34045. }
  34046. };
  34047. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34048. this._localDirection = newLocalDirection;
  34049. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34050. this._updateDirection();
  34051. }
  34052. };
  34053. Sound.prototype._updateDirection = function () {
  34054. var mat = this._connectedMesh.getWorldMatrix();
  34055. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34056. direction.normalize();
  34057. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34058. };
  34059. Sound.prototype.updateDistanceFromListener = function () {
  34060. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34061. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34062. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34063. }
  34064. };
  34065. Sound.prototype.setAttenuationFunction = function (callback) {
  34066. this._customAttenuationFunction = callback;
  34067. };
  34068. /**
  34069. * Play the sound
  34070. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34071. */
  34072. Sound.prototype.play = function (time) {
  34073. var _this = this;
  34074. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34075. try {
  34076. if (this._startOffset < 0) {
  34077. time = -this._startOffset;
  34078. this._startOffset = 0;
  34079. }
  34080. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34081. if (!this._soundSource || !this._streamingSource) {
  34082. if (this.spatialSound) {
  34083. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34084. if (this._isDirectional) {
  34085. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34086. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34087. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34088. if (this._connectedMesh) {
  34089. this._updateDirection();
  34090. }
  34091. else {
  34092. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34093. }
  34094. }
  34095. }
  34096. }
  34097. if (this._streaming) {
  34098. if (!this._streamingSource) {
  34099. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34100. this._htmlAudioElement.onended = function () { _this._onended(); };
  34101. this._htmlAudioElement.playbackRate = this._playbackRate;
  34102. }
  34103. this._streamingSource.disconnect();
  34104. this._streamingSource.connect(this._inputAudioNode);
  34105. this._htmlAudioElement.play();
  34106. }
  34107. else {
  34108. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34109. this._soundSource.buffer = this._audioBuffer;
  34110. this._soundSource.connect(this._inputAudioNode);
  34111. this._soundSource.loop = this.loop;
  34112. this._soundSource.playbackRate.value = this._playbackRate;
  34113. this._soundSource.onended = function () { _this._onended(); };
  34114. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34115. }
  34116. this._startTime = startTime;
  34117. this.isPlaying = true;
  34118. this.isPaused = false;
  34119. }
  34120. catch (ex) {
  34121. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34122. }
  34123. }
  34124. };
  34125. Sound.prototype._onended = function () {
  34126. this.isPlaying = false;
  34127. if (this.onended) {
  34128. this.onended();
  34129. }
  34130. };
  34131. /**
  34132. * Stop the sound
  34133. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34134. */
  34135. Sound.prototype.stop = function (time) {
  34136. if (this.isPlaying) {
  34137. if (this._streaming) {
  34138. this._htmlAudioElement.pause();
  34139. // Test needed for Firefox or it will generate an Invalid State Error
  34140. if (this._htmlAudioElement.currentTime > 0) {
  34141. this._htmlAudioElement.currentTime = 0;
  34142. }
  34143. }
  34144. else {
  34145. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34146. this._soundSource.stop(stopTime);
  34147. if (!this.isPaused) {
  34148. this._startOffset = 0;
  34149. }
  34150. }
  34151. this.isPlaying = false;
  34152. }
  34153. };
  34154. Sound.prototype.pause = function () {
  34155. if (this.isPlaying) {
  34156. this.isPaused = true;
  34157. if (this._streaming) {
  34158. this._htmlAudioElement.pause();
  34159. }
  34160. else {
  34161. this.stop(0);
  34162. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34163. }
  34164. }
  34165. };
  34166. Sound.prototype.setVolume = function (newVolume, time) {
  34167. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34168. if (time) {
  34169. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34170. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34171. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34172. }
  34173. else {
  34174. this._soundGain.gain.value = newVolume;
  34175. }
  34176. }
  34177. this._volume = newVolume;
  34178. };
  34179. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34180. this._playbackRate = newPlaybackRate;
  34181. if (this.isPlaying) {
  34182. if (this._streaming) {
  34183. this._htmlAudioElement.playbackRate = this._playbackRate;
  34184. }
  34185. else {
  34186. this._soundSource.playbackRate.value = this._playbackRate;
  34187. }
  34188. }
  34189. };
  34190. Sound.prototype.getVolume = function () {
  34191. return this._volume;
  34192. };
  34193. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34194. var _this = this;
  34195. if (this._connectedMesh) {
  34196. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34197. this._registerFunc = null;
  34198. }
  34199. this._connectedMesh = meshToConnectTo;
  34200. if (!this.spatialSound) {
  34201. this.spatialSound = true;
  34202. this._createSpatialParameters();
  34203. if (this.isPlaying && this.loop) {
  34204. this.stop();
  34205. this.play();
  34206. }
  34207. }
  34208. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34209. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34210. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34211. };
  34212. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34213. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34214. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34215. this._updateDirection();
  34216. }
  34217. };
  34218. Sound.prototype.clone = function () {
  34219. var _this = this;
  34220. if (!this._streaming) {
  34221. var setBufferAndRun = function () {
  34222. if (_this._isReadyToPlay) {
  34223. clonedSound._audioBuffer = _this.getAudioBuffer();
  34224. clonedSound._isReadyToPlay = true;
  34225. if (clonedSound.autoplay) {
  34226. clonedSound.play();
  34227. }
  34228. }
  34229. else {
  34230. window.setTimeout(setBufferAndRun, 300);
  34231. }
  34232. };
  34233. var currentOptions = {
  34234. autoplay: this.autoplay, loop: this.loop,
  34235. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34236. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34237. refDistance: this.refDistance, distanceModel: this.distanceModel
  34238. };
  34239. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34240. if (this.useCustomAttenuation) {
  34241. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34242. }
  34243. clonedSound.setPosition(this._position);
  34244. clonedSound.setPlaybackRate(this._playbackRate);
  34245. setBufferAndRun();
  34246. return clonedSound;
  34247. }
  34248. else {
  34249. return null;
  34250. }
  34251. };
  34252. Sound.prototype.getAudioBuffer = function () {
  34253. return this._audioBuffer;
  34254. };
  34255. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34256. var soundName = parsedSound.name;
  34257. var soundUrl;
  34258. if (parsedSound.url) {
  34259. soundUrl = rootUrl + parsedSound.url;
  34260. }
  34261. else {
  34262. soundUrl = rootUrl + soundName;
  34263. }
  34264. var options = {
  34265. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34266. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34267. rolloffFactor: parsedSound.rolloffFactor,
  34268. refDistance: parsedSound.refDistance,
  34269. distanceModel: parsedSound.distanceModel,
  34270. playbackRate: parsedSound.playbackRate
  34271. };
  34272. var newSound;
  34273. if (!sourceSound) {
  34274. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34275. scene._addPendingData(newSound);
  34276. }
  34277. else {
  34278. var setBufferAndRun = function () {
  34279. if (sourceSound._isReadyToPlay) {
  34280. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34281. newSound._isReadyToPlay = true;
  34282. if (newSound.autoplay) {
  34283. newSound.play();
  34284. }
  34285. }
  34286. else {
  34287. window.setTimeout(setBufferAndRun, 300);
  34288. }
  34289. };
  34290. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34291. setBufferAndRun();
  34292. }
  34293. if (parsedSound.position) {
  34294. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34295. newSound.setPosition(soundPosition);
  34296. }
  34297. if (parsedSound.isDirectional) {
  34298. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34299. if (parsedSound.localDirectionToMesh) {
  34300. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34301. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34302. }
  34303. }
  34304. if (parsedSound.connectedMeshId) {
  34305. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34306. if (connectedMesh) {
  34307. newSound.attachToMesh(connectedMesh);
  34308. }
  34309. }
  34310. return newSound;
  34311. };
  34312. return Sound;
  34313. })();
  34314. BABYLON.Sound = Sound;
  34315. })(BABYLON || (BABYLON = {}));
  34316. var BABYLON;
  34317. (function (BABYLON) {
  34318. var SoundTrack = (function () {
  34319. function SoundTrack(scene, options) {
  34320. this.id = -1;
  34321. this._isMainTrack = false;
  34322. this._isInitialized = false;
  34323. this._scene = scene;
  34324. this.soundCollection = new Array();
  34325. this._options = options;
  34326. if (!this._isMainTrack) {
  34327. this._scene.soundTracks.push(this);
  34328. this.id = this._scene.soundTracks.length - 1;
  34329. }
  34330. }
  34331. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34332. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34333. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34334. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34335. if (this._options) {
  34336. if (this._options.volume) {
  34337. this._outputAudioNode.gain.value = this._options.volume;
  34338. }
  34339. if (this._options.mainTrack) {
  34340. this._isMainTrack = this._options.mainTrack;
  34341. }
  34342. }
  34343. this._isInitialized = true;
  34344. }
  34345. };
  34346. SoundTrack.prototype.dispose = function () {
  34347. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34348. if (this._connectedAnalyser) {
  34349. this._connectedAnalyser.stopDebugCanvas();
  34350. }
  34351. while (this.soundCollection.length) {
  34352. this.soundCollection[0].dispose();
  34353. }
  34354. if (this._outputAudioNode) {
  34355. this._outputAudioNode.disconnect();
  34356. }
  34357. this._outputAudioNode = null;
  34358. }
  34359. };
  34360. SoundTrack.prototype.AddSound = function (sound) {
  34361. if (!this._isInitialized) {
  34362. this._initializeSoundTrackAudioGraph();
  34363. }
  34364. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34365. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34366. }
  34367. if (sound.soundTrackId) {
  34368. if (sound.soundTrackId === -1) {
  34369. this._scene.mainSoundTrack.RemoveSound(sound);
  34370. }
  34371. else {
  34372. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34373. }
  34374. }
  34375. this.soundCollection.push(sound);
  34376. sound.soundTrackId = this.id;
  34377. };
  34378. SoundTrack.prototype.RemoveSound = function (sound) {
  34379. var index = this.soundCollection.indexOf(sound);
  34380. if (index !== -1) {
  34381. this.soundCollection.splice(index, 1);
  34382. }
  34383. };
  34384. SoundTrack.prototype.setVolume = function (newVolume) {
  34385. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34386. this._outputAudioNode.gain.value = newVolume;
  34387. }
  34388. };
  34389. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34390. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34391. for (var i = 0; i < this.soundCollection.length; i++) {
  34392. this.soundCollection[i].switchPanningModelToHRTF();
  34393. }
  34394. }
  34395. };
  34396. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34397. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34398. for (var i = 0; i < this.soundCollection.length; i++) {
  34399. this.soundCollection[i].switchPanningModelToEqualPower();
  34400. }
  34401. }
  34402. };
  34403. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34404. if (this._connectedAnalyser) {
  34405. this._connectedAnalyser.stopDebugCanvas();
  34406. }
  34407. this._connectedAnalyser = analyser;
  34408. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34409. this._outputAudioNode.disconnect();
  34410. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34411. }
  34412. };
  34413. return SoundTrack;
  34414. })();
  34415. BABYLON.SoundTrack = SoundTrack;
  34416. })(BABYLON || (BABYLON = {}));
  34417. var BABYLON;
  34418. (function (BABYLON) {
  34419. var SIMDVector3 = (function () {
  34420. function SIMDVector3() {
  34421. }
  34422. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  34423. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  34424. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34425. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34426. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34427. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34428. 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));
  34429. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34430. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34431. };
  34432. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  34433. var v0 = SIMD.float32x4.splat(x);
  34434. var v1 = SIMD.float32x4.splat(y);
  34435. var v2 = SIMD.float32x4.splat(z);
  34436. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34437. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34438. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34439. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34440. 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));
  34441. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34442. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34443. };
  34444. return SIMDVector3;
  34445. })();
  34446. BABYLON.SIMDVector3 = SIMDVector3;
  34447. var SIMDMatrix = (function () {
  34448. function SIMDMatrix() {
  34449. }
  34450. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  34451. if (offset === void 0) { offset = 0; }
  34452. var tm = this.m;
  34453. var om = other.m;
  34454. var om0 = SIMD.float32x4.load(om, 0);
  34455. var om1 = SIMD.float32x4.load(om, 4);
  34456. var om2 = SIMD.float32x4.load(om, 8);
  34457. var om3 = SIMD.float32x4.load(om, 12);
  34458. var tm0 = SIMD.float32x4.load(tm, 0);
  34459. 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)))));
  34460. var tm1 = SIMD.float32x4.load(tm, 4);
  34461. 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)))));
  34462. var tm2 = SIMD.float32x4.load(tm, 8);
  34463. 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)))));
  34464. var tm3 = SIMD.float32x4.load(tm, 12);
  34465. 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)))));
  34466. };
  34467. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  34468. var src = this.m;
  34469. var dest = other.m;
  34470. var row0, row1, row2, row3;
  34471. var tmp1;
  34472. var minor0, minor1, minor2, minor3;
  34473. var det;
  34474. // Load the 4 rows
  34475. var src0 = SIMD.float32x4.load(src, 0);
  34476. var src1 = SIMD.float32x4.load(src, 4);
  34477. var src2 = SIMD.float32x4.load(src, 8);
  34478. var src3 = SIMD.float32x4.load(src, 12);
  34479. // Transpose the source matrix. Sort of. Not a true transpose operation
  34480. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34481. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34482. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  34483. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  34484. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34485. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34486. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  34487. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  34488. // This is a true transposition, but it will lead to an incorrect result
  34489. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34490. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34491. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34492. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34493. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34494. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34495. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34496. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34497. // ----
  34498. tmp1 = SIMD.float32x4.mul(row2, row3);
  34499. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34500. minor0 = SIMD.float32x4.mul(row1, tmp1);
  34501. minor1 = SIMD.float32x4.mul(row0, tmp1);
  34502. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34503. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  34504. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  34505. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  34506. // ----
  34507. tmp1 = SIMD.float32x4.mul(row1, row2);
  34508. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34509. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  34510. minor3 = SIMD.float32x4.mul(row0, tmp1);
  34511. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34512. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  34513. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  34514. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  34515. // ----
  34516. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  34517. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34518. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  34519. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  34520. minor2 = SIMD.float32x4.mul(row0, tmp1);
  34521. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34522. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  34523. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  34524. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  34525. // ----
  34526. tmp1 = SIMD.float32x4.mul(row0, row1);
  34527. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34528. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  34529. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  34530. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34531. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  34532. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  34533. // ----
  34534. tmp1 = SIMD.float32x4.mul(row0, row3);
  34535. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34536. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  34537. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  34538. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34539. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  34540. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  34541. // ----
  34542. tmp1 = SIMD.float32x4.mul(row0, row2);
  34543. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34544. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  34545. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  34546. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34547. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  34548. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  34549. // Compute determinant
  34550. det = SIMD.float32x4.mul(row0, minor0);
  34551. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  34552. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  34553. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  34554. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  34555. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  34556. // These shuffles aren't necessary if the faulty transposition is done
  34557. // up at the top of this function.
  34558. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  34559. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  34560. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  34561. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  34562. // Compute final values by multiplying with 1/det
  34563. minor0 = SIMD.float32x4.mul(det, minor0);
  34564. minor1 = SIMD.float32x4.mul(det, minor1);
  34565. minor2 = SIMD.float32x4.mul(det, minor2);
  34566. minor3 = SIMD.float32x4.mul(det, minor3);
  34567. SIMD.float32x4.store(dest, 0, minor0);
  34568. SIMD.float32x4.store(dest, 4, minor1);
  34569. SIMD.float32x4.store(dest, 8, minor2);
  34570. SIMD.float32x4.store(dest, 12, minor3);
  34571. return this;
  34572. };
  34573. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  34574. var out = result.m;
  34575. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  34576. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  34577. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  34578. // cc.kmVec3Subtract(f, pCenter, pEye);
  34579. var f = SIMD.float32x4.sub(center, eye);
  34580. // cc.kmVec3Normalize(f, f);
  34581. var tmp = SIMD.float32x4.mul(f, f);
  34582. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34583. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34584. // cc.kmVec3Assign(up, pUp);
  34585. // cc.kmVec3Normalize(up, up);
  34586. tmp = SIMD.float32x4.mul(up, up);
  34587. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34588. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34589. // cc.kmVec3Cross(s, f, up);
  34590. 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)));
  34591. // cc.kmVec3Normalize(s, s);
  34592. tmp = SIMD.float32x4.mul(s, s);
  34593. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34594. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34595. // cc.kmVec3Cross(u, s, f);
  34596. 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)));
  34597. // cc.kmVec3Normalize(s, s);
  34598. tmp = SIMD.float32x4.mul(s, s);
  34599. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34600. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34601. var zero = SIMD.float32x4.splat(0.0);
  34602. s = SIMD.float32x4.neg(s);
  34603. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  34604. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  34605. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34606. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  34607. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  34608. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  34609. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34610. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  34611. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  34612. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  34613. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  34614. var b3 = SIMD.float32x4.neg(eye);
  34615. b3 = SIMD.float32x4.withW(b3, 1.0);
  34616. 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)))));
  34617. 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)))));
  34618. 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)))));
  34619. 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)))));
  34620. };
  34621. return SIMDMatrix;
  34622. })();
  34623. BABYLON.SIMDMatrix = SIMDMatrix;
  34624. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  34625. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  34626. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  34627. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  34628. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  34629. var SIMDHelper = (function () {
  34630. function SIMDHelper() {
  34631. }
  34632. Object.defineProperty(SIMDHelper, "IsEnabled", {
  34633. get: function () {
  34634. return SIMDHelper._isEnabled;
  34635. },
  34636. enumerable: true,
  34637. configurable: true
  34638. });
  34639. SIMDHelper.DisableSIMD = function () {
  34640. // Replace functions
  34641. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  34642. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  34643. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  34644. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  34645. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  34646. SIMDHelper._isEnabled = false;
  34647. };
  34648. SIMDHelper.EnableSIMD = function () {
  34649. if (window.SIMD === undefined) {
  34650. return;
  34651. }
  34652. // Replace functions
  34653. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34654. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34655. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34656. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34657. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34658. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34659. get: function () { return this._data[0]; },
  34660. set: function (value) {
  34661. if (!this._data) {
  34662. this._data = new Float32Array(3);
  34663. }
  34664. this._data[0] = value;
  34665. }
  34666. });
  34667. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34668. get: function () { return this._data[1]; },
  34669. set: function (value) {
  34670. this._data[1] = value;
  34671. }
  34672. });
  34673. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34674. get: function () { return this._data[2]; },
  34675. set: function (value) {
  34676. this._data[2] = value;
  34677. }
  34678. });
  34679. SIMDHelper._isEnabled = true;
  34680. };
  34681. SIMDHelper._isEnabled = false;
  34682. return SIMDHelper;
  34683. })();
  34684. BABYLON.SIMDHelper = SIMDHelper;
  34685. })(BABYLON || (BABYLON = {}));
  34686. var BABYLON;
  34687. (function (BABYLON) {
  34688. /**
  34689. * This class describe a rectangle that were added to the map.
  34690. * You have access to its coordinates either in pixel or normalized (UV)
  34691. */
  34692. var PackedRect = (function () {
  34693. function PackedRect(root, parent, pos, size) {
  34694. this._pos = pos;
  34695. this._size = size;
  34696. this._root = root;
  34697. this._parent = parent;
  34698. }
  34699. Object.defineProperty(PackedRect.prototype, "pos", {
  34700. /**
  34701. * @returns the position of this node into the map
  34702. */
  34703. get: function () {
  34704. return this._pos;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. Object.defineProperty(PackedRect.prototype, "contentSize", {
  34710. /**
  34711. * @returns the size of the rectangle this node handles
  34712. */
  34713. get: function () {
  34714. return this._contentSize;
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(PackedRect.prototype, "UVs", {
  34720. /**
  34721. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  34722. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  34723. */
  34724. get: function () {
  34725. var mainWidth = this._root._size.width;
  34726. var mainHeight = this._root._size.height;
  34727. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  34728. var rightBottom = new BABYLON.Vector2((this._pos.x + this._contentSize.width - 1) / mainWidth, (this._pos.y + this._contentSize.height - 1) / mainHeight);
  34729. var uvs = new Array();
  34730. uvs.push(topLeft);
  34731. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  34732. uvs.push(rightBottom);
  34733. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  34734. return uvs;
  34735. },
  34736. enumerable: true,
  34737. configurable: true
  34738. });
  34739. /**
  34740. * Free this rectangle from the map.
  34741. * Call this method when you no longer need the rectangle to be in the map.
  34742. */
  34743. PackedRect.prototype.freeContent = function () {
  34744. if (!this.contentSize) {
  34745. return;
  34746. }
  34747. this._contentSize = null;
  34748. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  34749. this.attemptDefrag();
  34750. };
  34751. Object.defineProperty(PackedRect.prototype, "isUsed", {
  34752. get: function () {
  34753. return this._contentSize != null || this._leftNode != null;
  34754. },
  34755. enumerable: true,
  34756. configurable: true
  34757. });
  34758. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  34759. var node = this.findNode(contentSize);
  34760. // Not enough space...
  34761. if (!node) {
  34762. return null;
  34763. }
  34764. node.splitNode(contentSize);
  34765. return node;
  34766. };
  34767. PackedRect.prototype.findNode = function (size) {
  34768. var resNode = null;
  34769. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  34770. if (this.isUsed) {
  34771. if (this._leftNode) {
  34772. resNode = this._leftNode.findNode(size);
  34773. }
  34774. if (!resNode && this._rightNode) {
  34775. resNode = this._rightNode.findNode(size);
  34776. }
  34777. if (!resNode && this._bottomNode) {
  34778. resNode = this._bottomNode.findNode(size);
  34779. }
  34780. }
  34781. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  34782. resNode = this;
  34783. }
  34784. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  34785. resNode = this;
  34786. }
  34787. return resNode;
  34788. };
  34789. PackedRect.prototype.splitNode = function (contentSize) {
  34790. // 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)
  34791. if (!this._contentSize && this._initialSize) {
  34792. 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));
  34793. return this._leftNode.splitNode(contentSize);
  34794. }
  34795. else {
  34796. this._contentSize = contentSize.clone();
  34797. this._initialSize = contentSize.clone();
  34798. if (contentSize.width !== this._size.width) {
  34799. 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));
  34800. }
  34801. if (contentSize.height !== this._size.height) {
  34802. 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));
  34803. }
  34804. return this;
  34805. }
  34806. };
  34807. PackedRect.prototype.attemptDefrag = function () {
  34808. if (!this.isUsed && this.isRecursiveFree) {
  34809. this.clearNode();
  34810. if (this._parent) {
  34811. this._parent.attemptDefrag();
  34812. }
  34813. }
  34814. };
  34815. PackedRect.prototype.clearNode = function () {
  34816. this._initialSize = null;
  34817. this._rightNode = null;
  34818. this._bottomNode = null;
  34819. };
  34820. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  34821. get: function () {
  34822. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. PackedRect.prototype.evalFreeSize = function (size) {
  34828. var levelSize = 0;
  34829. if (!this.isUsed) {
  34830. if (this._initialSize) {
  34831. levelSize = this._initialSize.surface;
  34832. }
  34833. else {
  34834. levelSize = this._size.surface;
  34835. }
  34836. }
  34837. if (this._rightNode) {
  34838. levelSize += this._rightNode.evalFreeSize(0);
  34839. }
  34840. if (this._bottomNode) {
  34841. levelSize += this._bottomNode.evalFreeSize(0);
  34842. }
  34843. return levelSize + size;
  34844. };
  34845. return PackedRect;
  34846. })();
  34847. BABYLON.PackedRect = PackedRect;
  34848. /**
  34849. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  34850. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  34851. * 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.
  34852. */
  34853. var RectPackingMap = (function (_super) {
  34854. __extends(RectPackingMap, _super);
  34855. /**
  34856. * Create an instance of the object with a dimension using the given size
  34857. * @param size The dimension of the rectangle that will contain all the sub ones.
  34858. */
  34859. function RectPackingMap(size) {
  34860. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  34861. this._root = this;
  34862. }
  34863. /**
  34864. * Add a rectangle, finding the best location to store it into the map
  34865. * @param size the dimension of the rectangle to store
  34866. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  34867. */
  34868. RectPackingMap.prototype.addRect = function (size) {
  34869. var node = this.findAndSplitNode(size);
  34870. return node;
  34871. };
  34872. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  34873. /**
  34874. * Return the current space free normalized between [0;1]
  34875. * @returns {}
  34876. */
  34877. get: function () {
  34878. var freeSize = 0;
  34879. freeSize = this.evalFreeSize(freeSize);
  34880. return freeSize / (this._size.width * this._size.height);
  34881. },
  34882. enumerable: true,
  34883. configurable: true
  34884. });
  34885. return RectPackingMap;
  34886. })(PackedRect);
  34887. BABYLON.RectPackingMap = RectPackingMap;
  34888. })(BABYLON || (BABYLON = {}));
  34889. var BABYLON;
  34890. (function (BABYLON) {
  34891. var DynamicFloatArrayElementInfo = (function () {
  34892. function DynamicFloatArrayElementInfo() {
  34893. }
  34894. return DynamicFloatArrayElementInfo;
  34895. })();
  34896. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  34897. /**
  34898. * 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.
  34899. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  34900. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  34901. * 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.
  34902. * 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.
  34903. * 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".
  34904. */
  34905. var DynamicFloatArray = (function () {
  34906. /**
  34907. * Construct an instance of the dynamic float array
  34908. * @param stride size of one element in float (i.e. not bytes!)
  34909. * @param initialElementCount the number of available entries at construction
  34910. */
  34911. function DynamicFloatArray(stride, initialElementCount) {
  34912. this._stride = stride;
  34913. this.buffer = new Float32Array(stride * initialElementCount);
  34914. this._lastUsed = 0;
  34915. this._firstFree = 0;
  34916. this._allEntries = new Array(initialElementCount);
  34917. this._freeEntries = new Array(initialElementCount);
  34918. for (var i = 0; i < initialElementCount; i++) {
  34919. var element = new DynamicFloatArrayElementInfo();
  34920. element.offset = i * stride;
  34921. this._allEntries[i] = element;
  34922. this._freeEntries[initialElementCount - i - 1] = element;
  34923. }
  34924. }
  34925. /**
  34926. * Allocate an element in the array.
  34927. * @return the element info instance that contains the offset into the main buffer of the element's location.
  34928. * Beware, this offset may change when you call pack()
  34929. */
  34930. DynamicFloatArray.prototype.allocElement = function () {
  34931. if (this._freeEntries.length === 0) {
  34932. this._growBuffer();
  34933. }
  34934. var el = this._freeEntries.pop();
  34935. this._lastUsed = Math.max(el.offset, this._lastUsed);
  34936. if (el.offset === this._firstFree) {
  34937. if (this._freeEntries.length > 0) {
  34938. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  34939. }
  34940. else {
  34941. this._firstFree += this._stride;
  34942. }
  34943. }
  34944. return el;
  34945. };
  34946. /**
  34947. * Free the element corresponding to the given element info
  34948. * @param elInfo the element that describe the allocated element
  34949. */
  34950. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  34951. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  34952. this._freeEntries.push(elInfo);
  34953. };
  34954. /**
  34955. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  34956. * 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().
  34957. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  34958. */
  34959. DynamicFloatArray.prototype.pack = function () {
  34960. // no free slot? no need to pack
  34961. if (this._freeEntries.length === 0) {
  34962. return this.buffer;
  34963. }
  34964. // If the buffer is already packed the last used will always be lower than the first free
  34965. if (this._lastUsed < this._firstFree) {
  34966. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  34967. return elementsBuffer_1;
  34968. }
  34969. var s = this._stride;
  34970. // 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
  34971. var lastFree = new DynamicFloatArrayElementInfo();
  34972. lastFree.offset = this.totalElementCount * s;
  34973. this._freeEntries.push(lastFree);
  34974. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  34975. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  34976. var firstFreeSlotOffset = sortedFree[0].offset;
  34977. var freeZoneSize = 1;
  34978. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  34979. var prevOffset = sortedFree[0].offset;
  34980. for (var i = 1; i < sortedFree.length; i++) {
  34981. // 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
  34982. if (firstFreeSlotOffset >= occupiedZoneSize) {
  34983. break;
  34984. }
  34985. var curFree = sortedFree[i];
  34986. var curOffset = curFree.offset;
  34987. // Compute the distance between this offset and the previous
  34988. var distance = curOffset - prevOffset;
  34989. // If the distance is the stride size, they are adjacent, it good, move to the next
  34990. if (distance === s) {
  34991. // Free zone is one element bigger
  34992. ++freeZoneSize;
  34993. // as we're about to iterate to the next, the cur becomes the previous...
  34994. prevOffset = curOffset;
  34995. continue;
  34996. }
  34997. // Distance is bigger, which means there's x element between the previous free and this one
  34998. var usedRange = (distance / s) - 1;
  34999. // Two cases the free zone is smaller than the data to move or bigger
  35000. // Copy what can fit in the free zone
  35001. var curMoveOffset = curOffset - s;
  35002. var copyCount = Math.min(freeZoneSize, usedRange);
  35003. for (var j = 0; j < copyCount; j++) {
  35004. var freeI = firstFreeSlotOffset / s;
  35005. var curI = curMoveOffset / s;
  35006. var moveEl = sortedAll[curI];
  35007. this._moveElement(moveEl, firstFreeSlotOffset);
  35008. var replacedEl = sortedAll[freeI];
  35009. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  35010. replacedEl.offset = curMoveOffset;
  35011. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  35012. sortedAll[freeI] = moveEl;
  35013. sortedAll[curI] = replacedEl;
  35014. curMoveOffset -= s;
  35015. firstFreeSlotOffset += s;
  35016. }
  35017. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  35018. if (freeZoneSize <= usedRange) {
  35019. firstFreeSlotOffset = curMoveOffset + s;
  35020. freeZoneSize = 1 + copyCount;
  35021. }
  35022. else {
  35023. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  35024. }
  35025. // as we're about to iterate to the next, the cur becomes the previous...
  35026. prevOffset = curOffset;
  35027. }
  35028. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  35029. this._lastUsed = firstFreeSlotOffset - s;
  35030. this._firstFree = firstFreeSlotOffset;
  35031. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  35032. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  35033. this._allEntries = sortedAll;
  35034. return elementsBuffer;
  35035. };
  35036. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  35037. for (var i = 0; i < this._stride; i++) {
  35038. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  35039. }
  35040. element.offset = destOffset;
  35041. };
  35042. DynamicFloatArray.prototype._growBuffer = function () {
  35043. // Allocate the new buffer with 50% more entries, copy the content of the current one
  35044. var newElCount = Math.floor(this.totalElementCount * 1.5);
  35045. var newBuffer = new Float32Array(newElCount * this._stride);
  35046. newBuffer.set(this.buffer);
  35047. var curCount = this.totalElementCount;
  35048. var addedCount = newElCount - this.totalElementCount;
  35049. for (var i = 0; i < addedCount; i++) {
  35050. var element = new DynamicFloatArrayElementInfo();
  35051. element.offset = (curCount + i) * this.stride;
  35052. this._allEntries.push(element);
  35053. this._freeEntries[addedCount - i - 1] = element;
  35054. }
  35055. this._firstFree = curCount * this.stride;
  35056. this.buffer = newBuffer;
  35057. };
  35058. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  35059. /**
  35060. * Get the total count of entries that can fit in the current buffer
  35061. * @returns the elements count
  35062. */
  35063. get: function () {
  35064. return this._allEntries.length;
  35065. },
  35066. enumerable: true,
  35067. configurable: true
  35068. });
  35069. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  35070. /**
  35071. * Get the count of free entries that can still be allocated without resizing the buffer
  35072. * @returns the free elements count
  35073. */
  35074. get: function () {
  35075. return this._freeEntries.length;
  35076. },
  35077. enumerable: true,
  35078. configurable: true
  35079. });
  35080. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  35081. /**
  35082. * Get the count of allocated elements
  35083. * @returns the allocated elements count
  35084. */
  35085. get: function () {
  35086. return this._allEntries.length - this._freeEntries.length;
  35087. },
  35088. enumerable: true,
  35089. configurable: true
  35090. });
  35091. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  35092. /**
  35093. * Return the size of one element in float
  35094. * @returns the size in float
  35095. */
  35096. get: function () {
  35097. return this._stride;
  35098. },
  35099. enumerable: true,
  35100. configurable: true
  35101. });
  35102. return DynamicFloatArray;
  35103. })();
  35104. BABYLON.DynamicFloatArray = DynamicFloatArray;
  35105. })(BABYLON || (BABYLON = {}));
  35106. var BABYLON;
  35107. (function (BABYLON) {
  35108. /**
  35109. * This class given information about a given character.
  35110. */
  35111. var CharInfo = (function () {
  35112. function CharInfo() {
  35113. }
  35114. return CharInfo;
  35115. })();
  35116. BABYLON.CharInfo = CharInfo;
  35117. var FontTexture = (function (_super) {
  35118. __extends(FontTexture, _super);
  35119. /**
  35120. * Create a new instance of the FontTexture class
  35121. * @param name the name of the texture
  35122. * @param font the font to use, use the W3C CSS notation
  35123. * @param scene the scene that owns the texture
  35124. * @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
  35125. * @param samplingMode the texture sampling mode
  35126. */
  35127. function FontTexture(name, font, scene, maxCharCount, samplingMode) {
  35128. if (maxCharCount === void 0) { maxCharCount = 200; }
  35129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35130. _super.call(this, null, scene, true, false, samplingMode);
  35131. this._charInfos = {};
  35132. this._curCharCount = 0;
  35133. this._lastUpdateCharCount = -1;
  35134. this._usedCounter = 1;
  35135. this.name = name;
  35136. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35137. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35138. // First canvas creation to determine the size of the texture to create
  35139. this._canvas = document.createElement("canvas");
  35140. this._context = this._canvas.getContext("2d");
  35141. this._context.font = font;
  35142. this._context.fillStyle = "white";
  35143. var res = this.getFontHeight(font);
  35144. this._lineHeight = res.height;
  35145. this._offset = res.offset - 1;
  35146. var maxCharWidth = this._context.measureText("W").width;
  35147. this._spaceWidth = this._context.measureText(" ").width;
  35148. // This is an approximate size, but should always be able to fit at least the maxCharCount
  35149. var totalEstSurface = this._lineHeight * maxCharWidth * maxCharCount;
  35150. var edge = Math.sqrt(totalEstSurface);
  35151. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  35152. // Create the texture that will store the font characters
  35153. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  35154. var textureSize = this.getSize();
  35155. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  35156. this._canvas = document.createElement("canvas");
  35157. this._canvas.width = textureSize.width;
  35158. this._canvas.height = textureSize.height;
  35159. this._context = this._canvas.getContext("2d");
  35160. this._context.textBaseline = "top";
  35161. this._context.font = font;
  35162. this._context.fillStyle = "white";
  35163. this._context.imageSmoothingEnabled = false;
  35164. this._currentFreePosition = BABYLON.Vector2.Zero();
  35165. // Add the basic ASCII based characters
  35166. for (var i = 0x20; i < 0x7F; i++) {
  35167. var c = String.fromCharCode(i);
  35168. this.getChar(c);
  35169. }
  35170. this.update();
  35171. }
  35172. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  35173. get: function () {
  35174. return this._spaceWidth;
  35175. },
  35176. enumerable: true,
  35177. configurable: true
  35178. });
  35179. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  35180. get: function () {
  35181. return this._lineHeight;
  35182. },
  35183. enumerable: true,
  35184. configurable: true
  35185. });
  35186. FontTexture.GetCachedFontTexture = function (scene, fontName) {
  35187. var s = scene;
  35188. if (!s.__fontTextureCache__) {
  35189. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  35190. }
  35191. var dic = s.__fontTextureCache__;
  35192. var lfn = fontName.toLocaleLowerCase();
  35193. var ft = dic.get(lfn);
  35194. if (ft) {
  35195. ++ft._usedCounter;
  35196. return ft;
  35197. }
  35198. ft = new FontTexture(null, lfn, scene, 200, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35199. dic.add(lfn, ft);
  35200. return ft;
  35201. };
  35202. FontTexture.ReleaseCachedFontTexture = function (scene, fontName) {
  35203. var s = scene;
  35204. var dic = s.__fontTextureCache__;
  35205. if (!dic) {
  35206. return;
  35207. }
  35208. var lfn = fontName.toLocaleLowerCase();
  35209. var font = dic.get(lfn);
  35210. if (--font._usedCounter === 0) {
  35211. dic.remove(lfn);
  35212. font.dispose();
  35213. }
  35214. };
  35215. /**
  35216. * Make sure the given char is present in the font map.
  35217. * @param char the character to get or add
  35218. * @return the CharInfo instance corresponding to the given character
  35219. */
  35220. FontTexture.prototype.getChar = function (char) {
  35221. if (char.length !== 1) {
  35222. return null;
  35223. }
  35224. var info = this._charInfos[char];
  35225. if (info) {
  35226. return info;
  35227. }
  35228. info = new CharInfo();
  35229. var measure = this._context.measureText(char);
  35230. var textureSize = this.getSize();
  35231. // we reached the end of the current line?
  35232. var xMargin = 2;
  35233. var yMargin = 2;
  35234. var width = measure.width;
  35235. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  35236. this._currentFreePosition.x = 0;
  35237. this._currentFreePosition.y += this._lineHeight + yMargin; // +2 for safety margin
  35238. // No more room?
  35239. if (this._currentFreePosition.y > textureSize.height) {
  35240. return this.getChar("!");
  35241. }
  35242. }
  35243. // Draw the character in the texture
  35244. this._context.fillText(char, this._currentFreePosition.x - 0.5, this._currentFreePosition.y - this._offset - 0.5);
  35245. // Fill the CharInfo object
  35246. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  35247. info.bottomRightUV = new BABYLON.Vector2(info.topLeftUV.x + (width / textureSize.width), info.topLeftUV.y + ((this._lineHeight + 2) / textureSize.height));
  35248. info.charWidth = width;
  35249. // Add the info structure
  35250. this._charInfos[char] = info;
  35251. this._curCharCount++;
  35252. // Set the next position
  35253. this._currentFreePosition.x += width + xMargin;
  35254. return info;
  35255. };
  35256. FontTexture.prototype.measureText = function (text, tabulationSize) {
  35257. if (tabulationSize === void 0) { tabulationSize = 4; }
  35258. var maxWidth = 0;
  35259. var curWidth = 0;
  35260. var lineCount = 1;
  35261. var charxpos = 0;
  35262. // Parse each char of the string
  35263. for (var _i = 0; _i < text.length; _i++) {
  35264. var char = text[_i];
  35265. // Next line feed?
  35266. if (char === "\n") {
  35267. maxWidth = Math.max(maxWidth, curWidth);
  35268. charxpos = 0;
  35269. curWidth = 0;
  35270. ++lineCount;
  35271. continue;
  35272. }
  35273. // Tabulation ?
  35274. if (char === "\t") {
  35275. var nextPos = charxpos + tabulationSize;
  35276. nextPos = nextPos - (nextPos % tabulationSize);
  35277. curWidth += (nextPos - charxpos) * this.spaceWidth;
  35278. charxpos = nextPos;
  35279. continue;
  35280. }
  35281. if (char < " ") {
  35282. continue;
  35283. }
  35284. curWidth += this.getChar(char).charWidth;
  35285. ++charxpos;
  35286. }
  35287. maxWidth = Math.max(maxWidth, curWidth);
  35288. return new BABYLON.Size(maxWidth, lineCount * this._lineHeight);
  35289. };
  35290. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  35291. FontTexture.prototype.getFontHeight = function (font) {
  35292. var fontDraw = document.createElement("canvas");
  35293. var ctx = fontDraw.getContext('2d');
  35294. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  35295. ctx.textBaseline = 'top';
  35296. ctx.fillStyle = 'white';
  35297. ctx.font = font;
  35298. ctx.fillText('jH|', 0, 0);
  35299. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  35300. var start = -1;
  35301. var end = -1;
  35302. for (var row = 0; row < fontDraw.height; row++) {
  35303. for (var column = 0; column < fontDraw.width; column++) {
  35304. var index = (row * fontDraw.width + column) * 4;
  35305. if (pixels[index] === 0) {
  35306. if (column === fontDraw.width - 1 && start !== -1) {
  35307. end = row;
  35308. row = fontDraw.height;
  35309. break;
  35310. }
  35311. continue;
  35312. }
  35313. else {
  35314. if (start === -1) {
  35315. start = row;
  35316. }
  35317. break;
  35318. }
  35319. }
  35320. }
  35321. return { height: end - start, offset: start - 1 };
  35322. };
  35323. Object.defineProperty(FontTexture.prototype, "canRescale", {
  35324. get: function () {
  35325. return false;
  35326. },
  35327. enumerable: true,
  35328. configurable: true
  35329. });
  35330. FontTexture.prototype.getContext = function () {
  35331. return this._context;
  35332. };
  35333. /**
  35334. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  35335. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  35336. */
  35337. FontTexture.prototype.update = function () {
  35338. // Update only if there's new char added since the previous update
  35339. if (this._lastUpdateCharCount < this._curCharCount) {
  35340. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  35341. this._lastUpdateCharCount = this._curCharCount;
  35342. }
  35343. };
  35344. // cloning should be prohibited, there's no point to duplicate this texture at all
  35345. FontTexture.prototype.clone = function () {
  35346. return null;
  35347. };
  35348. return FontTexture;
  35349. })(BABYLON.Texture);
  35350. BABYLON.FontTexture = FontTexture;
  35351. })(BABYLON || (BABYLON = {}));
  35352. var BABYLON;
  35353. (function (BABYLON) {
  35354. var MapTexture = (function (_super) {
  35355. __extends(MapTexture, _super);
  35356. function MapTexture(name, scene, size, samplingMode) {
  35357. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35358. _super.call(this, null, scene, true, false, samplingMode);
  35359. this.name = name;
  35360. this._size = size;
  35361. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35362. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35363. // Create the rectPackMap that will allocate portion of the texture
  35364. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  35365. // Create the texture that will store the content
  35366. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  35367. }
  35368. /**
  35369. * Allocate a rectangle of a given size in the texture map
  35370. * @param size the size of the rectangle to allocation
  35371. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  35372. */
  35373. MapTexture.prototype.allocateRect = function (size) {
  35374. return this._rectPackingMap.addRect(size);
  35375. };
  35376. /**
  35377. * Free a given rectangle from the texture map
  35378. * @param rectInfo the instance corresponding to the rect to free.
  35379. */
  35380. MapTexture.prototype.freeRect = function (rectInfo) {
  35381. if (rectInfo) {
  35382. rectInfo.freeContent();
  35383. }
  35384. };
  35385. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  35386. /**
  35387. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  35388. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  35389. * @returns {}
  35390. */
  35391. get: function () {
  35392. return this._rectPackingMap.freeSpace;
  35393. },
  35394. enumerable: true,
  35395. configurable: true
  35396. });
  35397. /**
  35398. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  35399. * 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.
  35400. * Don't forget to call unbindTexture when you're done rendering
  35401. * @param rect the zone to render to
  35402. * @param clear true to clear the portion's color/depth data
  35403. */
  35404. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  35405. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  35406. };
  35407. /**
  35408. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  35409. * 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.
  35410. * Don't forget to call unbindTexture when you're done rendering
  35411. * @param pos the position into the texture
  35412. * @param size the portion to fit the clip space to
  35413. * @param clear true to clear the portion's color/depth data
  35414. */
  35415. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  35416. var engine = this.getScene().getEngine();
  35417. engine.bindFramebuffer(this._texture);
  35418. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  35419. if (clear) {
  35420. var gl = engine._gl;
  35421. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  35422. // Save state
  35423. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  35424. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  35425. // Change state
  35426. gl.enable(gl.SCISSOR_TEST);
  35427. gl.scissor(pos.x, pos.y, size.width, size.height);
  35428. // Clear
  35429. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  35430. // Restore state
  35431. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  35432. if (curScissor === true) {
  35433. gl.enable(gl.SCISSOR_TEST);
  35434. }
  35435. else {
  35436. gl.disable(gl.SCISSOR_TEST);
  35437. }
  35438. }
  35439. };
  35440. /**
  35441. * Unbind the texture map from the rendering engine.
  35442. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  35443. * @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.
  35444. */
  35445. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  35446. // Dump ?
  35447. if (dumpForDebug) {
  35448. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  35449. }
  35450. var engine = this.getScene().getEngine();
  35451. if (this._replacedViewport) {
  35452. engine.setViewport(this._replacedViewport);
  35453. this._replacedViewport = null;
  35454. }
  35455. engine.unBindFramebuffer(this._texture);
  35456. };
  35457. Object.defineProperty(MapTexture.prototype, "canRescale", {
  35458. get: function () {
  35459. return false;
  35460. },
  35461. enumerable: true,
  35462. configurable: true
  35463. });
  35464. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  35465. // Anyway, there's not much point to use this method for this kind of texture I guess
  35466. MapTexture.prototype.clone = function () {
  35467. return null;
  35468. };
  35469. return MapTexture;
  35470. })(BABYLON.Texture);
  35471. BABYLON.MapTexture = MapTexture;
  35472. })(BABYLON || (BABYLON = {}));
  35473. var BABYLON;
  35474. (function (BABYLON) {
  35475. /**
  35476. * Stores 2D Bounding Information.
  35477. * This class handles a circle area and a bounding rectangle one.
  35478. */
  35479. var BoundingInfo2D = (function () {
  35480. function BoundingInfo2D() {
  35481. this.radius = 0;
  35482. this.center = BABYLON.Vector2.Zero();
  35483. this.extent = BABYLON.Vector2.Zero();
  35484. }
  35485. BoundingInfo2D.CreateFromSize = function (size, origin) {
  35486. var r = new BoundingInfo2D();
  35487. BoundingInfo2D.CreateFromSizeToRef(size, r, origin);
  35488. return r;
  35489. };
  35490. BoundingInfo2D.CreateFromRadius = function (radius, origin) {
  35491. var r = new BoundingInfo2D();
  35492. BoundingInfo2D.CreateFromRadiusToRef(radius, r, origin);
  35493. return r;
  35494. };
  35495. BoundingInfo2D.CreateFromPoints = function (points, origin) {
  35496. var r = new BoundingInfo2D();
  35497. BoundingInfo2D.CreateFromPointsToRef(points, r, origin);
  35498. return r;
  35499. };
  35500. BoundingInfo2D.CreateFromSizeToRef = function (size, b, origin) {
  35501. b.center = new BABYLON.Vector2(size.width / 2, size.height / 2);
  35502. b.extent = b.center.clone();
  35503. if (origin) {
  35504. b.center.x -= size.width * origin.x;
  35505. b.center.y -= size.height * origin.y;
  35506. }
  35507. b.radius = b.extent.length();
  35508. };
  35509. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b, origin) {
  35510. b.center = BABYLON.Vector2.Zero();
  35511. if (origin) {
  35512. b.center.x -= radius * origin.x;
  35513. b.center.y -= radius * origin.y;
  35514. }
  35515. b.extent = new BABYLON.Vector2(radius, radius);
  35516. b.radius = radius;
  35517. };
  35518. BoundingInfo2D.CreateFromPointsToRef = function (points, b, origin) {
  35519. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  35520. for (var _i = 0; _i < points.length; _i++) {
  35521. var p = points[_i];
  35522. xmin = Math.min(p.x, xmin);
  35523. xmax = Math.max(p.x, xmax);
  35524. ymin = Math.min(p.y, ymin);
  35525. ymax = Math.max(p.y, ymax);
  35526. }
  35527. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b, origin);
  35528. };
  35529. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b, origin) {
  35530. var w = xmax - xmin;
  35531. var h = ymax - ymin;
  35532. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  35533. if (origin) {
  35534. b.center.x -= w * origin.x;
  35535. b.center.y -= h * origin.y;
  35536. }
  35537. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  35538. b.radius = b.extent.length();
  35539. };
  35540. /**
  35541. * Duplicate this instance and return a new one
  35542. * @return the duplicated instance
  35543. */
  35544. BoundingInfo2D.prototype.clone = function () {
  35545. var r = new BoundingInfo2D();
  35546. r.center = this.center.clone();
  35547. r.radius = this.radius;
  35548. r.extent = this.extent.clone();
  35549. return r;
  35550. };
  35551. BoundingInfo2D.prototype.max = function () {
  35552. var r = BABYLON.Vector2.Zero();
  35553. this.maxToRef(r);
  35554. return r;
  35555. };
  35556. BoundingInfo2D.prototype.maxToRef = function (result) {
  35557. result.x = this.center.x + this.extent.x;
  35558. result.y = this.center.y + this.extent.y;
  35559. };
  35560. /**
  35561. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  35562. * @param matrix the transformation matrix to apply
  35563. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  35564. */
  35565. BoundingInfo2D.prototype.transform = function (matrix) {
  35566. var r = new BoundingInfo2D();
  35567. this.transformToRef(matrix, r);
  35568. return r;
  35569. };
  35570. /**
  35571. * Compute the union of this BoundingInfo2D with a given one, return a new BoundingInfo2D as a result
  35572. * @param other the second BoundingInfo2D to compute the union with this one
  35573. * @return a new instance containing the result of the union
  35574. */
  35575. BoundingInfo2D.prototype.union = function (other) {
  35576. var r = new BoundingInfo2D();
  35577. this.unionToRef(other, r);
  35578. return r;
  35579. };
  35580. /**
  35581. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  35582. * 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.
  35583. * @param matrix The matrix to use to compute the transformation
  35584. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  35585. */
  35586. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  35587. // Construct a bounding box based on the extent values
  35588. var p = new Array(4);
  35589. p[0] = new BABYLON.Vector2(this.center.x + this.extent.x, this.center.y + this.extent.y);
  35590. p[1] = new BABYLON.Vector2(this.center.x + this.extent.x, this.center.y - this.extent.y);
  35591. p[2] = new BABYLON.Vector2(this.center.x - this.extent.x, this.center.y - this.extent.y);
  35592. p[3] = new BABYLON.Vector2(this.center.x - this.extent.x, this.center.y + this.extent.y);
  35593. // Transform the four points of the bounding box with the matrix
  35594. for (var i = 0; i < 4; i++) {
  35595. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  35596. }
  35597. BoundingInfo2D.CreateFromPointsToRef(p, result);
  35598. };
  35599. /**
  35600. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  35601. * 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.
  35602. * @param other the second object used to compute the union
  35603. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  35604. */
  35605. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  35606. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  35607. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  35608. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  35609. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  35610. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  35611. };
  35612. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  35613. // is it inside the radius?
  35614. var pickLocal = pickPosition.subtract(this.center);
  35615. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  35616. // is it inside the rectangle?
  35617. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  35618. }
  35619. return false;
  35620. };
  35621. return BoundingInfo2D;
  35622. })();
  35623. BABYLON.BoundingInfo2D = BoundingInfo2D;
  35624. })(BABYLON || (BABYLON = {}));
  35625. var BABYLON;
  35626. (function (BABYLON) {
  35627. /**
  35628. * Base class implementing the ILocable interface.
  35629. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  35630. */
  35631. var LockableBase = (function () {
  35632. function LockableBase() {
  35633. }
  35634. LockableBase.prototype.isLocked = function () {
  35635. return this._isLocked;
  35636. };
  35637. LockableBase.prototype.lock = function () {
  35638. if (this._isLocked) {
  35639. return true;
  35640. }
  35641. this.onLock();
  35642. this._isLocked = true;
  35643. return false;
  35644. };
  35645. /**
  35646. * Protected handler that will be called when the instance is about to be locked.
  35647. */
  35648. LockableBase.prototype.onLock = function () {
  35649. };
  35650. return LockableBase;
  35651. })();
  35652. BABYLON.LockableBase = LockableBase;
  35653. /**
  35654. * 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).
  35655. */
  35656. var SolidColorBrush2D = (function (_super) {
  35657. __extends(SolidColorBrush2D, _super);
  35658. function SolidColorBrush2D(color, lock) {
  35659. if (lock === void 0) { lock = false; }
  35660. _super.call(this);
  35661. this._color = color;
  35662. if (lock) {
  35663. {
  35664. this.lock();
  35665. }
  35666. }
  35667. }
  35668. SolidColorBrush2D.prototype.isTransparent = function () {
  35669. return this._color && this._color.a < 1.0;
  35670. };
  35671. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  35672. /**
  35673. * The color used by this instance to render
  35674. * @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.
  35675. */
  35676. get: function () {
  35677. return this._color;
  35678. },
  35679. set: function (value) {
  35680. if (this.isLocked()) {
  35681. return;
  35682. }
  35683. this._color = value;
  35684. },
  35685. enumerable: true,
  35686. configurable: true
  35687. });
  35688. /**
  35689. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  35690. */
  35691. SolidColorBrush2D.prototype.toString = function () {
  35692. return this._color.toHexString();
  35693. };
  35694. SolidColorBrush2D = __decorate([
  35695. BABYLON.className("SolidColorBrush2D")
  35696. ], SolidColorBrush2D);
  35697. return SolidColorBrush2D;
  35698. })(LockableBase);
  35699. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  35700. var GradientColorBrush2D = (function (_super) {
  35701. __extends(GradientColorBrush2D, _super);
  35702. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  35703. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  35704. if (rotation === void 0) { rotation = 0; }
  35705. if (scale === void 0) { scale = 1; }
  35706. if (lock === void 0) { lock = false; }
  35707. _super.call(this);
  35708. this._color1 = color1;
  35709. this._color2 = color2;
  35710. this._translation = translation;
  35711. this._rotation = rotation;
  35712. this._scale = scale;
  35713. if (lock) {
  35714. this.lock();
  35715. }
  35716. }
  35717. GradientColorBrush2D.prototype.isTransparent = function () {
  35718. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  35719. };
  35720. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  35721. get: function () {
  35722. return this._color1;
  35723. },
  35724. set: function (value) {
  35725. if (this.isLocked()) {
  35726. return;
  35727. }
  35728. this._color1 = value;
  35729. },
  35730. enumerable: true,
  35731. configurable: true
  35732. });
  35733. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  35734. get: function () {
  35735. return this._color2;
  35736. },
  35737. set: function (value) {
  35738. if (this.isLocked()) {
  35739. return;
  35740. }
  35741. this._color2 = value;
  35742. },
  35743. enumerable: true,
  35744. configurable: true
  35745. });
  35746. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  35747. get: function () {
  35748. return this._translation;
  35749. },
  35750. set: function (value) {
  35751. if (this.isLocked()) {
  35752. return;
  35753. }
  35754. this._translation = value;
  35755. },
  35756. enumerable: true,
  35757. configurable: true
  35758. });
  35759. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  35760. get: function () {
  35761. return this._rotation;
  35762. },
  35763. set: function (value) {
  35764. if (this.isLocked()) {
  35765. return;
  35766. }
  35767. this._rotation = value;
  35768. },
  35769. enumerable: true,
  35770. configurable: true
  35771. });
  35772. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  35773. get: function () {
  35774. return this._scale;
  35775. },
  35776. set: function (value) {
  35777. if (this.isLocked()) {
  35778. return;
  35779. }
  35780. this._scale = value;
  35781. },
  35782. enumerable: true,
  35783. configurable: true
  35784. });
  35785. GradientColorBrush2D.prototype.toString = function () {
  35786. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  35787. };
  35788. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  35789. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  35790. };
  35791. GradientColorBrush2D = __decorate([
  35792. BABYLON.className("GradientColorBrush2D")
  35793. ], GradientColorBrush2D);
  35794. return GradientColorBrush2D;
  35795. })(LockableBase);
  35796. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  35797. })(BABYLON || (BABYLON = {}));
  35798. var BABYLON;
  35799. (function (BABYLON) {
  35800. var Prim2DClassInfo = (function () {
  35801. function Prim2DClassInfo() {
  35802. }
  35803. return Prim2DClassInfo;
  35804. })();
  35805. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  35806. var Prim2DPropInfo = (function () {
  35807. function Prim2DPropInfo() {
  35808. }
  35809. Prim2DPropInfo.PROPKIND_MODEL = 1;
  35810. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  35811. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  35812. return Prim2DPropInfo;
  35813. })();
  35814. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  35815. var PropertyChangedInfo = (function () {
  35816. function PropertyChangedInfo() {
  35817. }
  35818. return PropertyChangedInfo;
  35819. })();
  35820. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  35821. var ClassTreeInfo = (function () {
  35822. function ClassTreeInfo(baseClass, type, classContentFactory) {
  35823. this._baseClass = baseClass;
  35824. this._type = type;
  35825. this._subClasses = new Array();
  35826. this._levelContent = new BABYLON.StringDictionary();
  35827. this._classContentFactory = classContentFactory;
  35828. }
  35829. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  35830. get: function () {
  35831. if (!this._classContent) {
  35832. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  35833. }
  35834. return this._classContent;
  35835. },
  35836. enumerable: true,
  35837. configurable: true
  35838. });
  35839. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  35840. get: function () {
  35841. return this._type;
  35842. },
  35843. enumerable: true,
  35844. configurable: true
  35845. });
  35846. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  35847. get: function () {
  35848. return this._levelContent;
  35849. },
  35850. enumerable: true,
  35851. configurable: true
  35852. });
  35853. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  35854. get: function () {
  35855. if (!this._fullContent) {
  35856. var dic = new BABYLON.StringDictionary();
  35857. var curLevel = this;
  35858. while (curLevel) {
  35859. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  35860. curLevel = curLevel._baseClass;
  35861. }
  35862. this._fullContent = dic;
  35863. }
  35864. return this._fullContent;
  35865. },
  35866. enumerable: true,
  35867. configurable: true
  35868. });
  35869. ClassTreeInfo.prototype.getLevelOf = function (type) {
  35870. // Are we already there?
  35871. if (type === this._type) {
  35872. return this;
  35873. }
  35874. var baseProto = Object.getPrototypeOf(type);
  35875. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  35876. if (!curProtoContent) {
  35877. this.getLevelOf(baseProto);
  35878. }
  35879. return this.getOrAddType(baseProto, type);
  35880. };
  35881. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  35882. // Are we at the level corresponding to the baseType?
  35883. // If so, get or add the level we're looking for
  35884. if (baseType === this._type) {
  35885. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  35886. var subType = _a[_i];
  35887. if (subType.type === type) {
  35888. return subType.node;
  35889. }
  35890. }
  35891. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  35892. var info = { type: type, node: node };
  35893. this._subClasses.push(info);
  35894. return info.node;
  35895. }
  35896. // Recurse down to keep looking for the node corresponding to the baseTypeName
  35897. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  35898. var subType = _c[_b];
  35899. var info = subType.node.getOrAddType(baseType, type);
  35900. if (info) {
  35901. return info;
  35902. }
  35903. }
  35904. return null;
  35905. };
  35906. ClassTreeInfo.get = function (type) {
  35907. var dic = type["__classTreeInfo"];
  35908. if (!dic) {
  35909. return null;
  35910. }
  35911. return dic.getLevelOf(type);
  35912. };
  35913. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  35914. var dic = type["__classTreeInfo"];
  35915. if (!dic) {
  35916. dic = new ClassTreeInfo(null, type, classContentFactory);
  35917. type["__classTreeInfo"] = dic;
  35918. }
  35919. return dic;
  35920. };
  35921. return ClassTreeInfo;
  35922. })();
  35923. BABYLON.ClassTreeInfo = ClassTreeInfo;
  35924. var SmartPropertyPrim = (function () {
  35925. function SmartPropertyPrim() {
  35926. }
  35927. SmartPropertyPrim.prototype.setupSmartPropertyPrim = function () {
  35928. this._modelKey = null;
  35929. this._modelDirty = false;
  35930. this._levelBoundingInfoDirty = false;
  35931. this._instanceDirtyFlags = 0;
  35932. this._isDisposed = false;
  35933. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  35934. this.animations = new Array();
  35935. };
  35936. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  35937. /**
  35938. * Check if the object is disposed or not.
  35939. * @returns true if the object is dispose, false otherwise.
  35940. */
  35941. get: function () {
  35942. return this._isDisposed;
  35943. },
  35944. enumerable: true,
  35945. configurable: true
  35946. });
  35947. /**
  35948. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  35949. * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
  35950. */
  35951. SmartPropertyPrim.prototype.dispose = function () {
  35952. if (this.isDisposed) {
  35953. return false;
  35954. }
  35955. // Don't set to null, it may upset somebody...
  35956. this.animations.splice(0);
  35957. this._isDisposed = true;
  35958. return true;
  35959. };
  35960. /**
  35961. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  35962. * Look at Sprite2D for more information
  35963. */
  35964. SmartPropertyPrim.prototype.getAnimatables = function () {
  35965. return new Array();
  35966. };
  35967. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  35968. /**
  35969. * Property giving the Model Key associated to the property.
  35970. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  35971. * @returns the model key string.
  35972. */
  35973. get: function () {
  35974. var _this = this;
  35975. // No need to compute it?
  35976. if (!this._modelDirty && this._modelKey) {
  35977. return this._modelKey;
  35978. }
  35979. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  35980. var propDic = this.propDic;
  35981. propDic.forEach(function (k, v) {
  35982. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  35983. var propVal = _this[v.name];
  35984. // Special case, array, this WON'T WORK IN ALL CASES, all entries have to be of the same type and it must be a BJS well known one
  35985. if (propVal && propVal.constructor === Array) {
  35986. var firstVal = propVal[0];
  35987. if (!firstVal) {
  35988. propVal = 0;
  35989. }
  35990. else {
  35991. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  35992. }
  35993. }
  35994. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  35995. }
  35996. });
  35997. this._modelDirty = false;
  35998. this._modelKey = modelKey;
  35999. return modelKey;
  36000. },
  36001. enumerable: true,
  36002. configurable: true
  36003. });
  36004. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  36005. /**
  36006. * States if the Primitive is dirty and should be rendered again next time.
  36007. * @returns true is dirty, false otherwise
  36008. */
  36009. get: function () {
  36010. return (this._instanceDirtyFlags !== 0) || this._modelDirty;
  36011. },
  36012. enumerable: true,
  36013. configurable: true
  36014. });
  36015. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  36016. /**
  36017. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  36018. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  36019. */
  36020. get: function () {
  36021. if (!this._propInfo) {
  36022. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  36023. if (!cti) {
  36024. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  36025. }
  36026. this._propInfo = cti.fullContent;
  36027. }
  36028. return this._propInfo;
  36029. },
  36030. enumerable: true,
  36031. configurable: true
  36032. });
  36033. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind) {
  36034. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  36035. var node = dic.getLevelOf(target);
  36036. var propInfo = node.levelContent.get(propId.toString());
  36037. if (propInfo) {
  36038. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  36039. }
  36040. // Create, setup and add the PropInfo object to our prop dictionary
  36041. propInfo = new Prim2DPropInfo();
  36042. propInfo.id = propId;
  36043. propInfo.flagId = Math.pow(2, propId);
  36044. propInfo.kind = kind;
  36045. propInfo.name = propName;
  36046. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  36047. propInfo.typeLevelCompare = typeLevelCompare;
  36048. node.levelContent.add(propName, propInfo);
  36049. return propInfo;
  36050. };
  36051. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  36052. // Nothing to nothing: nothing to do!
  36053. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  36054. return true;
  36055. }
  36056. // Check value unchanged
  36057. if ((curValue != null) && (newValue != null)) {
  36058. if (typeof (curValue.equals) == "function") {
  36059. if (curValue.equals(newValue)) {
  36060. return true;
  36061. }
  36062. }
  36063. else {
  36064. if (curValue === newValue) {
  36065. return true;
  36066. }
  36067. }
  36068. }
  36069. return false;
  36070. };
  36071. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  36072. var i = propertyName.indexOf(".");
  36073. if (i !== -1) {
  36074. propertyName = propertyName.substr(0, i);
  36075. }
  36076. var propInfo = this.propDic.get(propertyName);
  36077. if (!propInfo) {
  36078. return;
  36079. }
  36080. var newValue = this[propertyName];
  36081. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  36082. };
  36083. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  36084. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  36085. if (propInfo.dirtyBoundingInfo) {
  36086. this._levelBoundingInfoDirty = true;
  36087. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  36088. if (this instanceof BABYLON.Prim2DBase) {
  36089. var curprim = this.parent;
  36090. while (curprim) {
  36091. curprim._boundingInfoDirty = true;
  36092. if (curprim instanceof BABYLON.Group2D) {
  36093. if (curprim.isRenderableGroup) {
  36094. break;
  36095. }
  36096. }
  36097. curprim = curprim.parent;
  36098. }
  36099. }
  36100. }
  36101. // Trigger property changed
  36102. var info = SmartPropertyPrim.propChangedInfo;
  36103. info.oldValue = curValue;
  36104. info.newValue = newValue;
  36105. info.propertyName = propName;
  36106. var propMask = propInfo.flagId;
  36107. this.propertyChanged.notifyObservers(info, propMask);
  36108. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  36109. if (this instanceof BABYLON.Group2D) {
  36110. this.handleGroupChanged(propInfo);
  36111. }
  36112. // Check if we need to dirty only if the type change and make the test
  36113. var skipDirty = false;
  36114. if (typeLevelCompare && curValue != null && newValue != null) {
  36115. var cvProto = curValue.__proto__;
  36116. var nvProto = newValue.__proto__;
  36117. skipDirty = (cvProto === nvProto);
  36118. }
  36119. // Set the dirty flags
  36120. if (!skipDirty) {
  36121. if (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  36122. if (!this.isDirty) {
  36123. this.onPrimBecomesDirty();
  36124. }
  36125. this._modelDirty = true;
  36126. }
  36127. else if ((propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  36128. if (!this.isDirty) {
  36129. this.onPrimBecomesDirty();
  36130. }
  36131. this._instanceDirtyFlags |= propMask;
  36132. }
  36133. }
  36134. };
  36135. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  36136. };
  36137. /**
  36138. * Check if a given set of properties are dirty or not.
  36139. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  36140. * @return true if at least one property is dirty, false if none of them are.
  36141. */
  36142. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  36143. return (this._instanceDirtyFlags & flags) !== 0;
  36144. };
  36145. /**
  36146. * Clear a given set of properties.
  36147. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  36148. * @return the new set of property still marked as dirty
  36149. */
  36150. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  36151. this._instanceDirtyFlags &= ~flags;
  36152. return this._instanceDirtyFlags;
  36153. };
  36154. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  36155. this._instanceDirtyFlags = 0;
  36156. };
  36157. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  36158. /**
  36159. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  36160. * @returns {}
  36161. */
  36162. get: function () {
  36163. if (this._levelBoundingInfoDirty) {
  36164. this.updateLevelBoundingInfo();
  36165. this._levelBoundingInfoDirty = false;
  36166. }
  36167. return this._levelBoundingInfo;
  36168. },
  36169. enumerable: true,
  36170. configurable: true
  36171. });
  36172. /**
  36173. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  36174. */
  36175. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  36176. };
  36177. /**
  36178. * Property method called when the Primitive becomes dirty
  36179. */
  36180. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  36181. };
  36182. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, kind) {
  36183. return function (target, propName, descriptor) {
  36184. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind);
  36185. if (piStore) {
  36186. piStore(propInfo);
  36187. }
  36188. var getter = descriptor.get, setter = descriptor.set;
  36189. // Overload the property setter implementation to add our own logic
  36190. descriptor.set = function (val) {
  36191. // check for disposed first, do nothing
  36192. if (this.isDisposed) {
  36193. return;
  36194. }
  36195. var curVal = getter.call(this);
  36196. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  36197. return;
  36198. }
  36199. // Cast the object we're working one
  36200. var prim = this;
  36201. // Change the value
  36202. setter.call(this, val);
  36203. // Notify change, dirty flags update
  36204. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  36205. };
  36206. };
  36207. };
  36208. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  36209. SmartPropertyPrim = __decorate([
  36210. BABYLON.className("SmartPropertyPrim")
  36211. ], SmartPropertyPrim);
  36212. return SmartPropertyPrim;
  36213. })();
  36214. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  36215. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36216. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36217. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36218. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_MODEL);
  36219. }
  36220. BABYLON.modelLevelProperty = modelLevelProperty;
  36221. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36222. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36223. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36224. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_INSTANCE);
  36225. }
  36226. BABYLON.instanceLevelProperty = instanceLevelProperty;
  36227. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36228. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36229. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36230. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_DYNAMIC);
  36231. }
  36232. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  36233. })(BABYLON || (BABYLON = {}));
  36234. var BABYLON;
  36235. (function (BABYLON) {
  36236. var Render2DContext = (function () {
  36237. function Render2DContext() {
  36238. }
  36239. return Render2DContext;
  36240. })();
  36241. BABYLON.Render2DContext = Render2DContext;
  36242. /**
  36243. * This class store information for the pointerEventObservable Observable.
  36244. * 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.
  36245. */
  36246. var PrimitivePointerInfo = (function () {
  36247. function PrimitivePointerInfo() {
  36248. this.primitivePointerPos = BABYLON.Vector2.Zero();
  36249. this.tilt = BABYLON.Vector2.Zero();
  36250. this.cancelBubble = false;
  36251. }
  36252. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  36253. // 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.
  36254. /**
  36255. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  36256. * Bubbles: yes
  36257. */
  36258. get: function () {
  36259. return PrimitivePointerInfo._pointerOver;
  36260. },
  36261. enumerable: true,
  36262. configurable: true
  36263. });
  36264. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  36265. /**
  36266. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  36267. * Bubbles: no
  36268. */
  36269. get: function () {
  36270. return PrimitivePointerInfo._pointerEnter;
  36271. },
  36272. enumerable: true,
  36273. configurable: true
  36274. });
  36275. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  36276. /**
  36277. * 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.
  36278. * Bubbles: yes
  36279. */
  36280. get: function () {
  36281. return PrimitivePointerInfo._pointerDown;
  36282. },
  36283. enumerable: true,
  36284. configurable: true
  36285. });
  36286. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  36287. /**
  36288. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  36289. * Bubbles: yes
  36290. */
  36291. get: function () {
  36292. return PrimitivePointerInfo._pointerMouseWheel;
  36293. },
  36294. enumerable: true,
  36295. configurable: true
  36296. });
  36297. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  36298. /**
  36299. * 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.
  36300. * Bubbles: yes
  36301. */
  36302. get: function () {
  36303. return PrimitivePointerInfo._pointerMove;
  36304. },
  36305. enumerable: true,
  36306. configurable: true
  36307. });
  36308. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  36309. /**
  36310. * 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.
  36311. * Bubbles: yes
  36312. */
  36313. get: function () {
  36314. return PrimitivePointerInfo._pointerUp;
  36315. },
  36316. enumerable: true,
  36317. configurable: true
  36318. });
  36319. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  36320. /**
  36321. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  36322. * Bubbles: yes
  36323. */
  36324. get: function () {
  36325. return PrimitivePointerInfo._pointerOut;
  36326. },
  36327. enumerable: true,
  36328. configurable: true
  36329. });
  36330. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  36331. /**
  36332. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  36333. * Bubbles: no
  36334. */
  36335. get: function () {
  36336. return PrimitivePointerInfo._pointerLeave;
  36337. },
  36338. enumerable: true,
  36339. configurable: true
  36340. });
  36341. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  36342. /**
  36343. * 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.
  36344. * Bubbles: yes
  36345. */
  36346. get: function () {
  36347. return PrimitivePointerInfo._pointerGotCapture;
  36348. },
  36349. enumerable: true,
  36350. configurable: true
  36351. });
  36352. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  36353. /**
  36354. * This event type is raised after pointer capture is released for a pointer.
  36355. * Bubbles: yes
  36356. */
  36357. get: function () {
  36358. return PrimitivePointerInfo._pointerLostCapture;
  36359. },
  36360. enumerable: true,
  36361. configurable: true
  36362. });
  36363. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  36364. get: function () {
  36365. return PrimitivePointerInfo._mouseWheelPrecision;
  36366. },
  36367. enumerable: true,
  36368. configurable: true
  36369. });
  36370. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  36371. this.relatedTarget = prim;
  36372. this.relatedTargetPointerPos = primPointerPos;
  36373. };
  36374. PrimitivePointerInfo.getEventTypeName = function (mask) {
  36375. switch (mask) {
  36376. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  36377. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  36378. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  36379. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  36380. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  36381. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  36382. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  36383. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  36384. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  36385. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  36386. }
  36387. };
  36388. PrimitivePointerInfo._pointerOver = 0x0001;
  36389. PrimitivePointerInfo._pointerEnter = 0x0002;
  36390. PrimitivePointerInfo._pointerDown = 0x0004;
  36391. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  36392. PrimitivePointerInfo._pointerMove = 0x0010;
  36393. PrimitivePointerInfo._pointerUp = 0x0020;
  36394. PrimitivePointerInfo._pointerOut = 0x0040;
  36395. PrimitivePointerInfo._pointerLeave = 0x0080;
  36396. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  36397. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  36398. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  36399. return PrimitivePointerInfo;
  36400. })();
  36401. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  36402. /**
  36403. * Stores information about a Primitive that was intersected
  36404. */
  36405. var PrimitiveIntersectedInfo = (function () {
  36406. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  36407. this.prim = prim;
  36408. this.intersectionLocation = intersectionLocation;
  36409. }
  36410. return PrimitiveIntersectedInfo;
  36411. })();
  36412. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  36413. /**
  36414. * Main class used for the Primitive Intersection API
  36415. */
  36416. var IntersectInfo2D = (function () {
  36417. function IntersectInfo2D() {
  36418. this.findFirstOnly = false;
  36419. this.intersectHidden = false;
  36420. this.pickPosition = BABYLON.Vector2.Zero();
  36421. }
  36422. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  36423. /**
  36424. * true if at least one primitive intersected during the test
  36425. */
  36426. get: function () {
  36427. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  36428. },
  36429. enumerable: true,
  36430. configurable: true
  36431. });
  36432. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  36433. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  36434. var cur = _a[_i];
  36435. if (cur.prim === prim) {
  36436. return cur.intersectionLocation;
  36437. }
  36438. }
  36439. return null;
  36440. };
  36441. // Internals, don't use
  36442. IntersectInfo2D.prototype._exit = function (firstLevel) {
  36443. if (firstLevel) {
  36444. this._globalPickPosition = null;
  36445. }
  36446. };
  36447. return IntersectInfo2D;
  36448. })();
  36449. BABYLON.IntersectInfo2D = IntersectInfo2D;
  36450. var Prim2DBase = (function (_super) {
  36451. __extends(Prim2DBase, _super);
  36452. function Prim2DBase() {
  36453. _super.apply(this, arguments);
  36454. }
  36455. Prim2DBase.prototype.setupPrim2DBase = function (owner, parent, id, position, origin, isVisible) {
  36456. if (isVisible === void 0) { isVisible = true; }
  36457. if (!(this instanceof BABYLON.Group2D) && !(this instanceof BABYLON.Sprite2D && id !== null && id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  36458. 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");
  36459. }
  36460. this.setupSmartPropertyPrim();
  36461. this._pointerEventObservable = new BABYLON.Observable();
  36462. this._isPickable = true;
  36463. this._siblingDepthOffset = this._hierarchyDepthOffset = 0;
  36464. this._boundingInfoDirty = true;
  36465. this._boundingInfo = new BABYLON.BoundingInfo2D();
  36466. this._owner = owner;
  36467. this._parent = parent;
  36468. if (parent != null) {
  36469. this._hierarchyDepth = parent._hierarchyDepth + 1;
  36470. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  36471. parent.addChild(this);
  36472. }
  36473. else {
  36474. this._hierarchyDepth = 0;
  36475. this._renderGroup = null;
  36476. }
  36477. this._id = id;
  36478. this.propertyChanged = new BABYLON.Observable();
  36479. this._children = new Array();
  36480. this._globalTransformProcessStep = 0;
  36481. this._globalTransformStep = 0;
  36482. if (this instanceof BABYLON.Group2D) {
  36483. var group = this;
  36484. group.detectGroupStates();
  36485. }
  36486. this.position = position;
  36487. this.rotation = 0;
  36488. this.scale = 1;
  36489. this.levelVisible = isVisible;
  36490. this.origin = origin || new BABYLON.Vector2(0.5, 0.5);
  36491. };
  36492. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  36493. get: function () {
  36494. if (!this._actionManager) {
  36495. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  36496. }
  36497. return this._actionManager;
  36498. },
  36499. enumerable: true,
  36500. configurable: true
  36501. });
  36502. /**
  36503. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  36504. * @param predicate the predicate to test on each parent
  36505. * @return the first primitive where the predicate was successful
  36506. */
  36507. Prim2DBase.prototype.traverseUp = function (predicate) {
  36508. var p = this;
  36509. while (p != null) {
  36510. if (predicate(p)) {
  36511. return p;
  36512. }
  36513. p = p._parent;
  36514. }
  36515. return null;
  36516. };
  36517. Object.defineProperty(Prim2DBase.prototype, "owner", {
  36518. /**
  36519. * Retrieve the owner Canvas2D
  36520. */
  36521. get: function () {
  36522. return this._owner;
  36523. },
  36524. enumerable: true,
  36525. configurable: true
  36526. });
  36527. Object.defineProperty(Prim2DBase.prototype, "parent", {
  36528. /**
  36529. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  36530. */
  36531. get: function () {
  36532. return this._parent;
  36533. },
  36534. enumerable: true,
  36535. configurable: true
  36536. });
  36537. Object.defineProperty(Prim2DBase.prototype, "children", {
  36538. /**
  36539. * The array of direct children primitives
  36540. */
  36541. get: function () {
  36542. return this._children;
  36543. },
  36544. enumerable: true,
  36545. configurable: true
  36546. });
  36547. Object.defineProperty(Prim2DBase.prototype, "id", {
  36548. /**
  36549. * The identifier of this primitive, may not be unique, it's for information purpose only
  36550. */
  36551. get: function () {
  36552. return this._id;
  36553. },
  36554. enumerable: true,
  36555. configurable: true
  36556. });
  36557. Object.defineProperty(Prim2DBase.prototype, "position", {
  36558. get: function () {
  36559. return this._position;
  36560. },
  36561. set: function (value) {
  36562. this._position = value;
  36563. },
  36564. enumerable: true,
  36565. configurable: true
  36566. });
  36567. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  36568. get: function () {
  36569. return this._rotation;
  36570. },
  36571. set: function (value) {
  36572. this._rotation = value;
  36573. },
  36574. enumerable: true,
  36575. configurable: true
  36576. });
  36577. Object.defineProperty(Prim2DBase.prototype, "scale", {
  36578. get: function () {
  36579. return this._scale;
  36580. },
  36581. set: function (value) {
  36582. this._scale = value;
  36583. },
  36584. enumerable: true,
  36585. configurable: true
  36586. });
  36587. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  36588. /**
  36589. * this method must be implemented by the primitive type to return its size
  36590. * @returns The size of the primitive
  36591. */
  36592. get: function () {
  36593. return undefined;
  36594. },
  36595. enumerable: true,
  36596. configurable: true
  36597. });
  36598. Object.defineProperty(Prim2DBase.prototype, "origin", {
  36599. /**
  36600. * The origin defines the normalized coordinate of the center of the primitive, from the top/left corner.
  36601. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  36602. * For instance:
  36603. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  36604. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  36605. * 0,1 means the center is top/left
  36606. * @returns The normalized center.
  36607. */
  36608. get: function () {
  36609. return this._origin;
  36610. },
  36611. set: function (value) {
  36612. this._origin = value;
  36613. },
  36614. enumerable: true,
  36615. configurable: true
  36616. });
  36617. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  36618. get: function () {
  36619. return this._levelVisible;
  36620. },
  36621. set: function (value) {
  36622. this._levelVisible = value;
  36623. },
  36624. enumerable: true,
  36625. configurable: true
  36626. });
  36627. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  36628. get: function () {
  36629. return this._isVisible;
  36630. },
  36631. set: function (value) {
  36632. this._isVisible = value;
  36633. },
  36634. enumerable: true,
  36635. configurable: true
  36636. });
  36637. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  36638. get: function () {
  36639. return this._zOrder;
  36640. },
  36641. set: function (value) {
  36642. this._zOrder = value;
  36643. },
  36644. enumerable: true,
  36645. configurable: true
  36646. });
  36647. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  36648. /**
  36649. * Define if the Primitive can be subject to intersection test or not (default is true)
  36650. */
  36651. get: function () {
  36652. return this._isPickable;
  36653. },
  36654. set: function (value) {
  36655. this._isPickable = value;
  36656. },
  36657. enumerable: true,
  36658. configurable: true
  36659. });
  36660. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  36661. /**
  36662. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  36663. * @returns {}
  36664. */
  36665. get: function () {
  36666. return this._hierarchyDepth;
  36667. },
  36668. enumerable: true,
  36669. configurable: true
  36670. });
  36671. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  36672. /**
  36673. * Retrieve the Group that is responsible to render this primitive
  36674. * @returns {}
  36675. */
  36676. get: function () {
  36677. return this._renderGroup;
  36678. },
  36679. enumerable: true,
  36680. configurable: true
  36681. });
  36682. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  36683. /**
  36684. * Get the global transformation matrix of the primitive
  36685. */
  36686. get: function () {
  36687. return this._globalTransform;
  36688. },
  36689. enumerable: true,
  36690. configurable: true
  36691. });
  36692. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  36693. /**
  36694. * Get invert of the global transformation matrix of the primitive
  36695. * @returns {}
  36696. */
  36697. get: function () {
  36698. return this._invGlobalTransform;
  36699. },
  36700. enumerable: true,
  36701. configurable: true
  36702. });
  36703. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  36704. /**
  36705. * Get the local transformation of the primitive
  36706. */
  36707. get: function () {
  36708. this._updateLocalTransform();
  36709. return this._localTransform;
  36710. },
  36711. enumerable: true,
  36712. configurable: true
  36713. });
  36714. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  36715. /**
  36716. * Get the boundingInfo associated to the primitive.
  36717. * The value is supposed to be always up to date
  36718. */
  36719. get: function () {
  36720. if (this._boundingInfoDirty) {
  36721. this._boundingInfo = this.levelBoundingInfo.clone();
  36722. var bi = this._boundingInfo;
  36723. var tps = new BABYLON.BoundingInfo2D();
  36724. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  36725. var curChild = _a[_i];
  36726. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  36727. bi.unionToRef(tps, bi);
  36728. }
  36729. this._boundingInfoDirty = false;
  36730. }
  36731. return this._boundingInfo;
  36732. },
  36733. enumerable: true,
  36734. configurable: true
  36735. });
  36736. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  36737. /**
  36738. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  36739. */
  36740. get: function () {
  36741. return this._pointerEventObservable;
  36742. },
  36743. enumerable: true,
  36744. configurable: true
  36745. });
  36746. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  36747. return false;
  36748. };
  36749. /**
  36750. * Capture all the Events of the given PointerId for this primitive.
  36751. * Don't forget to call releasePointerEventsCapture when done.
  36752. * @param pointerId the Id of the pointer to capture the events from.
  36753. */
  36754. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  36755. return this.owner._setPointerCapture(pointerId, this);
  36756. };
  36757. /**
  36758. * Release a captured pointer made with setPointerEventCapture.
  36759. * @param pointerId the Id of the pointer to release the capture from.
  36760. */
  36761. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  36762. return this.owner._releasePointerCapture(pointerId, this);
  36763. };
  36764. /**
  36765. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  36766. * @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.
  36767. */
  36768. Prim2DBase.prototype.intersect = function (intersectInfo) {
  36769. if (!intersectInfo) {
  36770. return false;
  36771. }
  36772. // If this is null it means this method is call for the first level, initialize stuffs
  36773. var firstLevel = !intersectInfo._globalPickPosition;
  36774. if (firstLevel) {
  36775. // 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).
  36776. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  36777. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  36778. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  36779. intersectInfo.intersectedPrimitives = new Array();
  36780. intersectInfo.topMostIntersectedPrimitive = null;
  36781. }
  36782. if (!intersectInfo.intersectHidden && !this.isVisible) {
  36783. return false;
  36784. }
  36785. // Fast rejection test with boundingInfo
  36786. if (!this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  36787. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  36788. intersectInfo._exit(firstLevel);
  36789. return false;
  36790. }
  36791. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  36792. var levelIntersectRes = this.levelIntersect(intersectInfo);
  36793. if (levelIntersectRes) {
  36794. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  36795. intersectInfo.intersectedPrimitives.push(pii);
  36796. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.getActualZOffset() > pii.prim.getActualZOffset())) {
  36797. intersectInfo.topMostIntersectedPrimitive = pii;
  36798. }
  36799. // If we must stop at the first intersection, we're done, quit!
  36800. if (intersectInfo.findFirstOnly) {
  36801. intersectInfo._exit(firstLevel);
  36802. return true;
  36803. }
  36804. }
  36805. // Recurse to children if needed
  36806. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  36807. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  36808. var curChild = _a[_i];
  36809. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  36810. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  36811. continue;
  36812. }
  36813. // Must compute the localPickLocation for the children level
  36814. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  36815. // If we got an intersection with the child and we only need to find the first one, quit!
  36816. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  36817. intersectInfo._exit(firstLevel);
  36818. return true;
  36819. }
  36820. }
  36821. }
  36822. intersectInfo._exit(firstLevel);
  36823. return intersectInfo.isIntersected;
  36824. };
  36825. Prim2DBase.prototype.moveChild = function (child, previous) {
  36826. if (child.parent !== this) {
  36827. return false;
  36828. }
  36829. var prevOffset, nextOffset;
  36830. var childIndex = this._children.indexOf(child);
  36831. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  36832. // Move to first position
  36833. if (!previous) {
  36834. prevOffset = 1;
  36835. nextOffset = this._children[1]._siblingDepthOffset;
  36836. }
  36837. else {
  36838. prevOffset = this._children[prevIndex]._siblingDepthOffset;
  36839. nextOffset = this._children[prevIndex + 1]._siblingDepthOffset;
  36840. }
  36841. child._siblingDepthOffset = (nextOffset - prevOffset) / 2;
  36842. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  36843. };
  36844. Prim2DBase.prototype.addChild = function (child) {
  36845. child._hierarchyDepthOffset = this._hierarchyDepthOffset + ((this._children.length + 1) * this._siblingDepthOffset);
  36846. child._siblingDepthOffset = this._siblingDepthOffset / this.owner.hierarchyLevelMaxSiblingCount;
  36847. this._children.push(child);
  36848. };
  36849. Prim2DBase.prototype.dispose = function () {
  36850. if (!_super.prototype.dispose.call(this)) {
  36851. return false;
  36852. }
  36853. if (this._actionManager) {
  36854. this._actionManager.dispose();
  36855. this._actionManager = null;
  36856. }
  36857. // If there's a parent, remove this object from its parent list
  36858. if (this._parent) {
  36859. var i = this._parent._children.indexOf(this);
  36860. if (i !== undefined) {
  36861. this._parent._children.splice(i, 1);
  36862. }
  36863. this._parent = null;
  36864. }
  36865. // Recurse dispose to children
  36866. if (this._children) {
  36867. while (this._children.length > 0) {
  36868. this._children[this._children.length - 1].dispose();
  36869. }
  36870. }
  36871. return true;
  36872. };
  36873. Prim2DBase.prototype.getActualZOffset = function () {
  36874. return this._zOrder || (1 - this._hierarchyDepthOffset);
  36875. };
  36876. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  36877. if (this._renderGroup) {
  36878. this._renderGroup._addPrimToDirtyList(this);
  36879. }
  36880. };
  36881. Prim2DBase.prototype._needPrepare = function () {
  36882. return this._visibilityChanged || this._modelDirty || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  36883. };
  36884. Prim2DBase.prototype._prepareRender = function (context) {
  36885. this._prepareRenderPre(context);
  36886. this._prepareRenderPost(context);
  36887. };
  36888. Prim2DBase.prototype._prepareRenderPre = function (context) {
  36889. };
  36890. Prim2DBase.prototype._prepareRenderPost = function (context) {
  36891. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  36892. if (this instanceof BABYLON.Group2D) {
  36893. var self = this;
  36894. if (self.isRenderableGroup) {
  36895. return;
  36896. }
  36897. }
  36898. // Check if we need to recurse the prepare to children primitives
  36899. // - must have children
  36900. // - the global transform of this level have changed, or
  36901. // - the visible state of primitive has changed
  36902. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  36903. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  36904. this._children.forEach(function (c) {
  36905. // As usual stop the recursion if we meet a renderable group
  36906. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  36907. c._prepareRender(context);
  36908. }
  36909. });
  36910. }
  36911. // Finally reset the dirty flags as we've processed everything
  36912. this._modelDirty = false;
  36913. this._instanceDirtyFlags = 0;
  36914. };
  36915. Prim2DBase.CheckParent = function (parent) {
  36916. if (!parent) {
  36917. 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)");
  36918. }
  36919. };
  36920. Prim2DBase.prototype.updateGlobalTransVisOf = function (list, recurse) {
  36921. for (var _i = 0; _i < list.length; _i++) {
  36922. var cur = list[_i];
  36923. cur.updateGlobalTransVis(recurse);
  36924. }
  36925. };
  36926. Prim2DBase.prototype._updateLocalTransform = function () {
  36927. var tflags = Prim2DBase.positionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId;
  36928. if (this.checkPropertiesDirty(tflags)) {
  36929. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  36930. 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));
  36931. this._localTransform = local;
  36932. this.clearPropertiesDirty(tflags);
  36933. // 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
  36934. //var actualSize = this.actualSize;
  36935. //if (!actualSize) {
  36936. // throw new Error(`The primitive type: ${Tools.getClassName(this)} must implement the actualSize get property!`);
  36937. //}
  36938. //local.m[12] -= (actualSize.width * this.origin.x) * local.m[0] + (actualSize.height * this.origin.y) * local.m[4];
  36939. //local.m[13] -= (actualSize.width * this.origin.x) * local.m[1] + (actualSize.height * this.origin.y) * local.m[5];
  36940. return true;
  36941. }
  36942. return false;
  36943. };
  36944. Prim2DBase.prototype.updateGlobalTransVis = function (recurse) {
  36945. if (this.isDisposed) {
  36946. return;
  36947. }
  36948. // Check if the parent is synced
  36949. if (this._parent && this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  36950. this._parent.updateGlobalTransVis(false);
  36951. }
  36952. // Check if we must update this prim
  36953. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  36954. var curVisibleState = this.isVisible;
  36955. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  36956. // Detect a change of visibility
  36957. this._visibilityChanged = curVisibleState !== this.isVisible;
  36958. // Get/compute the localTransform
  36959. var localDirty = this._updateLocalTransform();
  36960. // Check if we have to update the globalTransform
  36961. if (!this._globalTransform || localDirty || (this._parent && this._parent._globalTransformStep !== this._parentTransformStep)) {
  36962. this._globalTransform = this._parent ? this._localTransform.multiply(this._parent._globalTransform) : this._localTransform;
  36963. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  36964. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  36965. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  36966. }
  36967. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  36968. }
  36969. if (recurse) {
  36970. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  36971. var child = _a[_i];
  36972. // Stop the recursion if we meet a renderable group
  36973. child.updateGlobalTransVis(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  36974. }
  36975. }
  36976. };
  36977. Prim2DBase.PRIM2DBASE_PROPCOUNT = 10;
  36978. __decorate([
  36979. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.positionProperty = pi; }, false, true)
  36980. ], Prim2DBase.prototype, "position", null);
  36981. __decorate([
  36982. BABYLON.instanceLevelProperty(2, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  36983. ], Prim2DBase.prototype, "rotation", null);
  36984. __decorate([
  36985. BABYLON.instanceLevelProperty(3, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  36986. ], Prim2DBase.prototype, "scale", null);
  36987. __decorate([
  36988. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  36989. ], Prim2DBase.prototype, "origin", null);
  36990. __decorate([
  36991. BABYLON.dynamicLevelProperty(5, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  36992. ], Prim2DBase.prototype, "levelVisible", null);
  36993. __decorate([
  36994. BABYLON.instanceLevelProperty(6, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  36995. ], Prim2DBase.prototype, "isVisible", null);
  36996. __decorate([
  36997. BABYLON.instanceLevelProperty(7, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  36998. ], Prim2DBase.prototype, "zOrder", null);
  36999. Prim2DBase = __decorate([
  37000. BABYLON.className("Prim2DBase")
  37001. ], Prim2DBase);
  37002. return Prim2DBase;
  37003. })(BABYLON.SmartPropertyPrim);
  37004. BABYLON.Prim2DBase = Prim2DBase;
  37005. })(BABYLON || (BABYLON = {}));
  37006. var BABYLON;
  37007. (function (BABYLON) {
  37008. var GroupInstanceInfo = (function () {
  37009. function GroupInstanceInfo(owner, cache) {
  37010. this._owner = owner;
  37011. this._modelCache = cache;
  37012. this._modelCache.addRef();
  37013. this._instancesPartsData = new Array();
  37014. this._instancesPartsBuffer = new Array();
  37015. this._instancesPartsBufferSize = new Array();
  37016. this._partIndexFromId = new BABYLON.StringDictionary();
  37017. this._instancesPartsUsedShaderCategories = new Array();
  37018. }
  37019. GroupInstanceInfo.prototype.dispose = function () {
  37020. if (this._isDisposed) {
  37021. return false;
  37022. }
  37023. if (this._modelCache) {
  37024. this._modelCache.dispose();
  37025. }
  37026. var engine = this._owner.owner.engine;
  37027. if (this._instancesPartsBuffer) {
  37028. this._instancesPartsBuffer.forEach(function (b) {
  37029. engine._releaseBuffer(b);
  37030. });
  37031. }
  37032. this._partIndexFromId = null;
  37033. this._instancesPartsData = null;
  37034. this._instancesPartsBufferSize = null;
  37035. this._instancesPartsUsedShaderCategories = null;
  37036. return true;
  37037. };
  37038. return GroupInstanceInfo;
  37039. })();
  37040. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  37041. var ModelRenderCache = (function () {
  37042. function ModelRenderCache(engine, modelKey, isTransparent) {
  37043. this._engine = engine;
  37044. this._modelKey = modelKey;
  37045. this._isTransparent = isTransparent;
  37046. this._nextKey = 1;
  37047. this._refCounter = 1;
  37048. this._instancesData = new BABYLON.StringDictionary();
  37049. }
  37050. ModelRenderCache.prototype.dispose = function () {
  37051. if (--this._refCounter !== 0) {
  37052. return false;
  37053. }
  37054. // Remove the Model Render Cache from the global dictionary
  37055. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  37056. if (edata) {
  37057. edata.DisposeModelRenderCache(this);
  37058. }
  37059. return true;
  37060. };
  37061. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  37062. get: function () {
  37063. return this._refCounter <= 0;
  37064. },
  37065. enumerable: true,
  37066. configurable: true
  37067. });
  37068. ModelRenderCache.prototype.addRef = function () {
  37069. return ++this._refCounter;
  37070. };
  37071. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  37072. get: function () {
  37073. return this._modelKey;
  37074. },
  37075. enumerable: true,
  37076. configurable: true
  37077. });
  37078. /**
  37079. * Render the model instances
  37080. * @param instanceInfo
  37081. * @param context
  37082. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  37083. */
  37084. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  37085. return true;
  37086. };
  37087. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  37088. var key = this._nextKey.toString();
  37089. if (!this._instancesData.add(key, data)) {
  37090. throw Error("Key: " + key + " is already allocated");
  37091. }
  37092. ++this._nextKey;
  37093. return key;
  37094. };
  37095. ModelRenderCache.prototype.removeInstanceData = function (key) {
  37096. this._instancesData.remove(key);
  37097. };
  37098. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  37099. for (var i = 0; i < this._partIdList.length; i++) {
  37100. if (this._partIdList[i] === partId) {
  37101. return i;
  37102. }
  37103. }
  37104. return null;
  37105. };
  37106. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  37107. var i = this.getPartIndexFromId(partId);
  37108. if (i === null) {
  37109. return null;
  37110. }
  37111. var ci = this._partsClassInfo[i];
  37112. var categories = this._partsUsedCategories[i];
  37113. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  37114. return res;
  37115. };
  37116. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  37117. var offset = (this._partsDataStride[partIndex] / 4) * elementCount;
  37118. var pci = this._partsClassInfo[partIndex];
  37119. var self = this;
  37120. pci.fullContent.forEach(function (k, v) {
  37121. if (!v.category || self._partsUsedCategories[partIndex].indexOf(v.category) !== 1) {
  37122. switch (v.dataType) {
  37123. case 4 /* float */:
  37124. {
  37125. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  37126. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  37127. break;
  37128. }
  37129. case 0 /* Vector2 */:
  37130. {
  37131. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  37132. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  37133. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  37134. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  37135. break;
  37136. }
  37137. case 5 /* Color3 */:
  37138. case 1 /* Vector3 */:
  37139. {
  37140. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  37141. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  37142. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  37143. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  37144. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  37145. break;
  37146. }
  37147. case 6 /* Color4 */:
  37148. case 2 /* Vector4 */:
  37149. {
  37150. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  37151. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  37152. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  37153. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  37154. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  37155. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  37156. break;
  37157. }
  37158. default:
  37159. }
  37160. }
  37161. });
  37162. };
  37163. Object.defineProperty(ModelRenderCache.prototype, "isTransparent", {
  37164. get: function () {
  37165. return this._isTransparent;
  37166. },
  37167. enumerable: true,
  37168. configurable: true
  37169. });
  37170. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  37171. // let i = this.getPartIndexFromId(partId);
  37172. // if (i === null) {
  37173. // return null;
  37174. // }
  37175. // let pci = this._partsClassInfo[i];
  37176. // pci.fullContent.forEach((k, v) => {
  37177. // if (uniforms.indexOf(v.attributeName) !== -1) {
  37178. // v.uniformLocation = effect.getUniform(v.attributeName);
  37179. // }
  37180. // });
  37181. //}
  37182. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  37183. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  37184. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  37185. return ModelRenderCache;
  37186. })();
  37187. BABYLON.ModelRenderCache = ModelRenderCache;
  37188. })(BABYLON || (BABYLON = {}));
  37189. var BABYLON;
  37190. (function (BABYLON) {
  37191. var InstanceClassInfo = (function () {
  37192. function InstanceClassInfo(base) {
  37193. this._baseInfo = base;
  37194. this._nextOffset = new BABYLON.StringDictionary();
  37195. this._attributes = new Array();
  37196. }
  37197. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  37198. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  37199. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  37200. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  37201. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  37202. if (push) {
  37203. this._attributes.push(propInfo);
  37204. }
  37205. };
  37206. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  37207. var catInline = ";" + categories.join(";") + ";";
  37208. var res = new Array();
  37209. var curInfo = this;
  37210. while (curInfo) {
  37211. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  37212. var attrib = _a[_i];
  37213. // 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
  37214. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  37215. var index = effect.getAttributeLocationByName(attrib.attributeName);
  37216. var iai = new BABYLON.InstancingAttributeInfo();
  37217. iai.index = index;
  37218. 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)
  37219. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  37220. iai.attributeName = attrib.attributeName;
  37221. res.push(iai);
  37222. }
  37223. }
  37224. curInfo = curInfo._baseInfo;
  37225. }
  37226. return res;
  37227. };
  37228. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  37229. var res = new Array();
  37230. var curInfo = this;
  37231. while (curInfo) {
  37232. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  37233. var attrib = _a[_i];
  37234. // 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
  37235. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  37236. res.push(attrib.attributeName);
  37237. }
  37238. }
  37239. curInfo = curInfo._baseInfo;
  37240. }
  37241. return res;
  37242. };
  37243. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  37244. var curOffset = 0;
  37245. var curBase = this._baseInfo;
  37246. while (curBase) {
  37247. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  37248. curBase = curBase._baseInfo;
  37249. }
  37250. return curOffset;
  37251. };
  37252. return InstanceClassInfo;
  37253. })();
  37254. BABYLON.InstanceClassInfo = InstanceClassInfo;
  37255. var InstancePropInfo = (function () {
  37256. function InstancePropInfo() {
  37257. this.instanceOffset = new BABYLON.StringDictionary();
  37258. }
  37259. InstancePropInfo.prototype.setSize = function (val) {
  37260. if (val instanceof BABYLON.Vector2) {
  37261. this.size = 8;
  37262. this.dataType = 0 /* Vector2 */;
  37263. return;
  37264. }
  37265. if (val instanceof BABYLON.Vector3) {
  37266. this.size = 12;
  37267. this.dataType = 1 /* Vector3 */;
  37268. return;
  37269. }
  37270. if (val instanceof BABYLON.Vector4) {
  37271. this.size = 16;
  37272. this.dataType = 2 /* Vector4 */;
  37273. return;
  37274. }
  37275. if (val instanceof BABYLON.Matrix) {
  37276. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  37277. }
  37278. if (typeof (val) === "number") {
  37279. this.size = 4;
  37280. this.dataType = 4 /* float */;
  37281. return;
  37282. }
  37283. if (val instanceof BABYLON.Color3) {
  37284. this.size = 12;
  37285. this.dataType = 5 /* Color3 */;
  37286. return;
  37287. }
  37288. if (val instanceof BABYLON.Color4) {
  37289. this.size = 16;
  37290. this.dataType = 6 /* Color4 */;
  37291. return;
  37292. }
  37293. if (val instanceof BABYLON.Size) {
  37294. this.size = 8;
  37295. this.dataType = 7 /* Size */;
  37296. return;
  37297. }
  37298. return;
  37299. };
  37300. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  37301. switch (this.dataType) {
  37302. case 0 /* Vector2 */:
  37303. {
  37304. var v = val;
  37305. array[offset + 0] = v.x;
  37306. array[offset + 1] = v.y;
  37307. break;
  37308. }
  37309. case 1 /* Vector3 */:
  37310. {
  37311. var v = val;
  37312. array[offset + 0] = v.x;
  37313. array[offset + 1] = v.y;
  37314. array[offset + 2] = v.z;
  37315. break;
  37316. }
  37317. case 2 /* Vector4 */:
  37318. {
  37319. var v = val;
  37320. array[offset + 0] = v.x;
  37321. array[offset + 1] = v.y;
  37322. array[offset + 2] = v.z;
  37323. array[offset + 3] = v.w;
  37324. break;
  37325. }
  37326. case 5 /* Color3 */:
  37327. {
  37328. var v = val;
  37329. array[offset + 0] = v.r;
  37330. array[offset + 1] = v.g;
  37331. array[offset + 2] = v.b;
  37332. break;
  37333. }
  37334. case 6 /* Color4 */:
  37335. {
  37336. var v = val;
  37337. array[offset + 0] = v.r;
  37338. array[offset + 1] = v.g;
  37339. array[offset + 2] = v.b;
  37340. array[offset + 3] = v.a;
  37341. break;
  37342. }
  37343. case 4 /* float */:
  37344. {
  37345. var v = val;
  37346. array[offset] = v;
  37347. break;
  37348. }
  37349. case 3 /* Matrix */:
  37350. {
  37351. var v = val;
  37352. for (var i = 0; i < 16; i++) {
  37353. array[offset + i] = v.m[i];
  37354. }
  37355. break;
  37356. }
  37357. case 7 /* Size */:
  37358. {
  37359. var s = val;
  37360. array[offset + 0] = s.width;
  37361. array[offset + 1] = s.height;
  37362. break;
  37363. }
  37364. }
  37365. };
  37366. return InstancePropInfo;
  37367. })();
  37368. BABYLON.InstancePropInfo = InstancePropInfo;
  37369. function instanceData(category, shaderAttributeName) {
  37370. return function (target, propName, descriptor) {
  37371. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  37372. var node = dic.getLevelOf(target);
  37373. var instanceDataName = propName;
  37374. shaderAttributeName = shaderAttributeName || instanceDataName;
  37375. var info = node.levelContent.get(instanceDataName);
  37376. if (info) {
  37377. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  37378. }
  37379. info = new InstancePropInfo();
  37380. info.attributeName = shaderAttributeName;
  37381. info.category = category || null;
  37382. if (info.category) {
  37383. info.delimitedCategory = ";" + info.category + ";";
  37384. }
  37385. node.levelContent.add(instanceDataName, info);
  37386. descriptor.get = function () {
  37387. return null;
  37388. };
  37389. descriptor.set = function (val) {
  37390. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  37391. // Quit if it's the case, otherwise we could overwrite data somewhere...
  37392. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  37393. return;
  37394. }
  37395. if (!info.size) {
  37396. info.setSize(val);
  37397. node.classContent.mapProperty(info, true);
  37398. }
  37399. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  37400. node.classContent.mapProperty(info, false);
  37401. }
  37402. var obj = this;
  37403. if (obj.dataBuffer && obj.dataElements) {
  37404. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  37405. info.writeData(obj.dataBuffer.buffer, offset, val);
  37406. }
  37407. };
  37408. };
  37409. }
  37410. BABYLON.instanceData = instanceData;
  37411. var InstanceDataBase = (function () {
  37412. function InstanceDataBase(partId, dataElementCount) {
  37413. this.id = partId;
  37414. this.curElement = 0;
  37415. this.dataElementCount = dataElementCount;
  37416. }
  37417. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  37418. get: function () {
  37419. return null;
  37420. },
  37421. enumerable: true,
  37422. configurable: true
  37423. });
  37424. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  37425. get: function () {
  37426. return null;
  37427. },
  37428. enumerable: true,
  37429. configurable: true
  37430. });
  37431. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  37432. get: function () {
  37433. return null;
  37434. },
  37435. enumerable: true,
  37436. configurable: true
  37437. });
  37438. Object.defineProperty(InstanceDataBase.prototype, "origin", {
  37439. get: function () {
  37440. return null;
  37441. },
  37442. enumerable: true,
  37443. configurable: true
  37444. });
  37445. InstanceDataBase.prototype.getClassTreeInfo = function () {
  37446. if (!this.typeInfo) {
  37447. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  37448. }
  37449. return this.typeInfo;
  37450. };
  37451. InstanceDataBase.prototype.allocElements = function () {
  37452. if (!this.dataBuffer) {
  37453. return;
  37454. }
  37455. var res = new Array(this.dataElementCount);
  37456. for (var i = 0; i < this.dataElementCount; i++) {
  37457. res[i] = this.dataBuffer.allocElement();
  37458. }
  37459. this.dataElements = res;
  37460. };
  37461. InstanceDataBase.prototype.freeElements = function () {
  37462. if (!this.dataElements) {
  37463. return;
  37464. }
  37465. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  37466. var ei = _a[_i];
  37467. this.dataBuffer.freeElement(ei);
  37468. }
  37469. this.dataElements = null;
  37470. };
  37471. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  37472. get: function () {
  37473. return this._dataElementCount;
  37474. },
  37475. set: function (value) {
  37476. if (value === this._dataElementCount) {
  37477. return;
  37478. }
  37479. this.freeElements();
  37480. this._dataElementCount = value;
  37481. this.allocElements();
  37482. },
  37483. enumerable: true,
  37484. configurable: true
  37485. });
  37486. __decorate([
  37487. instanceData()
  37488. ], InstanceDataBase.prototype, "zBias", null);
  37489. __decorate([
  37490. instanceData()
  37491. ], InstanceDataBase.prototype, "transformX", null);
  37492. __decorate([
  37493. instanceData()
  37494. ], InstanceDataBase.prototype, "transformY", null);
  37495. __decorate([
  37496. instanceData()
  37497. ], InstanceDataBase.prototype, "origin", null);
  37498. return InstanceDataBase;
  37499. })();
  37500. BABYLON.InstanceDataBase = InstanceDataBase;
  37501. var RenderablePrim2D = (function (_super) {
  37502. __extends(RenderablePrim2D, _super);
  37503. function RenderablePrim2D() {
  37504. _super.apply(this, arguments);
  37505. }
  37506. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  37507. get: function () {
  37508. return this._isTransparent;
  37509. },
  37510. set: function (value) {
  37511. this._isTransparent = value;
  37512. },
  37513. enumerable: true,
  37514. configurable: true
  37515. });
  37516. RenderablePrim2D.prototype.setupRenderablePrim2D = function (owner, parent, id, position, origin, isVisible) {
  37517. this.setupPrim2DBase(owner, parent, id, position, origin);
  37518. this._isTransparent = false;
  37519. };
  37520. RenderablePrim2D.prototype.dispose = function () {
  37521. if (!_super.prototype.dispose.call(this)) {
  37522. return false;
  37523. }
  37524. if (this._modelRenderInstanceID) {
  37525. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  37526. this._modelRenderInstanceID = null;
  37527. }
  37528. if (this._modelRenderCache) {
  37529. this._modelRenderCache.dispose();
  37530. this._modelRenderCache = null;
  37531. }
  37532. if (this._instanceDataParts) {
  37533. this._instanceDataParts.forEach(function (p) {
  37534. p.freeElements();
  37535. });
  37536. this._instanceDataParts = null;
  37537. }
  37538. return true;
  37539. };
  37540. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  37541. var _this = this;
  37542. _super.prototype._prepareRenderPre.call(this, context);
  37543. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  37544. if (this._modelDirty && this._modelRenderInstanceID) {
  37545. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  37546. this._modelRenderInstanceID = null;
  37547. }
  37548. // Need to create the model?
  37549. var setupModelRenderCache = false;
  37550. if (!this._modelRenderCache || this._modelDirty) {
  37551. if (this._modelRenderCache) {
  37552. this._modelRenderCache.dispose();
  37553. }
  37554. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  37555. var mrc = _this.createModelRenderCache(key, _this.isTransparent);
  37556. setupModelRenderCache = true;
  37557. return mrc;
  37558. });
  37559. this._modelDirty = false;
  37560. // if this is still false it means the MRC already exists, so we add a reference to it
  37561. if (!setupModelRenderCache) {
  37562. this._modelRenderCache.addRef();
  37563. }
  37564. }
  37565. var gii;
  37566. var newInstance = false;
  37567. // Need to create the instance data parts?
  37568. if (!this._modelRenderInstanceID) {
  37569. // Yes, flag it for later, more processing will have to be done
  37570. newInstance = true;
  37571. // Create the instance data parts of the primitive and store them
  37572. var parts = this.createInstanceDataParts();
  37573. this._instanceDataParts = parts;
  37574. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  37575. if (!this._modelRenderCache._partsDataStride) {
  37576. var ctiArray = new Array();
  37577. var dataStrides = new Array();
  37578. var usedCatList = new Array();
  37579. var partIdList = new Array();
  37580. var joinedUsedCatList = new Array();
  37581. for (var _i = 0; _i < parts.length; _i++) {
  37582. var dataPart = parts[_i];
  37583. var cat = this.getUsedShaderCategories(dataPart);
  37584. var cti = dataPart.getClassTreeInfo();
  37585. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  37586. var curVisible = this.isVisible;
  37587. this.isVisible = true;
  37588. // 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.
  37589. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  37590. var joinCat = ";" + cat.join(";") + ";";
  37591. joinedUsedCatList.push(joinCat);
  37592. InstanceClassInfo._CurCategories = joinCat;
  37593. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  37594. this.refreshInstanceDataPart(dataPart);
  37595. this.afterRefreshForLayoutConstruction(dataPart, obj);
  37596. this.isVisible = curVisible;
  37597. var size = 0;
  37598. cti.fullContent.forEach(function (k, v) {
  37599. if (!v.category || cat.indexOf(v.category) !== -1) {
  37600. if (!v.size) {
  37601. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  37602. }
  37603. else {
  37604. size += v.size;
  37605. }
  37606. }
  37607. });
  37608. dataStrides.push(size);
  37609. usedCatList.push(cat);
  37610. ctiArray.push(cti);
  37611. partIdList.push(dataPart.id);
  37612. }
  37613. this._modelRenderCache._partsDataStride = dataStrides;
  37614. this._modelRenderCache._partsUsedCategories = usedCatList;
  37615. this._modelRenderCache._partsJoinedUsedCategories = joinedUsedCatList;
  37616. this._modelRenderCache._partsClassInfo = ctiArray;
  37617. this._modelRenderCache._partIdList = partIdList;
  37618. }
  37619. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  37620. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  37621. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  37622. gii = this.renderGroup._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) { return new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache); });
  37623. // First time init of the GroupInstanceInfo
  37624. if (gii._instancesPartsData.length === 0) {
  37625. for (var j = 0; j < this._modelRenderCache._partsDataStride.length; j++) {
  37626. var stride = this._modelRenderCache._partsDataStride[j];
  37627. gii._instancesPartsData.push(new BABYLON.DynamicFloatArray(stride / 4, 50));
  37628. gii._partIndexFromId.add(this._modelRenderCache._partIdList[j].toString(), j);
  37629. for (var _a = 0, _b = this._instanceDataParts; _a < _b.length; _a++) {
  37630. var part = _b[_a];
  37631. gii._instancesPartsUsedShaderCategories[gii._partIndexFromId.get(part.id.toString())] = ";" + this.getUsedShaderCategories(part).join(";") + ";";
  37632. }
  37633. }
  37634. }
  37635. // For each instance data part of the primitive, allocate the instanced element it needs for render
  37636. for (var i = 0; i < parts.length; i++) {
  37637. var part = parts[i];
  37638. part.dataBuffer = gii._instancesPartsData[i];
  37639. part.allocElements();
  37640. }
  37641. // 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
  37642. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  37643. }
  37644. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  37645. if (setupModelRenderCache) {
  37646. this.setupModelRenderCache(this._modelRenderCache);
  37647. }
  37648. // 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.
  37649. // 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.
  37650. if (this._visibilityChanged || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  37651. // Fetch the GroupInstanceInfo if we don't already have it
  37652. if (!gii) {
  37653. gii = this.renderGroup._renderGroupInstancesInfo.get(this.modelKey);
  37654. }
  37655. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  37656. for (var _c = 0, _d = this._instanceDataParts; _c < _d.length; _c++) {
  37657. var part = _d[_c];
  37658. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  37659. if (this._visibilityChanged && !part.dataElements) {
  37660. part.allocElements();
  37661. }
  37662. InstanceClassInfo._CurCategories = gii._instancesPartsUsedShaderCategories[gii._partIndexFromId.get(part.id.toString())];
  37663. // Will return false if the instance should not be rendered (not visible or other any reasons)
  37664. if (!this.refreshInstanceDataPart(part)) {
  37665. // Free the data element
  37666. if (part.dataElements) {
  37667. part.freeElements();
  37668. }
  37669. }
  37670. }
  37671. this._instanceDirtyFlags = 0;
  37672. gii._dirtyInstancesData = true;
  37673. this._visibilityChanged = false; // Reset the flag as we've handled the case
  37674. }
  37675. };
  37676. /**
  37677. * Transform a given point using the Primitive's origin setting.
  37678. * This method requires the Primitive's actualSize to be accurate
  37679. * @param p the point to transform
  37680. * @param originOffset an offset applied on the current origin before performing the transformation. Depending on which frame of reference your data is expressed you may have to apply a offset. (if you data is expressed from the bottom/left, no offset is required. If it's expressed from the center the a [-0.5;-0.5] offset has to be applied.
  37681. * @param res an allocated Vector2 that will receive the transformed content
  37682. */
  37683. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  37684. var actualSize = this.actualSize;
  37685. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  37686. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  37687. };
  37688. RenderablePrim2D.prototype.transformPointWithOrigin = function (p, originOffset) {
  37689. var res = new BABYLON.Vector2(0, 0);
  37690. this.transformPointWithOriginByRef(p, originOffset, res);
  37691. return res;
  37692. };
  37693. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes) {
  37694. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  37695. if (!dataPart) {
  37696. return null;
  37697. }
  37698. var instancedArray = this.owner.supportInstancedArray;
  37699. var cti = dataPart.getClassTreeInfo();
  37700. var categories = this.getUsedShaderCategories(dataPart);
  37701. var att = cti.classContent.getShaderAttributes(categories);
  37702. var defines = "";
  37703. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  37704. if (instancedArray) {
  37705. defines += "#define Instanced\n";
  37706. }
  37707. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  37708. };
  37709. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  37710. get: function () {
  37711. return this._modelRenderCache;
  37712. },
  37713. enumerable: true,
  37714. configurable: true
  37715. });
  37716. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  37717. return null;
  37718. };
  37719. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  37720. };
  37721. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  37722. return null;
  37723. };
  37724. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  37725. return [];
  37726. };
  37727. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  37728. };
  37729. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  37730. };
  37731. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  37732. if (!this.isVisible) {
  37733. return false;
  37734. }
  37735. part.isVisible = this.isVisible;
  37736. // 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)
  37737. if (part.dataElementCount === 1) {
  37738. part.curElement = 0;
  37739. this.updateInstanceDataPart(part);
  37740. }
  37741. return true;
  37742. };
  37743. /**
  37744. * Update the instanceDataBase level properties of a part
  37745. * @param part the part to update
  37746. * @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.
  37747. * @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.
  37748. */
  37749. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset, customSize) {
  37750. if (positionOffset === void 0) { positionOffset = null; }
  37751. if (customSize === void 0) { customSize = null; }
  37752. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  37753. var size = this.renderGroup.viewportSize;
  37754. var zBias = this.getActualZOffset();
  37755. var offX = 0;
  37756. var offY = 0;
  37757. // If there's an offset, apply the global transformation matrix on it to get a global offset
  37758. if (positionOffset && customSize) {
  37759. offX = (positionOffset.x - (customSize.width * this.origin.x)) * t.m[0] + (positionOffset.y - (customSize.height * this.origin.y)) * t.m[4];
  37760. offY = (positionOffset.x - (customSize.width * this.origin.x)) * t.m[1] + (positionOffset.y - (customSize.height * this.origin.y)) * t.m[5];
  37761. }
  37762. // 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
  37763. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  37764. // 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.
  37765. // So for X:
  37766. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  37767. // - 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.
  37768. var w = size.width * zBias;
  37769. var h = size.height * zBias;
  37770. var invZBias = 1 / zBias;
  37771. 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));
  37772. 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));
  37773. part.transformX = tx;
  37774. part.transformY = ty;
  37775. part.origin = this.origin;
  37776. // 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)
  37777. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  37778. };
  37779. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  37780. __decorate([
  37781. BABYLON.modelLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  37782. ], RenderablePrim2D.prototype, "isTransparent", null);
  37783. RenderablePrim2D = __decorate([
  37784. BABYLON.className("RenderablePrim2D")
  37785. ], RenderablePrim2D);
  37786. return RenderablePrim2D;
  37787. })(BABYLON.Prim2DBase);
  37788. BABYLON.RenderablePrim2D = RenderablePrim2D;
  37789. })(BABYLON || (BABYLON = {}));
  37790. var BABYLON;
  37791. (function (BABYLON) {
  37792. var Shape2D = (function (_super) {
  37793. __extends(Shape2D, _super);
  37794. function Shape2D() {
  37795. _super.apply(this, arguments);
  37796. }
  37797. Object.defineProperty(Shape2D.prototype, "border", {
  37798. get: function () {
  37799. return this._border;
  37800. },
  37801. set: function (value) {
  37802. this._border = value;
  37803. this._updateTransparencyStatus();
  37804. },
  37805. enumerable: true,
  37806. configurable: true
  37807. });
  37808. Object.defineProperty(Shape2D.prototype, "fill", {
  37809. get: function () {
  37810. return this._fill;
  37811. },
  37812. set: function (value) {
  37813. this._fill = value;
  37814. this._updateTransparencyStatus();
  37815. },
  37816. enumerable: true,
  37817. configurable: true
  37818. });
  37819. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  37820. get: function () {
  37821. return this._borderThickness;
  37822. },
  37823. set: function (value) {
  37824. this._borderThickness = value;
  37825. },
  37826. enumerable: true,
  37827. configurable: true
  37828. });
  37829. Shape2D.prototype.setupShape2D = function (owner, parent, id, position, origin, isVisible, fill, border, borderThickness) {
  37830. if (borderThickness === void 0) { borderThickness = 1.0; }
  37831. this.setupRenderablePrim2D(owner, parent, id, position, origin, isVisible);
  37832. this.border = border;
  37833. this.fill = fill;
  37834. this.borderThickness = borderThickness;
  37835. };
  37836. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  37837. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  37838. // Fill Part
  37839. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  37840. var fill = this.fill;
  37841. if (fill instanceof BABYLON.SolidColorBrush2D) {
  37842. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  37843. }
  37844. if (fill instanceof BABYLON.GradientColorBrush2D) {
  37845. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  37846. }
  37847. }
  37848. // Border Part
  37849. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  37850. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  37851. var border = this.border;
  37852. if (border instanceof BABYLON.SolidColorBrush2D) {
  37853. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  37854. }
  37855. if (border instanceof BABYLON.GradientColorBrush2D) {
  37856. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  37857. }
  37858. }
  37859. return cat;
  37860. };
  37861. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  37862. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  37863. return false;
  37864. }
  37865. // Fill Part
  37866. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  37867. var d = part;
  37868. if (this.fill) {
  37869. var fill = this.fill;
  37870. if (fill instanceof BABYLON.SolidColorBrush2D) {
  37871. d.fillSolidColor = fill.color;
  37872. }
  37873. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  37874. d.fillGradientColor1 = fill.color1;
  37875. d.fillGradientColor2 = fill.color2;
  37876. 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));
  37877. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  37878. d.fillGradientTY = ty;
  37879. }
  37880. }
  37881. }
  37882. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  37883. var d = part;
  37884. if (this.border) {
  37885. d.borderThickness = this.borderThickness;
  37886. var border = this.border;
  37887. if (border instanceof BABYLON.SolidColorBrush2D) {
  37888. d.borderSolidColor = border.color;
  37889. }
  37890. else if (border instanceof BABYLON.GradientColorBrush2D) {
  37891. d.borderGradientColor1 = border.color1;
  37892. d.borderGradientColor2 = border.color2;
  37893. 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));
  37894. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  37895. d.borderGradientTY = ty;
  37896. }
  37897. }
  37898. }
  37899. return true;
  37900. };
  37901. Shape2D.prototype._updateTransparencyStatus = function () {
  37902. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent());
  37903. };
  37904. Shape2D.SHAPE2D_BORDERPARTID = 1;
  37905. Shape2D.SHAPE2D_FILLPARTID = 2;
  37906. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  37907. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  37908. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  37909. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  37910. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  37911. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  37912. __decorate([
  37913. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  37914. ], Shape2D.prototype, "border", null);
  37915. __decorate([
  37916. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  37917. ], Shape2D.prototype, "fill", null);
  37918. __decorate([
  37919. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  37920. ], Shape2D.prototype, "borderThickness", null);
  37921. Shape2D = __decorate([
  37922. BABYLON.className("Shape2D")
  37923. ], Shape2D);
  37924. return Shape2D;
  37925. })(BABYLON.RenderablePrim2D);
  37926. BABYLON.Shape2D = Shape2D;
  37927. var Shape2DInstanceData = (function (_super) {
  37928. __extends(Shape2DInstanceData, _super);
  37929. function Shape2DInstanceData() {
  37930. _super.apply(this, arguments);
  37931. }
  37932. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  37933. // FILL ATTRIBUTES
  37934. get: function () {
  37935. return null;
  37936. },
  37937. enumerable: true,
  37938. configurable: true
  37939. });
  37940. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  37941. get: function () {
  37942. return null;
  37943. },
  37944. enumerable: true,
  37945. configurable: true
  37946. });
  37947. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  37948. get: function () {
  37949. return null;
  37950. },
  37951. enumerable: true,
  37952. configurable: true
  37953. });
  37954. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  37955. get: function () {
  37956. return null;
  37957. },
  37958. enumerable: true,
  37959. configurable: true
  37960. });
  37961. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  37962. // BORDER ATTRIBUTES
  37963. get: function () {
  37964. return null;
  37965. },
  37966. enumerable: true,
  37967. configurable: true
  37968. });
  37969. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  37970. get: function () {
  37971. return null;
  37972. },
  37973. enumerable: true,
  37974. configurable: true
  37975. });
  37976. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  37977. get: function () {
  37978. return null;
  37979. },
  37980. enumerable: true,
  37981. configurable: true
  37982. });
  37983. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  37984. get: function () {
  37985. return null;
  37986. },
  37987. enumerable: true,
  37988. configurable: true
  37989. });
  37990. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  37991. get: function () {
  37992. return null;
  37993. },
  37994. enumerable: true,
  37995. configurable: true
  37996. });
  37997. __decorate([
  37998. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  37999. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  38000. __decorate([
  38001. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  38002. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  38003. __decorate([
  38004. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  38005. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  38006. __decorate([
  38007. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  38008. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  38009. __decorate([
  38010. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  38011. ], Shape2DInstanceData.prototype, "borderThickness", null);
  38012. __decorate([
  38013. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  38014. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  38015. __decorate([
  38016. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  38017. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  38018. __decorate([
  38019. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  38020. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  38021. __decorate([
  38022. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  38023. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  38024. return Shape2DInstanceData;
  38025. })(BABYLON.InstanceDataBase);
  38026. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  38027. })(BABYLON || (BABYLON = {}));
  38028. var BABYLON;
  38029. (function (BABYLON) {
  38030. var Group2D = (function (_super) {
  38031. __extends(Group2D, _super);
  38032. /**
  38033. * Don't invoke directly, rely on Group2D.CreateXXX methods
  38034. */
  38035. function Group2D() {
  38036. _super.call(this);
  38037. this._primDirtyList = new Array();
  38038. this._childrenRenderableGroups = new Array();
  38039. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  38040. }
  38041. /**
  38042. * Create an Logical or Renderable Group.
  38043. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  38044. * options:
  38045. * - id a text identifier, for information purpose
  38046. * - position: the X & Y positions relative to its parent, default is [0;0]
  38047. * - origin: define the normalized origin point location, default [0.5;0.5]
  38048. * - size: the size of the group, if null the size will be computed from its content, default is null.
  38049. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  38050. */
  38051. Group2D.CreateGroup2D = function (parent, options) {
  38052. BABYLON.Prim2DBase.CheckParent(parent);
  38053. var g = new Group2D();
  38054. g.setupGroup2D(parent.owner, parent, options && options.id || null, options && options.position || BABYLON.Vector2.Zero(), options && options.origin || null, options && options.size || null, options && options.cacheBehavior || Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY);
  38055. return g;
  38056. };
  38057. Group2D._createCachedCanvasGroup = function (owner) {
  38058. var g = new Group2D();
  38059. g.setupGroup2D(owner, null, "__cachedCanvasGroup__", BABYLON.Vector2.Zero(), null);
  38060. g.origin = BABYLON.Vector2.Zero();
  38061. return g;
  38062. };
  38063. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  38064. this._bindCacheTarget();
  38065. var uv = vertexData.uvs;
  38066. var nodeuv = this._cacheNode.UVs;
  38067. for (var i = 0; i < 4; i++) {
  38068. uv[i * 2 + 0] = nodeuv[i].x;
  38069. uv[i * 2 + 1] = nodeuv[i].y;
  38070. }
  38071. material.diffuseTexture = this._cacheTexture;
  38072. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  38073. this._cacheTexture.hasAlpha = true;
  38074. this._unbindCacheTarget();
  38075. };
  38076. /**
  38077. * Call this method to remove this Group and its children from the Canvas
  38078. */
  38079. Group2D.prototype.dispose = function () {
  38080. if (!_super.prototype.dispose.call(this)) {
  38081. return false;
  38082. }
  38083. if (this._cacheRenderSprite) {
  38084. this._cacheRenderSprite.dispose();
  38085. this._cacheRenderSprite = null;
  38086. }
  38087. if (this._cacheTexture && this._cacheNode) {
  38088. this._cacheTexture.freeRect(this._cacheNode);
  38089. this._cacheTexture = null;
  38090. this._cacheNode = null;
  38091. }
  38092. if (this._primDirtyList) {
  38093. this._primDirtyList.splice(0);
  38094. this._primDirtyList = null;
  38095. }
  38096. if (this._renderGroupInstancesInfo) {
  38097. this._renderGroupInstancesInfo.forEach(function (k, v) {
  38098. v.dispose();
  38099. });
  38100. this._renderGroupInstancesInfo = null;
  38101. }
  38102. return true;
  38103. };
  38104. Group2D.prototype.setupGroup2D = function (owner, parent, id, position, origin, size, cacheBehavior) {
  38105. if (cacheBehavior === void 0) { cacheBehavior = Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY; }
  38106. this._cacheBehavior = cacheBehavior;
  38107. this.setupPrim2DBase(owner, parent, id, position, origin);
  38108. this.size = size;
  38109. this._viewportPosition = BABYLON.Vector2.Zero();
  38110. };
  38111. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  38112. /**
  38113. * @returns Returns true if the Group render content, false if it's a logical group only
  38114. */
  38115. get: function () {
  38116. return this._isRenderableGroup;
  38117. },
  38118. enumerable: true,
  38119. configurable: true
  38120. });
  38121. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  38122. /**
  38123. * @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
  38124. */
  38125. get: function () {
  38126. return this._isCachedGroup;
  38127. },
  38128. enumerable: true,
  38129. configurable: true
  38130. });
  38131. Object.defineProperty(Group2D.prototype, "size", {
  38132. get: function () {
  38133. return this._size;
  38134. },
  38135. /**
  38136. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  38137. * 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.
  38138. */
  38139. set: function (val) {
  38140. this._size = val;
  38141. },
  38142. enumerable: true,
  38143. configurable: true
  38144. });
  38145. Object.defineProperty(Group2D.prototype, "viewportSize", {
  38146. get: function () {
  38147. return this._viewportSize;
  38148. },
  38149. enumerable: true,
  38150. configurable: true
  38151. });
  38152. Object.defineProperty(Group2D.prototype, "actualSize", {
  38153. get: function () {
  38154. // The computed size will be floor on both width and height
  38155. var actualSize;
  38156. // Return the size if set by the user
  38157. if (this._size) {
  38158. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  38159. }
  38160. else {
  38161. var m = this.boundingInfo.max();
  38162. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  38163. }
  38164. // 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)
  38165. if (!actualSize.equals(this._actualSize)) {
  38166. this._instanceDirtyFlags |= Group2D.actualSizeProperty.flagId;
  38167. this._actualSize = actualSize;
  38168. this.handleGroupChanged(Group2D.actualSizeProperty);
  38169. }
  38170. return actualSize;
  38171. },
  38172. enumerable: true,
  38173. configurable: true
  38174. });
  38175. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  38176. /**
  38177. * 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.
  38178. * 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.
  38179. */
  38180. get: function () {
  38181. return this._cacheBehavior;
  38182. },
  38183. enumerable: true,
  38184. configurable: true
  38185. });
  38186. Group2D.prototype._addPrimToDirtyList = function (prim) {
  38187. this._primDirtyList.push(prim);
  38188. };
  38189. Group2D.prototype._renderCachedCanvas = function (context) {
  38190. this.updateGlobalTransVis(true);
  38191. this._prepareGroupRender(context);
  38192. this._groupRender(context);
  38193. };
  38194. Group2D.prototype.levelIntersect = function (intersectInfo) {
  38195. // 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
  38196. return true;
  38197. };
  38198. Group2D.prototype.updateLevelBoundingInfo = function () {
  38199. var size;
  38200. // If the size is set by the user, the boundingInfo is computed from this value
  38201. if (this.size) {
  38202. size = this.size;
  38203. }
  38204. else {
  38205. size = new BABYLON.Size(0, 0);
  38206. }
  38207. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  38208. };
  38209. // Method called only on renderable groups to prepare the rendering
  38210. Group2D.prototype._prepareGroupRender = function (context) {
  38211. var sortedDirtyList = null;
  38212. // Update the Global Transformation and visibility status of the changed primitives
  38213. if ((this._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  38214. sortedDirtyList = this._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  38215. this.updateGlobalTransVisOf(sortedDirtyList, true);
  38216. }
  38217. // Setup the size of the rendering viewport
  38218. // 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
  38219. if (!this._isCachedGroup) {
  38220. // Compute the WebGL viewport's location/size
  38221. var t = this._globalTransform.getTranslation();
  38222. var s = this.actualSize.clone();
  38223. var rs = this.owner._renderingSize;
  38224. s.height = Math.min(s.height, rs.height - t.y);
  38225. s.width = Math.min(s.width, rs.width - t.x);
  38226. var x = t.x;
  38227. var y = t.y;
  38228. // 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
  38229. this._viewportPosition.x = x;
  38230. this._viewportPosition.y = y;
  38231. var vw = s.width;
  38232. var vh = s.height;
  38233. if (!this._viewportSize) {
  38234. this._viewportSize = new BABYLON.Size(vw, vh);
  38235. }
  38236. else {
  38237. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  38238. context.forceRefreshPrimitive = true;
  38239. }
  38240. this._viewportSize.width = vw;
  38241. this._viewportSize.height = vh;
  38242. }
  38243. }
  38244. else {
  38245. var newSize = this.actualSize.clone();
  38246. if (!newSize.equals(this._viewportSize)) {
  38247. context.forceRefreshPrimitive = true;
  38248. }
  38249. this._viewportSize = newSize;
  38250. }
  38251. if ((this._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  38252. // If the group is cached, set the dirty flag to true because of the incoming changes
  38253. this._cacheGroupDirty = this._isCachedGroup;
  38254. // If it's a force refresh, prepare all the children
  38255. if (context.forceRefreshPrimitive) {
  38256. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  38257. var p = _a[_i];
  38258. p._prepareRender(context);
  38259. }
  38260. }
  38261. else {
  38262. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  38263. // the hierarchyDepth in order to prepare primitives from top to bottom
  38264. if (!sortedDirtyList) {
  38265. sortedDirtyList = this._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  38266. }
  38267. sortedDirtyList.forEach(function (p) {
  38268. // 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.
  38269. // 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.
  38270. if (!p.isDisposed && p._needPrepare()) {
  38271. p._prepareRender(context);
  38272. }
  38273. });
  38274. // Everything is updated, clear the dirty list
  38275. this._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  38276. this._primDirtyList.splice(0);
  38277. }
  38278. }
  38279. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  38280. this._childrenRenderableGroups.forEach(function (g) {
  38281. g._prepareGroupRender(context);
  38282. });
  38283. };
  38284. Group2D.prototype._groupRender = function (context) {
  38285. var _this = this;
  38286. var engine = this.owner.engine;
  38287. var failedCount = 0;
  38288. // First recurse to children render group to render them (in their cache or on screen)
  38289. for (var _i = 0, _a = this._childrenRenderableGroups; _i < _a.length; _i++) {
  38290. var childGroup = _a[_i];
  38291. childGroup._groupRender(context);
  38292. }
  38293. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  38294. if (!this.isCachedGroup || this._cacheGroupDirty) {
  38295. if (this.isCachedGroup) {
  38296. this._bindCacheTarget();
  38297. }
  38298. else {
  38299. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  38300. }
  38301. // For each different model of primitive to render
  38302. var totalRenderCount = 0;
  38303. this._renderGroupInstancesInfo.forEach(function (k, v) {
  38304. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  38305. // Skip it if instanced arrays are not supported
  38306. if (_this.owner.supportInstancedArray) {
  38307. for (var i = 0; i < v._instancesPartsData.length; i++) {
  38308. // If the instances of the model was changed, pack the data
  38309. var array = v._instancesPartsData[i];
  38310. var instanceData_1 = array.pack();
  38311. totalRenderCount += array.usedElementCount;
  38312. // Compute the size the instance buffer should have
  38313. var neededSize = array.usedElementCount * array.stride * 4;
  38314. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  38315. if (!v._instancesPartsBuffer[i] || (v._instancesPartsBufferSize[i] < neededSize)) {
  38316. if (v._instancesPartsBuffer[i]) {
  38317. engine.deleteInstancesBuffer(v._instancesPartsBuffer[i]);
  38318. }
  38319. v._instancesPartsBuffer[i] = engine.createInstancesBuffer(neededSize);
  38320. v._instancesPartsBufferSize[i] = neededSize;
  38321. v._dirtyInstancesData = false;
  38322. // Update the WebGL buffer to match the new content of the instances data
  38323. engine._gl.bufferSubData(engine._gl.ARRAY_BUFFER, 0, instanceData_1);
  38324. }
  38325. else if (v._dirtyInstancesData) {
  38326. // Update the WebGL buffer to match the new content of the instances data
  38327. engine._gl.bindBuffer(engine._gl.ARRAY_BUFFER, v._instancesPartsBuffer[i]);
  38328. engine._gl.bufferSubData(engine._gl.ARRAY_BUFFER, 0, instanceData_1);
  38329. }
  38330. }
  38331. v._dirtyInstancesData = false;
  38332. }
  38333. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  38334. if (!_this.owner.supportInstancedArray || totalRenderCount > 0) {
  38335. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  38336. var renderFailed = !v._modelCache.render(v, context);
  38337. // Update dirty flag/related
  38338. v._dirtyInstancesData = renderFailed;
  38339. failedCount += renderFailed ? 1 : 0;
  38340. }
  38341. });
  38342. // The group's content is no longer dirty
  38343. this._cacheGroupDirty = failedCount !== 0;
  38344. if (this.isCachedGroup) {
  38345. this._unbindCacheTarget();
  38346. }
  38347. else {
  38348. if (curVP) {
  38349. engine.setViewport(curVP);
  38350. }
  38351. }
  38352. }
  38353. };
  38354. Group2D.prototype._bindCacheTarget = function () {
  38355. var curWidth;
  38356. var curHeight;
  38357. if (this._cacheNode) {
  38358. var size = this._cacheNode.contentSize;
  38359. var groupWidth = Math.ceil(this.actualSize.width);
  38360. var groupHeight = Math.ceil(this.actualSize.height);
  38361. if ((size.width < groupWidth) || (size.height < groupHeight)) {
  38362. curWidth = Math.floor(size.width * 1.07); // Grow 5% more to avoid frequent resizing for few pixels...
  38363. curHeight = Math.floor(size.height * 1.07);
  38364. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  38365. this._cacheTexture.freeRect(this._cacheNode);
  38366. this._cacheNode = null;
  38367. }
  38368. }
  38369. if (!this._cacheNode) {
  38370. // Check if we have to allocate a rendering zone in the global cache texture
  38371. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null);
  38372. this._cacheNode = res.node;
  38373. this._cacheTexture = res.texture;
  38374. this._cacheRenderSprite = res.sprite;
  38375. var size = this._cacheNode.contentSize;
  38376. }
  38377. var n = this._cacheNode;
  38378. this._cacheTexture.bindTextureForPosSize(n.pos, this.actualSize, true);
  38379. };
  38380. Group2D.prototype._unbindCacheTarget = function () {
  38381. if (this._cacheTexture) {
  38382. this._cacheTexture.unbindTexture();
  38383. }
  38384. };
  38385. Group2D.prototype.handleGroupChanged = function (prop) {
  38386. // This method is only for cachedGroup
  38387. if (!this.isCachedGroup || !this._cacheRenderSprite) {
  38388. return;
  38389. }
  38390. // For now we only support these property changes
  38391. // TODO: add more! :)
  38392. if (prop.id === BABYLON.Prim2DBase.positionProperty.id) {
  38393. this._cacheRenderSprite.position = this.position.clone();
  38394. }
  38395. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  38396. this._cacheRenderSprite.rotation = this.rotation;
  38397. }
  38398. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  38399. this._cacheRenderSprite.scale = this.scale;
  38400. }
  38401. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  38402. this._cacheRenderSprite.origin = this.origin.clone();
  38403. }
  38404. else if (prop.id === Group2D.actualSizeProperty.id) {
  38405. this._cacheRenderSprite.spriteSize = this.actualSize.clone();
  38406. }
  38407. };
  38408. Group2D.prototype.detectGroupStates = function () {
  38409. var isCanvas = this instanceof BABYLON.Canvas2D;
  38410. var canvasStrat = this.owner.cachingStrategy;
  38411. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  38412. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  38413. this._isRenderableGroup = isCanvas;
  38414. this._isCachedGroup = false;
  38415. }
  38416. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  38417. if (isCanvas) {
  38418. this._isRenderableGroup = true;
  38419. this._isCachedGroup = true;
  38420. }
  38421. else {
  38422. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  38423. this._isCachedGroup = false;
  38424. }
  38425. }
  38426. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  38427. if (isCanvas) {
  38428. this._isRenderableGroup = true;
  38429. this._isCachedGroup = false;
  38430. }
  38431. else {
  38432. if (this.hierarchyDepth === 1) {
  38433. this._isRenderableGroup = true;
  38434. this._isCachedGroup = true;
  38435. }
  38436. else {
  38437. this._isRenderableGroup = false;
  38438. this._isCachedGroup = false;
  38439. }
  38440. }
  38441. }
  38442. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  38443. var gcb = this.cacheBehavior;
  38444. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  38445. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  38446. this._isCachedGroup = false;
  38447. }
  38448. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  38449. this._isRenderableGroup = true;
  38450. this._isCachedGroup = true;
  38451. }
  38452. }
  38453. // If the group is tagged as renderable we add it to the renderable tree
  38454. if (this._isCachedGroup) {
  38455. var cur = this.parent;
  38456. while (cur) {
  38457. if (cur instanceof Group2D && cur._isRenderableGroup) {
  38458. cur._childrenRenderableGroups.push(this);
  38459. break;
  38460. }
  38461. cur = cur.parent;
  38462. }
  38463. }
  38464. };
  38465. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  38466. /**
  38467. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  38468. */
  38469. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  38470. /**
  38471. * When used, this group's content won't be cached, no matter which strategy used.
  38472. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  38473. */
  38474. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  38475. /**
  38476. * When used, the group's content will be cached in the nearest cached parent group/canvas
  38477. */
  38478. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  38479. __decorate([
  38480. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  38481. ], Group2D.prototype, "size", null);
  38482. __decorate([
  38483. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  38484. ], Group2D.prototype, "actualSize", null);
  38485. Group2D = __decorate([
  38486. BABYLON.className("Group2D")
  38487. ], Group2D);
  38488. return Group2D;
  38489. })(BABYLON.Prim2DBase);
  38490. BABYLON.Group2D = Group2D;
  38491. })(BABYLON || (BABYLON = {}));
  38492. var BABYLON;
  38493. (function (BABYLON) {
  38494. var Rectangle2DRenderCache = (function (_super) {
  38495. __extends(Rectangle2DRenderCache, _super);
  38496. function Rectangle2DRenderCache(engine, modelKey, isTransparent) {
  38497. _super.call(this, engine, modelKey, isTransparent);
  38498. }
  38499. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  38500. // Do nothing if the shader is still loading/preparing
  38501. if ((this.effectFill && !this.effectFill.isReady()) || (this.effectBorder && !this.effectBorder.isReady())) {
  38502. return false;
  38503. }
  38504. var engine = instanceInfo._owner.owner.engine;
  38505. var depthFunction = 0;
  38506. if (this.effectFill && this.effectBorder) {
  38507. depthFunction = engine.getDepthFunction();
  38508. engine.setDepthFunctionToLessOrEqual();
  38509. }
  38510. var cur;
  38511. if (this.isTransparent) {
  38512. cur = engine.getAlphaMode();
  38513. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38514. }
  38515. if (this.effectFill) {
  38516. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  38517. engine.enableEffect(this.effectFill);
  38518. engine.bindBuffers(this.fillVB, this.fillIB, [1], 4, this.effectFill);
  38519. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  38520. if (instanceInfo._owner.owner.supportInstancedArray) {
  38521. if (!this.instancingFillAttributes) {
  38522. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  38523. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, this.effectFill);
  38524. }
  38525. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingFillAttributes);
  38526. engine.draw(true, 0, this.fillIndicesCount, count);
  38527. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingFillAttributes);
  38528. }
  38529. else {
  38530. for (var i = 0; i < count; i++) {
  38531. this.setupUniforms(this.effectFill, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  38532. engine.draw(true, 0, this.fillIndicesCount);
  38533. }
  38534. }
  38535. }
  38536. if (this.effectBorder) {
  38537. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  38538. engine.enableEffect(this.effectBorder);
  38539. engine.bindBuffers(this.borderVB, this.borderIB, [1], 4, this.effectBorder);
  38540. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  38541. if (instanceInfo._owner.owner.supportInstancedArray) {
  38542. if (!this.instancingBorderAttributes) {
  38543. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, this.effectBorder);
  38544. }
  38545. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingBorderAttributes);
  38546. engine.draw(true, 0, this.borderIndicesCount, count);
  38547. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingBorderAttributes);
  38548. }
  38549. else {
  38550. for (var i = 0; i < count; i++) {
  38551. this.setupUniforms(this.effectBorder, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  38552. engine.draw(true, 0, this.borderIndicesCount);
  38553. }
  38554. }
  38555. }
  38556. if (this.isTransparent) {
  38557. engine.setAlphaMode(cur);
  38558. }
  38559. if (this.effectFill && this.effectBorder) {
  38560. engine.setDepthFunction(depthFunction);
  38561. }
  38562. return true;
  38563. };
  38564. Rectangle2DRenderCache.prototype.dispose = function () {
  38565. if (!_super.prototype.dispose.call(this)) {
  38566. return false;
  38567. }
  38568. if (this.fillVB) {
  38569. this._engine._releaseBuffer(this.fillVB);
  38570. this.fillVB = null;
  38571. }
  38572. if (this.fillIB) {
  38573. this._engine._releaseBuffer(this.fillIB);
  38574. this.fillIB = null;
  38575. }
  38576. if (this.effectFill) {
  38577. this._engine._releaseEffect(this.effectFill);
  38578. this.effectFill = null;
  38579. }
  38580. if (this.borderVB) {
  38581. this._engine._releaseBuffer(this.borderVB);
  38582. this.borderVB = null;
  38583. }
  38584. if (this.borderIB) {
  38585. this._engine._releaseBuffer(this.borderIB);
  38586. this.borderIB = null;
  38587. }
  38588. if (this.effectBorder) {
  38589. this._engine._releaseEffect(this.effectBorder);
  38590. this.effectBorder = null;
  38591. }
  38592. return true;
  38593. };
  38594. return Rectangle2DRenderCache;
  38595. })(BABYLON.ModelRenderCache);
  38596. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  38597. var Rectangle2DInstanceData = (function (_super) {
  38598. __extends(Rectangle2DInstanceData, _super);
  38599. function Rectangle2DInstanceData(partId) {
  38600. _super.call(this, partId, 1);
  38601. }
  38602. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  38603. get: function () {
  38604. return null;
  38605. },
  38606. enumerable: true,
  38607. configurable: true
  38608. });
  38609. __decorate([
  38610. BABYLON.instanceData()
  38611. ], Rectangle2DInstanceData.prototype, "properties", null);
  38612. return Rectangle2DInstanceData;
  38613. })(BABYLON.Shape2DInstanceData);
  38614. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  38615. var Rectangle2D = (function (_super) {
  38616. __extends(Rectangle2D, _super);
  38617. function Rectangle2D() {
  38618. _super.apply(this, arguments);
  38619. }
  38620. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  38621. get: function () {
  38622. return this.size;
  38623. },
  38624. enumerable: true,
  38625. configurable: true
  38626. });
  38627. Object.defineProperty(Rectangle2D.prototype, "size", {
  38628. get: function () {
  38629. return this._size;
  38630. },
  38631. set: function (value) {
  38632. this._size = value;
  38633. },
  38634. enumerable: true,
  38635. configurable: true
  38636. });
  38637. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  38638. get: function () {
  38639. return this._notRounded;
  38640. },
  38641. set: function (value) {
  38642. this._notRounded = value;
  38643. },
  38644. enumerable: true,
  38645. configurable: true
  38646. });
  38647. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  38648. get: function () {
  38649. return this._roundRadius;
  38650. },
  38651. set: function (value) {
  38652. this._roundRadius = value;
  38653. this.notRounded = value === 0;
  38654. },
  38655. enumerable: true,
  38656. configurable: true
  38657. });
  38658. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  38659. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  38660. if (this.notRounded) {
  38661. return true;
  38662. }
  38663. // Well, for now we neglect the area where the pickPosition could be outside due to the roundRadius...
  38664. // TODO make REAL intersection test here!
  38665. return true;
  38666. };
  38667. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  38668. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo, this.origin);
  38669. };
  38670. Rectangle2D.prototype.setupRectangle2D = function (owner, parent, id, position, origin, size, roundRadius, fill, border, borderThickness) {
  38671. if (roundRadius === void 0) { roundRadius = 0; }
  38672. if (borderThickness === void 0) { borderThickness = 1; }
  38673. this.setupShape2D(owner, parent, id, position, origin, true, fill, border, borderThickness);
  38674. this.size = size;
  38675. this.notRounded = !roundRadius;
  38676. this.roundRadius = roundRadius;
  38677. };
  38678. /**
  38679. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  38680. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  38681. * options:
  38682. * - id a text identifier, for information purpose
  38683. * - x: the X position relative to its parent, default is 0
  38684. * - y: the Y position relative to its parent, default is 0
  38685. * - origin: define the normalized origin point location, default [0.5;0.5]
  38686. * - width: the width of the rectangle, default is 10
  38687. * - height: the height of the rectangle, default is 10
  38688. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp rectangle).
  38689. * - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white.
  38690. * - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null.
  38691. * - borderThickness: the thickness of the drawn border, default is 1.
  38692. */
  38693. Rectangle2D.Create = function (parent, options) {
  38694. BABYLON.Prim2DBase.CheckParent(parent);
  38695. var rect = new Rectangle2D();
  38696. rect.setupRectangle2D(parent.owner, parent, options && options.id || null, new BABYLON.Vector2(options && options.x || 0, options && options.y || 0), options && options.origin || null, new BABYLON.Size(options && options.width || 10, options && options.height || 10), options && options.roundRadius || 0);
  38697. if (options && options.fill !== undefined) {
  38698. rect.fill = options.fill;
  38699. }
  38700. else {
  38701. rect.fill = BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF");
  38702. }
  38703. rect.border = options && options.border || null;
  38704. rect.borderThickness = options && options.borderThickness || 1;
  38705. return rect;
  38706. };
  38707. Rectangle2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  38708. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey, isTransparent);
  38709. return renderCache;
  38710. };
  38711. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  38712. var renderCache = modelRenderCache;
  38713. var engine = this.owner.engine;
  38714. // Need to create WebGL resources for fill part?
  38715. if (this.fill) {
  38716. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  38717. var vb = new Float32Array(vbSize);
  38718. for (var i = 0; i < vbSize; i++) {
  38719. vb[i] = i;
  38720. }
  38721. renderCache.fillVB = engine.createVertexBuffer(vb);
  38722. var triCount = vbSize - 1;
  38723. var ib = new Float32Array(triCount * 3);
  38724. for (var i = 0; i < triCount; i++) {
  38725. ib[i * 3 + 0] = 0;
  38726. ib[i * 3 + 2] = i + 1;
  38727. ib[i * 3 + 1] = i + 2;
  38728. }
  38729. ib[triCount * 3 - 2] = 1;
  38730. renderCache.fillIB = engine.createIndexBuffer(ib);
  38731. renderCache.fillIndicesCount = triCount * 3;
  38732. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"]);
  38733. renderCache.effectFill = engine.createEffect({ vertex: "rect2d", fragment: "rect2d" }, ei.attributes, ei.uniforms, [], ei.defines, null, function (e) {
  38734. // renderCache.setupUniformsLocation(e, ei.uniforms, Shape2D.SHAPE2D_FILLPARTID);
  38735. });
  38736. }
  38737. // Need to create WebGL resource for border part?
  38738. if (this.border) {
  38739. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  38740. var vb = new Float32Array(vbSize);
  38741. for (var i = 0; i < vbSize; i++) {
  38742. vb[i] = i;
  38743. }
  38744. renderCache.borderVB = engine.createVertexBuffer(vb);
  38745. var triCount = vbSize;
  38746. var rs = triCount / 2;
  38747. var ib = new Float32Array(triCount * 3);
  38748. for (var i = 0; i < rs; i++) {
  38749. var r0 = i;
  38750. var r1 = (i + 1) % rs;
  38751. ib[i * 6 + 0] = rs + r1;
  38752. ib[i * 6 + 1] = rs + r0;
  38753. ib[i * 6 + 2] = r0;
  38754. ib[i * 6 + 3] = r1;
  38755. ib[i * 6 + 4] = rs + r1;
  38756. ib[i * 6 + 5] = r0;
  38757. }
  38758. renderCache.borderIB = engine.createIndexBuffer(ib);
  38759. renderCache.borderIndicesCount = triCount * 3;
  38760. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"]);
  38761. renderCache.effectBorder = engine.createEffect({ vertex: "rect2d", fragment: "rect2d" }, ei.attributes, ei.uniforms, [], ei.defines, null, function (e) {
  38762. // renderCache.setupUniformsLocation(e, ei.uniforms, Shape2D.SHAPE2D_BORDERPARTID);
  38763. });
  38764. }
  38765. return renderCache;
  38766. };
  38767. Rectangle2D.prototype.createInstanceDataParts = function () {
  38768. var res = new Array();
  38769. if (this.border) {
  38770. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  38771. }
  38772. if (this.fill) {
  38773. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  38774. }
  38775. return res;
  38776. };
  38777. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  38778. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  38779. return false;
  38780. }
  38781. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  38782. var d = part;
  38783. var size = this.size;
  38784. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  38785. }
  38786. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  38787. var d = part;
  38788. var size = this.size;
  38789. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  38790. }
  38791. return true;
  38792. };
  38793. Rectangle2D.roundSubdivisions = 16;
  38794. __decorate([
  38795. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.sizeProperty = pi; }, false, true)
  38796. ], Rectangle2D.prototype, "size", null);
  38797. __decorate([
  38798. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  38799. ], Rectangle2D.prototype, "notRounded", null);
  38800. __decorate([
  38801. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  38802. ], Rectangle2D.prototype, "roundRadius", null);
  38803. Rectangle2D = __decorate([
  38804. BABYLON.className("Rectangle2D")
  38805. ], Rectangle2D);
  38806. return Rectangle2D;
  38807. })(BABYLON.Shape2D);
  38808. BABYLON.Rectangle2D = Rectangle2D;
  38809. })(BABYLON || (BABYLON = {}));
  38810. var BABYLON;
  38811. (function (BABYLON) {
  38812. var Ellipse2DRenderCache = (function (_super) {
  38813. __extends(Ellipse2DRenderCache, _super);
  38814. function Ellipse2DRenderCache(engine, modelKey, isTransparent) {
  38815. _super.call(this, engine, modelKey, isTransparent);
  38816. }
  38817. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  38818. // Do nothing if the shader is still loading/preparing
  38819. if ((this.effectFill && !this.effectFill.isReady()) || (this.effectBorder && !this.effectBorder.isReady())) {
  38820. return false;
  38821. }
  38822. var engine = instanceInfo._owner.owner.engine;
  38823. var depthFunction = 0;
  38824. if (this.effectFill && this.effectBorder) {
  38825. depthFunction = engine.getDepthFunction();
  38826. engine.setDepthFunctionToLessOrEqual();
  38827. }
  38828. var cur;
  38829. if (this.isTransparent) {
  38830. cur = engine.getAlphaMode();
  38831. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38832. }
  38833. if (this.effectFill) {
  38834. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  38835. engine.enableEffect(this.effectFill);
  38836. engine.bindBuffers(this.fillVB, this.fillIB, [1], 4, this.effectFill);
  38837. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  38838. if (instanceInfo._owner.owner.supportInstancedArray) {
  38839. if (!this.instancingFillAttributes) {
  38840. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  38841. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, this.effectFill);
  38842. }
  38843. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingFillAttributes);
  38844. engine.draw(true, 0, this.fillIndicesCount, count);
  38845. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingFillAttributes);
  38846. }
  38847. else {
  38848. for (var i = 0; i < count; i++) {
  38849. this.setupUniforms(this.effectFill, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  38850. engine.draw(true, 0, this.fillIndicesCount);
  38851. }
  38852. }
  38853. }
  38854. if (this.effectBorder) {
  38855. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  38856. engine.enableEffect(this.effectBorder);
  38857. engine.bindBuffers(this.borderVB, this.borderIB, [1], 4, this.effectBorder);
  38858. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  38859. if (instanceInfo._owner.owner.supportInstancedArray) {
  38860. if (!this.instancingBorderAttributes) {
  38861. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, this.effectBorder);
  38862. }
  38863. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingBorderAttributes);
  38864. engine.draw(true, 0, this.borderIndicesCount, count);
  38865. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingBorderAttributes);
  38866. }
  38867. else {
  38868. for (var i = 0; i < count; i++) {
  38869. this.setupUniforms(this.effectBorder, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  38870. engine.draw(true, 0, this.borderIndicesCount);
  38871. }
  38872. }
  38873. }
  38874. if (this.isTransparent) {
  38875. engine.setAlphaMode(cur);
  38876. }
  38877. if (this.effectFill && this.effectBorder) {
  38878. engine.setDepthFunction(depthFunction);
  38879. }
  38880. return true;
  38881. };
  38882. Ellipse2DRenderCache.prototype.dispose = function () {
  38883. if (!_super.prototype.dispose.call(this)) {
  38884. return false;
  38885. }
  38886. if (this.fillVB) {
  38887. this._engine._releaseBuffer(this.fillVB);
  38888. this.fillVB = null;
  38889. }
  38890. if (this.fillIB) {
  38891. this._engine._releaseBuffer(this.fillIB);
  38892. this.fillIB = null;
  38893. }
  38894. if (this.effectFill) {
  38895. this._engine._releaseEffect(this.effectFill);
  38896. this.effectFill = null;
  38897. }
  38898. if (this.borderVB) {
  38899. this._engine._releaseBuffer(this.borderVB);
  38900. this.borderVB = null;
  38901. }
  38902. if (this.borderIB) {
  38903. this._engine._releaseBuffer(this.borderIB);
  38904. this.borderIB = null;
  38905. }
  38906. if (this.effectBorder) {
  38907. this._engine._releaseEffect(this.effectBorder);
  38908. this.effectBorder = null;
  38909. }
  38910. return true;
  38911. };
  38912. return Ellipse2DRenderCache;
  38913. })(BABYLON.ModelRenderCache);
  38914. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  38915. var Ellipse2DInstanceData = (function (_super) {
  38916. __extends(Ellipse2DInstanceData, _super);
  38917. function Ellipse2DInstanceData(partId) {
  38918. _super.call(this, partId, 1);
  38919. }
  38920. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  38921. get: function () {
  38922. return null;
  38923. },
  38924. enumerable: true,
  38925. configurable: true
  38926. });
  38927. __decorate([
  38928. BABYLON.instanceData()
  38929. ], Ellipse2DInstanceData.prototype, "properties", null);
  38930. return Ellipse2DInstanceData;
  38931. })(BABYLON.Shape2DInstanceData);
  38932. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  38933. var Ellipse2D = (function (_super) {
  38934. __extends(Ellipse2D, _super);
  38935. function Ellipse2D() {
  38936. _super.apply(this, arguments);
  38937. }
  38938. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  38939. get: function () {
  38940. return this.size;
  38941. },
  38942. enumerable: true,
  38943. configurable: true
  38944. });
  38945. Object.defineProperty(Ellipse2D.prototype, "size", {
  38946. get: function () {
  38947. return this._size;
  38948. },
  38949. set: function (value) {
  38950. this._size = value;
  38951. },
  38952. enumerable: true,
  38953. configurable: true
  38954. });
  38955. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  38956. get: function () {
  38957. return this._subdivisions;
  38958. },
  38959. set: function (value) {
  38960. this._subdivisions = value;
  38961. },
  38962. enumerable: true,
  38963. configurable: true
  38964. });
  38965. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  38966. var x = intersectInfo._localPickPosition.x;
  38967. var y = intersectInfo._localPickPosition.y;
  38968. var w = this.size.width / 2;
  38969. var h = this.size.height / 2;
  38970. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  38971. };
  38972. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  38973. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo, this.origin);
  38974. };
  38975. Ellipse2D.prototype.setupEllipse2D = function (owner, parent, id, position, origin, size, subdivisions, fill, border, borderThickness) {
  38976. if (subdivisions === void 0) { subdivisions = 64; }
  38977. if (borderThickness === void 0) { borderThickness = 1; }
  38978. this.setupShape2D(owner, parent, id, position, origin, true, fill, border, borderThickness);
  38979. this.size = size;
  38980. this.subdivisions = subdivisions;
  38981. };
  38982. /**
  38983. * Create an Ellipse 2D Shape primitive
  38984. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  38985. * options:
  38986. * - id: a text identifier, for information purpose
  38987. * - x: the X position relative to its parent, default is 0
  38988. * - y: the Y position relative to its parent, default is 0
  38989. * - origin: define the normalized origin point location, default [0.5;0.5]
  38990. * - width: the width of the ellipse, default is 10
  38991. * - height: the height of the ellipse, default is 10
  38992. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  38993. * - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white.
  38994. * - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null.
  38995. * - borderThickness: the thickness of the drawn border, default is 1.
  38996. */
  38997. Ellipse2D.Create = function (parent, options) {
  38998. BABYLON.Prim2DBase.CheckParent(parent);
  38999. var fill;
  39000. if (options && options.fill !== undefined) {
  39001. fill = options.fill;
  39002. }
  39003. else {
  39004. fill = BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF");
  39005. }
  39006. var ellipse = new Ellipse2D();
  39007. ellipse.setupEllipse2D(parent.owner, parent, options && options.id || null, new BABYLON.Vector2(options && options.x || 0, options && options.y || 0), options && options.origin || null, new BABYLON.Size(options && options.width || 10, options && options.height || 10), options && options.subdivisions || 64, fill, options && options.border || null, options && options.borderThickness || 1);
  39008. return ellipse;
  39009. };
  39010. Ellipse2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  39011. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey, isTransparent);
  39012. return renderCache;
  39013. };
  39014. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  39015. var renderCache = modelRenderCache;
  39016. var engine = this.owner.engine;
  39017. // Need to create WebGL resources for fill part?
  39018. if (this.fill) {
  39019. var vbSize = this.subdivisions + 1;
  39020. var vb = new Float32Array(vbSize);
  39021. for (var i = 0; i < vbSize; i++) {
  39022. vb[i] = i;
  39023. }
  39024. renderCache.fillVB = engine.createVertexBuffer(vb);
  39025. var triCount = vbSize - 1;
  39026. var ib = new Float32Array(triCount * 3);
  39027. for (var i = 0; i < triCount; i++) {
  39028. ib[i * 3 + 0] = 0;
  39029. ib[i * 3 + 2] = i + 1;
  39030. ib[i * 3 + 1] = i + 2;
  39031. }
  39032. ib[triCount * 3 - 2] = 1;
  39033. renderCache.fillIB = engine.createIndexBuffer(ib);
  39034. renderCache.fillIndicesCount = triCount * 3;
  39035. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"]);
  39036. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  39037. }
  39038. // Need to create WebGL resource for border part?
  39039. if (this.border) {
  39040. var vbSize = this.subdivisions * 2;
  39041. var vb = new Float32Array(vbSize);
  39042. for (var i = 0; i < vbSize; i++) {
  39043. vb[i] = i;
  39044. }
  39045. renderCache.borderVB = engine.createVertexBuffer(vb);
  39046. var triCount = vbSize;
  39047. var rs = triCount / 2;
  39048. var ib = new Float32Array(triCount * 3);
  39049. for (var i = 0; i < rs; i++) {
  39050. var r0 = i;
  39051. var r1 = (i + 1) % rs;
  39052. ib[i * 6 + 0] = rs + r1;
  39053. ib[i * 6 + 1] = rs + r0;
  39054. ib[i * 6 + 2] = r0;
  39055. ib[i * 6 + 3] = r1;
  39056. ib[i * 6 + 4] = rs + r1;
  39057. ib[i * 6 + 5] = r0;
  39058. }
  39059. renderCache.borderIB = engine.createIndexBuffer(ib);
  39060. renderCache.borderIndicesCount = (triCount * 3);
  39061. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"]);
  39062. renderCache.effectBorder = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  39063. }
  39064. return renderCache;
  39065. };
  39066. Ellipse2D.prototype.createInstanceDataParts = function () {
  39067. var res = new Array();
  39068. if (this.border) {
  39069. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  39070. }
  39071. if (this.fill) {
  39072. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  39073. }
  39074. return res;
  39075. };
  39076. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  39077. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  39078. return false;
  39079. }
  39080. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  39081. var d = part;
  39082. var size = this.size;
  39083. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  39084. }
  39085. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  39086. var d = part;
  39087. var size = this.size;
  39088. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  39089. }
  39090. return true;
  39091. };
  39092. __decorate([
  39093. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.sizeProperty = pi; }, false, true)
  39094. ], Ellipse2D.prototype, "size", null);
  39095. __decorate([
  39096. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  39097. ], Ellipse2D.prototype, "subdivisions", null);
  39098. Ellipse2D = __decorate([
  39099. BABYLON.className("Ellipse2D")
  39100. ], Ellipse2D);
  39101. return Ellipse2D;
  39102. })(BABYLON.Shape2D);
  39103. BABYLON.Ellipse2D = Ellipse2D;
  39104. })(BABYLON || (BABYLON = {}));
  39105. var BABYLON;
  39106. (function (BABYLON) {
  39107. var Sprite2DRenderCache = (function (_super) {
  39108. __extends(Sprite2DRenderCache, _super);
  39109. function Sprite2DRenderCache() {
  39110. _super.apply(this, arguments);
  39111. }
  39112. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  39113. // Do nothing if the shader is still loading/preparing
  39114. if (!this.effect.isReady() || !this.texture.isReady()) {
  39115. return false;
  39116. }
  39117. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  39118. var engine = instanceInfo._owner.owner.engine;
  39119. engine.enableEffect(this.effect);
  39120. this.effect.setTexture("diffuseSampler", this.texture);
  39121. engine.bindBuffers(this.vb, this.ib, [1], 4, this.effect);
  39122. var cur = engine.getAlphaMode();
  39123. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39124. var count = instanceInfo._instancesPartsData[0].usedElementCount;
  39125. if (instanceInfo._owner.owner.supportInstancedArray) {
  39126. if (!this.instancingAttributes) {
  39127. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, this.effect);
  39128. }
  39129. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], null, this.instancingAttributes);
  39130. engine.draw(true, 0, 6, count);
  39131. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], this.instancingAttributes);
  39132. }
  39133. else {
  39134. for (var i = 0; i < count; i++) {
  39135. this.setupUniforms(this.effect, 0, instanceInfo._instancesPartsData[0], i);
  39136. engine.draw(true, 0, 6);
  39137. }
  39138. }
  39139. engine.setAlphaMode(cur);
  39140. return true;
  39141. };
  39142. Sprite2DRenderCache.prototype.dispose = function () {
  39143. if (!_super.prototype.dispose.call(this)) {
  39144. return false;
  39145. }
  39146. if (this.vb) {
  39147. this._engine._releaseBuffer(this.vb);
  39148. this.vb = null;
  39149. }
  39150. if (this.ib) {
  39151. this._engine._releaseBuffer(this.ib);
  39152. this.ib = null;
  39153. }
  39154. if (this.texture) {
  39155. this.texture.dispose();
  39156. this.texture = null;
  39157. }
  39158. if (this.effect) {
  39159. this._engine._releaseEffect(this.effect);
  39160. this.effect = null;
  39161. }
  39162. return true;
  39163. };
  39164. return Sprite2DRenderCache;
  39165. })(BABYLON.ModelRenderCache);
  39166. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  39167. var Sprite2DInstanceData = (function (_super) {
  39168. __extends(Sprite2DInstanceData, _super);
  39169. function Sprite2DInstanceData(partId) {
  39170. _super.call(this, partId, 1);
  39171. }
  39172. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  39173. get: function () {
  39174. return null;
  39175. },
  39176. enumerable: true,
  39177. configurable: true
  39178. });
  39179. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  39180. get: function () {
  39181. return null;
  39182. },
  39183. enumerable: true,
  39184. configurable: true
  39185. });
  39186. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  39187. get: function () {
  39188. return null;
  39189. },
  39190. enumerable: true,
  39191. configurable: true
  39192. });
  39193. Object.defineProperty(Sprite2DInstanceData.prototype, "frame", {
  39194. get: function () {
  39195. return null;
  39196. },
  39197. enumerable: true,
  39198. configurable: true
  39199. });
  39200. Object.defineProperty(Sprite2DInstanceData.prototype, "invertY", {
  39201. get: function () {
  39202. return null;
  39203. },
  39204. enumerable: true,
  39205. configurable: true
  39206. });
  39207. __decorate([
  39208. BABYLON.instanceData()
  39209. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  39210. __decorate([
  39211. BABYLON.instanceData()
  39212. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  39213. __decorate([
  39214. BABYLON.instanceData()
  39215. ], Sprite2DInstanceData.prototype, "textureSize", null);
  39216. __decorate([
  39217. BABYLON.instanceData()
  39218. ], Sprite2DInstanceData.prototype, "frame", null);
  39219. __decorate([
  39220. BABYLON.instanceData()
  39221. ], Sprite2DInstanceData.prototype, "invertY", null);
  39222. return Sprite2DInstanceData;
  39223. })(BABYLON.InstanceDataBase);
  39224. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  39225. var Sprite2D = (function (_super) {
  39226. __extends(Sprite2D, _super);
  39227. function Sprite2D() {
  39228. _super.apply(this, arguments);
  39229. }
  39230. Object.defineProperty(Sprite2D.prototype, "texture", {
  39231. get: function () {
  39232. return this._texture;
  39233. },
  39234. set: function (value) {
  39235. this._texture = value;
  39236. },
  39237. enumerable: true,
  39238. configurable: true
  39239. });
  39240. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  39241. get: function () {
  39242. return this.spriteSize;
  39243. },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  39248. get: function () {
  39249. return this._size;
  39250. },
  39251. set: function (value) {
  39252. this._size = value;
  39253. },
  39254. enumerable: true,
  39255. configurable: true
  39256. });
  39257. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  39258. get: function () {
  39259. return this._location;
  39260. },
  39261. set: function (value) {
  39262. this._location = value;
  39263. },
  39264. enumerable: true,
  39265. configurable: true
  39266. });
  39267. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  39268. get: function () {
  39269. return this._spriteFrame;
  39270. },
  39271. set: function (value) {
  39272. this._spriteFrame = value;
  39273. },
  39274. enumerable: true,
  39275. configurable: true
  39276. });
  39277. Object.defineProperty(Sprite2D.prototype, "invertY", {
  39278. get: function () {
  39279. return this._invertY;
  39280. },
  39281. set: function (value) {
  39282. this._invertY = value;
  39283. },
  39284. enumerable: true,
  39285. configurable: true
  39286. });
  39287. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  39288. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.spriteSize, this._levelBoundingInfo, this.origin);
  39289. };
  39290. Sprite2D.prototype.getAnimatables = function () {
  39291. var res = new Array();
  39292. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  39293. res.push(this.texture);
  39294. }
  39295. return res;
  39296. };
  39297. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  39298. // If we've made it so far it means the boundingInfo intersection test succeed, the Sprite2D is shaped the same, so we always return true
  39299. return true;
  39300. };
  39301. Sprite2D.prototype.setupSprite2D = function (owner, parent, id, position, origin, texture, spriteSize, spriteLocation, invertY) {
  39302. this.setupRenderablePrim2D(owner, parent, id, position, origin, true);
  39303. this.texture = texture;
  39304. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39305. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39306. this.spriteSize = spriteSize || null;
  39307. this.spriteLocation = spriteLocation || new BABYLON.Vector2(0, 0);
  39308. this.spriteFrame = 0;
  39309. this.invertY = invertY;
  39310. this._isTransparent = true;
  39311. if (!this.spriteSize) {
  39312. var s = texture.getSize();
  39313. this.spriteSize = new BABYLON.Size(s.width, s.height);
  39314. }
  39315. };
  39316. /**
  39317. * Create an 2D Sprite primitive
  39318. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  39319. * @param texture the texture that stores the sprite to render
  39320. * options:
  39321. * - id a text identifier, for information purpose
  39322. * - x: the X position relative to its parent, default is 0
  39323. * - y: the Y position relative to its parent, default is 0
  39324. * - origin: define the normalized origin point location, default [0.5;0.5]
  39325. * - spriteSize: the size of the sprite, if null the size of the given texture will be used, default is null.
  39326. * - spriteLocation: the location in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  39327. * - invertY: if true the texture Y will be inverted, default is false.
  39328. */
  39329. Sprite2D.Create = function (parent, texture, options) {
  39330. BABYLON.Prim2DBase.CheckParent(parent);
  39331. var sprite = new Sprite2D();
  39332. sprite.setupSprite2D(parent.owner, parent, options && options.id || null, new BABYLON.Vector2(options && options.x || 0, options && options.y || 0), options && options.origin || null, texture, options && options.spriteSize || null, options && options.spriteLocation || null, options && options.invertY || false);
  39333. return sprite;
  39334. };
  39335. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  39336. var sprite = new Sprite2D();
  39337. sprite.setupSprite2D(owner, null, "__cachedCanvasSprite__", new BABYLON.Vector2(0, 0), null, texture, size, pos, false);
  39338. return sprite;
  39339. };
  39340. Sprite2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  39341. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey, isTransparent);
  39342. return renderCache;
  39343. };
  39344. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  39345. var renderCache = modelRenderCache;
  39346. var engine = this.owner.engine;
  39347. var vb = new Float32Array(4);
  39348. for (var i = 0; i < 4; i++) {
  39349. vb[i] = i;
  39350. }
  39351. renderCache.vb = engine.createVertexBuffer(vb);
  39352. var ib = new Float32Array(6);
  39353. ib[0] = 0;
  39354. ib[1] = 2;
  39355. ib[2] = 1;
  39356. ib[3] = 0;
  39357. ib[4] = 3;
  39358. ib[5] = 2;
  39359. renderCache.ib = engine.createIndexBuffer(ib);
  39360. renderCache.texture = this.texture;
  39361. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"]);
  39362. renderCache.effect = engine.createEffect({ vertex: "sprite2d", fragment: "sprite2d" }, ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null, function (e) {
  39363. // renderCache.setupUniformsLocation(e, ei.uniforms, Sprite2D.SPRITE2D_MAINPARTID);
  39364. });
  39365. return renderCache;
  39366. };
  39367. Sprite2D.prototype.createInstanceDataParts = function () {
  39368. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  39369. };
  39370. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  39371. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  39372. return false;
  39373. }
  39374. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  39375. var d = this._instanceDataParts[0];
  39376. var ts = this.texture.getBaseSize();
  39377. var sl = this.spriteLocation;
  39378. var ss = this.spriteSize;
  39379. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  39380. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  39381. d.sizeUV = suv;
  39382. d.frame = this.spriteFrame;
  39383. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  39384. d.invertY = this.invertY ? 1 : 0;
  39385. }
  39386. return true;
  39387. };
  39388. Sprite2D.SPRITE2D_MAINPARTID = 1;
  39389. __decorate([
  39390. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  39391. ], Sprite2D.prototype, "texture", null);
  39392. __decorate([
  39393. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.spriteSizeProperty = pi; }, false, true)
  39394. ], Sprite2D.prototype, "spriteSize", null);
  39395. __decorate([
  39396. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  39397. ], Sprite2D.prototype, "spriteLocation", null);
  39398. __decorate([
  39399. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  39400. ], Sprite2D.prototype, "spriteFrame", null);
  39401. __decorate([
  39402. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  39403. ], Sprite2D.prototype, "invertY", null);
  39404. Sprite2D = __decorate([
  39405. BABYLON.className("Sprite2D")
  39406. ], Sprite2D);
  39407. return Sprite2D;
  39408. })(BABYLON.RenderablePrim2D);
  39409. BABYLON.Sprite2D = Sprite2D;
  39410. })(BABYLON || (BABYLON = {}));
  39411. var BABYLON;
  39412. (function (BABYLON) {
  39413. var Text2DRenderCache = (function (_super) {
  39414. __extends(Text2DRenderCache, _super);
  39415. function Text2DRenderCache() {
  39416. _super.apply(this, arguments);
  39417. }
  39418. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  39419. // Do nothing if the shader is still loading/preparing
  39420. if (!this.effect.isReady() || !this.fontTexture.isReady()) {
  39421. return false;
  39422. }
  39423. // Compute the offset locations of the attributes in the vertexshader that will be mapped to the instance buffer data
  39424. if (!this.instancingAttributes) {
  39425. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, this.effect);
  39426. }
  39427. var engine = instanceInfo._owner.owner.engine;
  39428. this.fontTexture.update();
  39429. engine.enableEffect(this.effect);
  39430. this.effect.setTexture("diffuseSampler", this.fontTexture);
  39431. engine.bindBuffers(this.vb, this.ib, [1], 4, this.effect);
  39432. var cur = engine.getAlphaMode();
  39433. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  39434. var count = instanceInfo._instancesPartsData[0].usedElementCount;
  39435. if (instanceInfo._owner.owner.supportInstancedArray) {
  39436. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], null, this.instancingAttributes);
  39437. engine.draw(true, 0, 6, count);
  39438. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], this.instancingAttributes);
  39439. }
  39440. else {
  39441. for (var i = 0; i < count; i++) {
  39442. this.setupUniforms(this.effect, 0, instanceInfo._instancesPartsData[0], i);
  39443. engine.draw(true, 0, 6);
  39444. }
  39445. }
  39446. engine.setAlphaMode(cur);
  39447. return true;
  39448. };
  39449. Text2DRenderCache.prototype.dispose = function () {
  39450. if (!_super.prototype.dispose.call(this)) {
  39451. return false;
  39452. }
  39453. if (this.vb) {
  39454. this._engine._releaseBuffer(this.vb);
  39455. this.vb = null;
  39456. }
  39457. if (this.ib) {
  39458. this._engine._releaseBuffer(this.ib);
  39459. this.ib = null;
  39460. }
  39461. if (this.fontTexture) {
  39462. this.fontTexture.dispose();
  39463. this.fontTexture = null;
  39464. }
  39465. if (this.effect) {
  39466. this._engine._releaseEffect(this.effect);
  39467. this.effect = null;
  39468. }
  39469. return true;
  39470. };
  39471. return Text2DRenderCache;
  39472. })(BABYLON.ModelRenderCache);
  39473. BABYLON.Text2DRenderCache = Text2DRenderCache;
  39474. var Text2DInstanceData = (function (_super) {
  39475. __extends(Text2DInstanceData, _super);
  39476. function Text2DInstanceData(partId, dataElementCount) {
  39477. _super.call(this, partId, dataElementCount);
  39478. }
  39479. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  39480. get: function () {
  39481. return null;
  39482. },
  39483. enumerable: true,
  39484. configurable: true
  39485. });
  39486. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  39487. get: function () {
  39488. return null;
  39489. },
  39490. enumerable: true,
  39491. configurable: true
  39492. });
  39493. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  39494. get: function () {
  39495. return null;
  39496. },
  39497. enumerable: true,
  39498. configurable: true
  39499. });
  39500. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  39501. get: function () {
  39502. return null;
  39503. },
  39504. enumerable: true,
  39505. configurable: true
  39506. });
  39507. __decorate([
  39508. BABYLON.instanceData()
  39509. ], Text2DInstanceData.prototype, "topLeftUV", null);
  39510. __decorate([
  39511. BABYLON.instanceData()
  39512. ], Text2DInstanceData.prototype, "sizeUV", null);
  39513. __decorate([
  39514. BABYLON.instanceData()
  39515. ], Text2DInstanceData.prototype, "textureSize", null);
  39516. __decorate([
  39517. BABYLON.instanceData()
  39518. ], Text2DInstanceData.prototype, "color", null);
  39519. return Text2DInstanceData;
  39520. })(BABYLON.InstanceDataBase);
  39521. BABYLON.Text2DInstanceData = Text2DInstanceData;
  39522. var Text2D = (function (_super) {
  39523. __extends(Text2D, _super);
  39524. function Text2D() {
  39525. _super.apply(this, arguments);
  39526. }
  39527. Object.defineProperty(Text2D.prototype, "fontName", {
  39528. get: function () {
  39529. return this._fontName;
  39530. },
  39531. set: function (value) {
  39532. if (this._fontName) {
  39533. throw new Error("Font Name change is not supported right now.");
  39534. }
  39535. this._fontName = value;
  39536. },
  39537. enumerable: true,
  39538. configurable: true
  39539. });
  39540. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  39541. get: function () {
  39542. return this._defaultFontColor;
  39543. },
  39544. set: function (value) {
  39545. this._defaultFontColor = value;
  39546. },
  39547. enumerable: true,
  39548. configurable: true
  39549. });
  39550. Object.defineProperty(Text2D.prototype, "text", {
  39551. get: function () {
  39552. return this._text;
  39553. },
  39554. set: function (value) {
  39555. this._text = value;
  39556. this._actualSize = null; // A change of text will reset the Actual Area Size which will be recomputed next time it's used
  39557. this._updateCharCount();
  39558. },
  39559. enumerable: true,
  39560. configurable: true
  39561. });
  39562. Object.defineProperty(Text2D.prototype, "areaSize", {
  39563. get: function () {
  39564. return this._areaSize;
  39565. },
  39566. set: function (value) {
  39567. this._areaSize = value;
  39568. },
  39569. enumerable: true,
  39570. configurable: true
  39571. });
  39572. Object.defineProperty(Text2D.prototype, "vAlign", {
  39573. get: function () {
  39574. return this._vAlign;
  39575. },
  39576. set: function (value) {
  39577. this._vAlign = value;
  39578. },
  39579. enumerable: true,
  39580. configurable: true
  39581. });
  39582. Object.defineProperty(Text2D.prototype, "hAlign", {
  39583. get: function () {
  39584. return this._hAlign;
  39585. },
  39586. set: function (value) {
  39587. this._hAlign = value;
  39588. },
  39589. enumerable: true,
  39590. configurable: true
  39591. });
  39592. Object.defineProperty(Text2D.prototype, "actualSize", {
  39593. get: function () {
  39594. if (this.areaSize) {
  39595. return this.areaSize;
  39596. }
  39597. if (this._actualSize) {
  39598. return this._actualSize;
  39599. }
  39600. this._actualSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  39601. return this._actualSize;
  39602. },
  39603. enumerable: true,
  39604. configurable: true
  39605. });
  39606. Object.defineProperty(Text2D.prototype, "fontTexture", {
  39607. get: function () {
  39608. if (this._fontTexture) {
  39609. return this._fontTexture;
  39610. }
  39611. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName);
  39612. return this._fontTexture;
  39613. },
  39614. enumerable: true,
  39615. configurable: true
  39616. });
  39617. Text2D.prototype.dispose = function () {
  39618. if (!_super.prototype.dispose.call(this)) {
  39619. return false;
  39620. }
  39621. if (this._fontTexture) {
  39622. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName);
  39623. this._fontTexture = null;
  39624. }
  39625. return true;
  39626. };
  39627. Text2D.prototype.updateLevelBoundingInfo = function () {
  39628. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo, this.origin);
  39629. };
  39630. Text2D.prototype.setupText2D = function (owner, parent, id, position, origin, fontName, text, areaSize, defaultFontColor, vAlign, hAlign, tabulationSize) {
  39631. this.setupRenderablePrim2D(owner, parent, id, position, origin, true);
  39632. this.fontName = fontName;
  39633. this.defaultFontColor = defaultFontColor;
  39634. this.text = text;
  39635. this.areaSize = areaSize;
  39636. this.vAlign = vAlign;
  39637. this.hAlign = hAlign;
  39638. this._tabulationSize = tabulationSize;
  39639. this._isTransparent = true;
  39640. };
  39641. /**
  39642. * Create a Text primitive
  39643. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  39644. * @param text the text to display
  39645. * Options:
  39646. * - id a text identifier, for information purpose
  39647. * - x: the X position relative to its parent, default is 0
  39648. * - y: the Y position relative to its parent, default is 0
  39649. * - origin: define the normalized origin point location, default [0.5;0.5]
  39650. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  39651. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  39652. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  39653. * - vAlign: vertical alignment (areaSize must be specified), default is Text2D.TEXT2D_VALIGN_CENTER
  39654. * - hAlign: horizontal alignment (areaSize must be specified), default is Text2D.TEXT2D_HALIGN_CENTER
  39655. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  39656. */
  39657. Text2D.Create = function (parent, text, options) {
  39658. BABYLON.Prim2DBase.CheckParent(parent);
  39659. var text2d = new Text2D();
  39660. text2d.setupText2D(parent.owner, parent, options && options.id || null, new BABYLON.Vector2(options && options.x || 0, options && options.y || 0), options && options.origin || null, options && options.fontName || "12pt Arial", text, options && options.areaSize, options && options.defaultFontColor || new BABYLON.Color4(1, 1, 1, 1), options && options.vAlign || Text2D.TEXT2D_VALIGN_CENTER, options && options.hAlign || Text2D.TEXT2D_HALIGN_CENTER, options && options.tabulationSize || 4);
  39661. return text2d;
  39662. };
  39663. Text2D.prototype.levelIntersect = function (intersectInfo) {
  39664. // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
  39665. return true;
  39666. };
  39667. Text2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  39668. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey, isTransparent);
  39669. return renderCache;
  39670. };
  39671. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  39672. var renderCache = modelRenderCache;
  39673. var engine = this.owner.engine;
  39674. renderCache.fontTexture = this.fontTexture;
  39675. var vb = new Float32Array(4);
  39676. for (var i = 0; i < 4; i++) {
  39677. vb[i] = i;
  39678. }
  39679. renderCache.vb = engine.createVertexBuffer(vb);
  39680. var ib = new Float32Array(6);
  39681. ib[0] = 0;
  39682. ib[1] = 2;
  39683. ib[2] = 1;
  39684. ib[3] = 0;
  39685. ib[4] = 3;
  39686. ib[5] = 2;
  39687. renderCache.ib = engine.createIndexBuffer(ib);
  39688. // Effects
  39689. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"]);
  39690. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  39691. return renderCache;
  39692. };
  39693. Text2D.prototype.createInstanceDataParts = function () {
  39694. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  39695. };
  39696. // Looks like a hack!? Yes! Because that's what it is!
  39697. // 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
  39698. // 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)
  39699. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  39700. if (!this._charCount) {
  39701. var curText = this._text;
  39702. this.text = "A";
  39703. return curText;
  39704. }
  39705. };
  39706. // if obj contains something, we restore the _text property
  39707. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  39708. if (obj !== undefined) {
  39709. this.text = obj;
  39710. }
  39711. };
  39712. Text2D.prototype.refreshInstanceDataPart = function (part) {
  39713. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  39714. return false;
  39715. }
  39716. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  39717. var d = part;
  39718. var texture = this.fontTexture;
  39719. var ts = texture.getSize();
  39720. var textSize = texture.measureText(this.text, this._tabulationSize);
  39721. var offset = BABYLON.Vector2.Zero();
  39722. var charxpos = 0;
  39723. d.dataElementCount = this._charCount;
  39724. d.curElement = 0;
  39725. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  39726. var char = _a[_i];
  39727. // Line feed
  39728. if (char === "\n") {
  39729. offset.x = 0;
  39730. offset.y -= texture.lineHeight;
  39731. }
  39732. // Tabulation ?
  39733. if (char === "\t") {
  39734. var nextPos = charxpos + this._tabulationSize;
  39735. nextPos = nextPos - (nextPos % this._tabulationSize);
  39736. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  39737. charxpos = nextPos;
  39738. continue;
  39739. }
  39740. if (char < " ") {
  39741. continue;
  39742. }
  39743. this.updateInstanceDataPart(d, offset, textSize);
  39744. var ci = texture.getChar(char);
  39745. offset.x += ci.charWidth;
  39746. d.topLeftUV = ci.topLeftUV;
  39747. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  39748. d.sizeUV = suv;
  39749. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  39750. d.color = this.defaultFontColor;
  39751. ++d.curElement;
  39752. }
  39753. }
  39754. return true;
  39755. };
  39756. Text2D.prototype._updateCharCount = function () {
  39757. var count = 0;
  39758. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  39759. var char = _a[_i];
  39760. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  39761. continue;
  39762. }
  39763. ++count;
  39764. }
  39765. this._charCount = count;
  39766. };
  39767. Text2D.TEXT2D_MAINPARTID = 1;
  39768. Text2D.TEXT2D_VALIGN_TOP = 1;
  39769. Text2D.TEXT2D_VALIGN_CENTER = 2;
  39770. Text2D.TEXT2D_VALIGN_BOTTOM = 3;
  39771. Text2D.TEXT2D_HALIGN_LEFT = 1;
  39772. Text2D.TEXT2D_HALIGN_CENTER = 2;
  39773. Text2D.TEXT2D_HALIGN_RIGHT = 3;
  39774. __decorate([
  39775. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  39776. ], Text2D.prototype, "fontName", null);
  39777. __decorate([
  39778. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  39779. ], Text2D.prototype, "defaultFontColor", null);
  39780. __decorate([
  39781. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  39782. ], Text2D.prototype, "text", null);
  39783. __decorate([
  39784. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.areaSizeProperty = pi; })
  39785. ], Text2D.prototype, "areaSize", null);
  39786. __decorate([
  39787. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D.vAlignProperty = pi; })
  39788. ], Text2D.prototype, "vAlign", null);
  39789. __decorate([
  39790. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D.hAlignProperty = pi; })
  39791. ], Text2D.prototype, "hAlign", null);
  39792. Text2D = __decorate([
  39793. BABYLON.className("Text2D")
  39794. ], Text2D);
  39795. return Text2D;
  39796. })(BABYLON.RenderablePrim2D);
  39797. BABYLON.Text2D = Text2D;
  39798. })(BABYLON || (BABYLON = {}));
  39799. var BABYLON;
  39800. (function (BABYLON) {
  39801. var Lines2DRenderCache = (function (_super) {
  39802. __extends(Lines2DRenderCache, _super);
  39803. function Lines2DRenderCache(engine, modelKey, isTransparent) {
  39804. _super.call(this, engine, modelKey, isTransparent);
  39805. }
  39806. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  39807. // Do nothing if the shader is still loading/preparing
  39808. if ((this.effectFill && !this.effectFill.isReady()) || (this.effectBorder && !this.effectBorder.isReady())) {
  39809. return false;
  39810. }
  39811. var engine = instanceInfo._owner.owner.engine;
  39812. var depthFunction = 0;
  39813. if (this.effectFill && this.effectBorder) {
  39814. depthFunction = engine.getDepthFunction();
  39815. engine.setDepthFunctionToLessOrEqual();
  39816. }
  39817. var cur;
  39818. if (this.isTransparent) {
  39819. cur = engine.getAlphaMode();
  39820. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39821. }
  39822. if (this.effectFill) {
  39823. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  39824. engine.enableEffect(this.effectFill);
  39825. engine.bindBuffers(this.fillVB, this.fillIB, [2], 2 * 4, this.effectFill);
  39826. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  39827. if (instanceInfo._owner.owner.supportInstancedArray) {
  39828. if (!this.instancingFillAttributes) {
  39829. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  39830. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, this.effectFill);
  39831. }
  39832. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingFillAttributes);
  39833. engine.draw(true, 0, this.fillIndicesCount, count);
  39834. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingFillAttributes);
  39835. }
  39836. else {
  39837. for (var i = 0; i < count; i++) {
  39838. this.setupUniforms(this.effectFill, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  39839. engine.draw(true, 0, this.fillIndicesCount);
  39840. }
  39841. }
  39842. }
  39843. if (this.effectBorder) {
  39844. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  39845. engine.enableEffect(this.effectBorder);
  39846. engine.bindBuffers(this.borderVB, this.borderIB, [2], 2 * 4, this.effectBorder);
  39847. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  39848. if (instanceInfo._owner.owner.supportInstancedArray) {
  39849. if (!this.instancingBorderAttributes) {
  39850. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, this.effectBorder);
  39851. }
  39852. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingBorderAttributes);
  39853. engine.draw(true, 0, this.borderIndicesCount, count);
  39854. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingBorderAttributes);
  39855. }
  39856. else {
  39857. for (var i = 0; i < count; i++) {
  39858. this.setupUniforms(this.effectBorder, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  39859. engine.draw(true, 0, this.borderIndicesCount);
  39860. }
  39861. }
  39862. }
  39863. if (this.isTransparent) {
  39864. engine.setAlphaMode(cur);
  39865. }
  39866. if (this.effectFill && this.effectBorder) {
  39867. engine.setDepthFunction(depthFunction);
  39868. }
  39869. return true;
  39870. };
  39871. Lines2DRenderCache.prototype.dispose = function () {
  39872. if (!_super.prototype.dispose.call(this)) {
  39873. return false;
  39874. }
  39875. if (this.fillVB) {
  39876. this._engine._releaseBuffer(this.fillVB);
  39877. this.fillVB = null;
  39878. }
  39879. if (this.fillIB) {
  39880. this._engine._releaseBuffer(this.fillIB);
  39881. this.fillIB = null;
  39882. }
  39883. if (this.effectFill) {
  39884. this._engine._releaseEffect(this.effectFill);
  39885. this.effectFill = null;
  39886. }
  39887. if (this.borderVB) {
  39888. this._engine._releaseBuffer(this.borderVB);
  39889. this.borderVB = null;
  39890. }
  39891. if (this.borderIB) {
  39892. this._engine._releaseBuffer(this.borderIB);
  39893. this.borderIB = null;
  39894. }
  39895. if (this.effectBorder) {
  39896. this._engine._releaseEffect(this.effectBorder);
  39897. this.effectBorder = null;
  39898. }
  39899. return true;
  39900. };
  39901. return Lines2DRenderCache;
  39902. })(BABYLON.ModelRenderCache);
  39903. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  39904. var Lines2DInstanceData = (function (_super) {
  39905. __extends(Lines2DInstanceData, _super);
  39906. function Lines2DInstanceData(partId) {
  39907. _super.call(this, partId, 1);
  39908. }
  39909. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  39910. get: function () {
  39911. return null;
  39912. },
  39913. enumerable: true,
  39914. configurable: true
  39915. });
  39916. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  39917. get: function () {
  39918. return null;
  39919. },
  39920. enumerable: true,
  39921. configurable: true
  39922. });
  39923. __decorate([
  39924. BABYLON.instanceData()
  39925. ], Lines2DInstanceData.prototype, "boundingMin", null);
  39926. __decorate([
  39927. BABYLON.instanceData()
  39928. ], Lines2DInstanceData.prototype, "boundingMax", null);
  39929. return Lines2DInstanceData;
  39930. })(BABYLON.Shape2DInstanceData);
  39931. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  39932. var Lines2D = (function (_super) {
  39933. __extends(Lines2D, _super);
  39934. function Lines2D() {
  39935. _super.apply(this, arguments);
  39936. }
  39937. Object.defineProperty(Lines2D, "NoCap", {
  39938. get: function () { return Lines2D._noCap; },
  39939. enumerable: true,
  39940. configurable: true
  39941. });
  39942. Object.defineProperty(Lines2D, "RoundCap", {
  39943. get: function () { return Lines2D._roundCap; },
  39944. enumerable: true,
  39945. configurable: true
  39946. });
  39947. Object.defineProperty(Lines2D, "TriangleCap", {
  39948. get: function () { return Lines2D._triangleCap; },
  39949. enumerable: true,
  39950. configurable: true
  39951. });
  39952. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  39953. get: function () { return Lines2D._squareAnchorCap; },
  39954. enumerable: true,
  39955. configurable: true
  39956. });
  39957. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  39958. get: function () { return Lines2D._roundAnchorCap; },
  39959. enumerable: true,
  39960. configurable: true
  39961. });
  39962. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  39963. get: function () { return Lines2D._diamondAnchorCap; },
  39964. enumerable: true,
  39965. configurable: true
  39966. });
  39967. Object.defineProperty(Lines2D, "ArrowCap", {
  39968. get: function () { return Lines2D._arrowCap; },
  39969. enumerable: true,
  39970. configurable: true
  39971. });
  39972. Object.defineProperty(Lines2D.prototype, "actualSize", {
  39973. get: function () {
  39974. return this.size;
  39975. },
  39976. enumerable: true,
  39977. configurable: true
  39978. });
  39979. Object.defineProperty(Lines2D.prototype, "points", {
  39980. get: function () {
  39981. return this._points;
  39982. },
  39983. set: function (value) {
  39984. this._points = value;
  39985. this._levelBoundingInfoDirty = true;
  39986. },
  39987. enumerable: true,
  39988. configurable: true
  39989. });
  39990. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  39991. get: function () {
  39992. return this._fillThickness;
  39993. },
  39994. set: function (value) {
  39995. this._fillThickness = value;
  39996. },
  39997. enumerable: true,
  39998. configurable: true
  39999. });
  40000. Object.defineProperty(Lines2D.prototype, "closed", {
  40001. get: function () {
  40002. return this._closed;
  40003. },
  40004. set: function (value) {
  40005. this._closed = value;
  40006. },
  40007. enumerable: true,
  40008. configurable: true
  40009. });
  40010. Object.defineProperty(Lines2D.prototype, "startCap", {
  40011. get: function () {
  40012. return this._startCap;
  40013. },
  40014. set: function (value) {
  40015. this._startCap = value;
  40016. },
  40017. enumerable: true,
  40018. configurable: true
  40019. });
  40020. Object.defineProperty(Lines2D.prototype, "endCap", {
  40021. get: function () {
  40022. return this._endCap;
  40023. },
  40024. set: function (value) {
  40025. this._endCap = value;
  40026. },
  40027. enumerable: true,
  40028. configurable: true
  40029. });
  40030. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  40031. var pl = this.points.length;
  40032. var l = this.closed ? pl + 1 : pl;
  40033. var originOffset = new BABYLON.Vector2(-0.5, -0.5);
  40034. var p = intersectInfo._localPickPosition;
  40035. var prevA = this.transformPointWithOrigin(this._contour[0], originOffset);
  40036. var prevB = this.transformPointWithOrigin(this._contour[1], originOffset);
  40037. for (var i = 1; i < l; i++) {
  40038. var curA = this.transformPointWithOrigin(this._contour[(i % pl) * 2 + 0], originOffset);
  40039. var curB = this.transformPointWithOrigin(this._contour[(i % pl) * 2 + 1], originOffset);
  40040. if (BABYLON.Vector2.PointInTriangle(p, prevA, prevB, curA)) {
  40041. return true;
  40042. }
  40043. if (BABYLON.Vector2.PointInTriangle(p, curA, prevB, curB)) {
  40044. return true;
  40045. }
  40046. prevA = curA;
  40047. prevB = curB;
  40048. }
  40049. return false;
  40050. };
  40051. Object.defineProperty(Lines2D.prototype, "size", {
  40052. get: function () {
  40053. return this._size;
  40054. },
  40055. enumerable: true,
  40056. configurable: true
  40057. });
  40058. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  40059. get: function () {
  40060. return this._boundingMin;
  40061. },
  40062. enumerable: true,
  40063. configurable: true
  40064. });
  40065. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  40066. get: function () {
  40067. return this._boundingMax;
  40068. },
  40069. enumerable: true,
  40070. configurable: true
  40071. });
  40072. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  40073. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  40074. // Remove the BORDER category, we don't use it in the VertexShader
  40075. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  40076. if (i !== -1) {
  40077. res.splice(i, 1);
  40078. }
  40079. return res;
  40080. };
  40081. Lines2D.prototype.updateLevelBoundingInfo = function () {
  40082. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo, this.origin);
  40083. };
  40084. Lines2D.prototype.setupLines2D = function (owner, parent, id, position, origin, points, fillThickness, startCap, endCap, fill, border, borderThickness, closed) {
  40085. this.setupShape2D(owner, parent, id, position, origin, true, fill, border, borderThickness);
  40086. this.fillThickness = fillThickness;
  40087. this.startCap = startCap;
  40088. this.endCap = endCap;
  40089. this.points = points;
  40090. this.closed = closed;
  40091. this._size = BABYLON.Size.Zero();
  40092. this._boundingMin = BABYLON.Vector2.Zero();
  40093. this._boundingMax = BABYLON.Vector2.Zero();
  40094. };
  40095. /**
  40096. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  40097. * @param parent the parent primitive, must be a valid primitive (or the Canvas)
  40098. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  40099. * options:
  40100. * - id a text identifier, for information purpose
  40101. * - x: the X position relative to its parent, default is 0
  40102. * - y: the Y position relative to its parent, default is 0
  40103. * - origin: define the normalized origin point location, default [0.5;0.5]
  40104. * - fillThickness: the thickness of the fill part of the line, can be null to draw nothing (but a border brush must be given), default is 1.
  40105. * - closed: if false the lines are said to be opened, the first point and the latest DON'T connect. if true the lines are said to be closed, the first and last point will be connected by a line. For instance you can define the 4 points of a rectangle, if you set closed to true a 4 edges rectangle will be drawn. If you set false, only three edges will be drawn, the edge formed by the first and last point won't exist. Default is false.
  40106. * - Draw a cap of the given type at the start of the first line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  40107. * - Draw a cap of the given type at the end of the last line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  40108. * - fill: the brush used to draw the fill content of the lines, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white.
  40109. * - border: the brush used to draw the border of the lines, you can set null to draw nothing (but you will have to set a fill brush), default is null.
  40110. * - borderThickness: the thickness of the drawn border, default is 1.
  40111. */
  40112. Lines2D.Create = function (parent, points, options) {
  40113. BABYLON.Prim2DBase.CheckParent(parent);
  40114. var fill;
  40115. if (options && options.fill !== undefined) {
  40116. fill = options.fill;
  40117. }
  40118. else {
  40119. fill = BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF");
  40120. }
  40121. var lines = new Lines2D();
  40122. lines.setupLines2D(parent.owner, parent, options && options.id || null, new BABYLON.Vector2(options && options.x || 0, options && options.y || 0), options && options.origin || null, points, options && options.fillThickness || 1, options && options.startCap || 0, options && options.endCap || 0, fill, options && options.border || null, options && options.borderThickness || 0, options && options.closed || false);
  40123. return lines;
  40124. };
  40125. Lines2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  40126. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey, isTransparent);
  40127. return renderCache;
  40128. };
  40129. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  40130. var _this = this;
  40131. var renderCache = modelRenderCache;
  40132. var engine = this.owner.engine;
  40133. // Init min/max because their being computed here
  40134. this.boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  40135. this.boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  40136. var perp = function (v, res) {
  40137. res.x = v.y;
  40138. res.y = -v.x;
  40139. };
  40140. var direction = function (a, b, res) {
  40141. a.subtractToRef(b, res);
  40142. res.normalize();
  40143. };
  40144. var tps = BABYLON.Vector2.Zero();
  40145. var computeMiter = function (tangent, miter, a, b) {
  40146. a.addToRef(b, tangent);
  40147. tangent.normalize();
  40148. miter.x = -tangent.y;
  40149. miter.y = tangent.x;
  40150. tps.x = -a.y;
  40151. tps.y = a.x;
  40152. return 1 / BABYLON.Vector2.Dot(miter, tps);
  40153. };
  40154. var intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  40155. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  40156. if (d === 0)
  40157. return false;
  40158. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  40159. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  40160. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  40161. return false;
  40162. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  40163. return false;
  40164. return true;
  40165. };
  40166. var startDir = BABYLON.Vector2.Zero();
  40167. var endDir = BABYLON.Vector2.Zero();
  40168. var updateMinMax = function (array, offset) {
  40169. if (offset >= array.length) {
  40170. return;
  40171. }
  40172. _this._boundingMin.x = Math.min(_this._boundingMin.x, array[offset]);
  40173. _this._boundingMax.x = Math.max(_this._boundingMax.x, array[offset]);
  40174. _this._boundingMin.y = Math.min(_this._boundingMin.y, array[offset + 1]);
  40175. _this._boundingMax.y = Math.max(_this._boundingMax.y, array[offset + 1]);
  40176. };
  40177. var store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  40178. var borderMode = borderThickness != null && !isNaN(borderThickness);
  40179. var off = index * (borderMode ? 8 : 4);
  40180. // Mandatory because we'll be out of bound in case of closed line, for the very last point (which is a duplicate of the first that we don't store in the vb)
  40181. if (off >= array.length) {
  40182. return;
  40183. }
  40184. // Store start/end normal, we need it for the cap construction
  40185. if (index === 0) {
  40186. perp(n, startDir);
  40187. }
  40188. else if (index === max - 1) {
  40189. perp(n, endDir);
  40190. endDir.x *= -1;
  40191. endDir.y *= -1;
  40192. }
  40193. var swap = false;
  40194. array[off + 0] = p.x + n.x * halfThickness;
  40195. array[off + 1] = p.y + n.y * halfThickness;
  40196. array[off + 2] = p.x + n.x * -halfThickness;
  40197. array[off + 3] = p.y + n.y * -halfThickness;
  40198. updateMinMax(array, off);
  40199. updateMinMax(array, off + 2);
  40200. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  40201. // It should not be the case, they should be parallel, so if they cross, we switch the order of storage to ensure we'll have parallel lines
  40202. if (detectFlip !== undefined) {
  40203. // Flip if intersect
  40204. var flipOff = detectFlip * (borderMode ? 8 : 4);
  40205. if (intersect(array[off + 0], array[off + 1], array[flipOff + 0], array[flipOff + 1], array[off + 2], array[off + 3], array[flipOff + 2], array[flipOff + 3])) {
  40206. swap = true;
  40207. var tps_1 = array[off + 0];
  40208. array[off + 0] = array[off + 2];
  40209. array[off + 2] = tps_1;
  40210. tps_1 = array[off + 1];
  40211. array[off + 1] = array[off + 3];
  40212. array[off + 3] = tps_1;
  40213. }
  40214. }
  40215. if (borderMode) {
  40216. var t = halfThickness + borderThickness;
  40217. array[off + 4] = p.x + n.x * (swap ? -t : t);
  40218. array[off + 5] = p.y + n.y * (swap ? -t : t);
  40219. array[off + 6] = p.x + n.x * (swap ? t : -t);
  40220. array[off + 7] = p.y + n.y * (swap ? t : -t);
  40221. updateMinMax(array, off + 4);
  40222. updateMinMax(array, off + 6);
  40223. }
  40224. if (contour) {
  40225. off += borderMode ? 4 : 0;
  40226. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  40227. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  40228. }
  40229. };
  40230. var sd = Lines2D._roundCapSubDiv;
  40231. var getCapSize = function (type, border) {
  40232. if (border === void 0) { border = false; }
  40233. // If no array given, we call this to get the size
  40234. var vbsize = 0, ibsize = 0;
  40235. switch (type) {
  40236. case Lines2D.NoCap:
  40237. // If the line is not close and we're computing border, we add the size to generate the edge border
  40238. if (!_this.closed && border) {
  40239. vbsize = 4;
  40240. ibsize = 6;
  40241. }
  40242. else {
  40243. vbsize = ibsize = 0;
  40244. }
  40245. break;
  40246. case Lines2D.RoundCap:
  40247. if (border) {
  40248. vbsize = sd;
  40249. ibsize = (sd - 2) * 3;
  40250. }
  40251. else {
  40252. vbsize = (sd / 2) + 1;
  40253. ibsize = (sd / 2) * 3;
  40254. }
  40255. break;
  40256. case Lines2D.ArrowCap:
  40257. if (border) {
  40258. vbsize = 12;
  40259. ibsize = 24;
  40260. }
  40261. else {
  40262. vbsize = 3;
  40263. ibsize = 3;
  40264. }
  40265. break;
  40266. case Lines2D.TriangleCap:
  40267. if (border) {
  40268. vbsize = 6;
  40269. ibsize = 12;
  40270. }
  40271. else {
  40272. vbsize = 3;
  40273. ibsize = 3;
  40274. }
  40275. break;
  40276. case Lines2D.DiamondAnchorCap:
  40277. if (border) {
  40278. vbsize = 10;
  40279. ibsize = 24;
  40280. }
  40281. else {
  40282. vbsize = 5;
  40283. ibsize = 9;
  40284. }
  40285. break;
  40286. case Lines2D.SquareAnchorCap:
  40287. if (border) {
  40288. vbsize = 12;
  40289. ibsize = 30;
  40290. }
  40291. else {
  40292. vbsize = 4;
  40293. ibsize = 6;
  40294. }
  40295. break;
  40296. case Lines2D.RoundAnchorCap:
  40297. if (border) {
  40298. vbsize = sd * 2;
  40299. ibsize = (sd - 1) * 6;
  40300. }
  40301. else {
  40302. vbsize = sd + 1;
  40303. ibsize = (sd + 1) * 3;
  40304. }
  40305. break;
  40306. }
  40307. return { vbsize: vbsize * 2, ibsize: ibsize };
  40308. };
  40309. var v = BABYLON.Vector2.Zero();
  40310. var storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex) {
  40311. var c = Math.cos(rotation);
  40312. var s = Math.sin(rotation);
  40313. v.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  40314. v.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  40315. var offset = baseOffset + (index * 2);
  40316. vb[offset + 0] = v.x;
  40317. vb[offset + 1] = v.y;
  40318. updateMinMax(vb, offset);
  40319. return (baseOffset + index * 2) / 2;
  40320. };
  40321. var storeIndex = function (ib, baseOffset, index, vertexIndex) {
  40322. ib[baseOffset + index] = vertexIndex;
  40323. };
  40324. var buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir) {
  40325. // Compute the transformation from the direction of the cap to build relative to our default orientation [1;0] (our cap are by default pointing toward right, horizontal
  40326. var dir = new BABYLON.Vector2(1, 0);
  40327. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  40328. var ht = thickness / 2;
  40329. var t = thickness;
  40330. var borderMode = borderThickness != null;
  40331. var bt = borderThickness;
  40332. switch (type) {
  40333. case Lines2D.NoCap:
  40334. if (borderMode && !_this.closed) {
  40335. var vi = 0;
  40336. var ii = 0;
  40337. var v1 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt));
  40338. var v2 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt));
  40339. var v3 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)));
  40340. var v4 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)));
  40341. storeIndex(ib, ibi, ii++, v1);
  40342. storeIndex(ib, ibi, ii++, v2);
  40343. storeIndex(ib, ibi, ii++, v3);
  40344. storeIndex(ib, ibi, ii++, v1);
  40345. storeIndex(ib, ibi, ii++, v3);
  40346. storeIndex(ib, ibi, ii++, v4);
  40347. }
  40348. break;
  40349. case Lines2D.ArrowCap:
  40350. ht *= 2;
  40351. case Lines2D.TriangleCap:
  40352. {
  40353. if (borderMode) {
  40354. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  40355. var v1 = storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht));
  40356. var v2 = storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0));
  40357. var v3 = storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht));
  40358. var v4 = storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f));
  40359. var v5 = storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0));
  40360. var v6 = storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)));
  40361. var ii = 0;
  40362. storeIndex(ib, ibi, ii++, v1);
  40363. storeIndex(ib, ibi, ii++, v4);
  40364. storeIndex(ib, ibi, ii++, v5);
  40365. storeIndex(ib, ibi, ii++, v1);
  40366. storeIndex(ib, ibi, ii++, v5);
  40367. storeIndex(ib, ibi, ii++, v2);
  40368. storeIndex(ib, ibi, ii++, v6);
  40369. storeIndex(ib, ibi, ii++, v3);
  40370. storeIndex(ib, ibi, ii++, v2);
  40371. storeIndex(ib, ibi, ii++, v6);
  40372. storeIndex(ib, ibi, ii++, v2);
  40373. storeIndex(ib, ibi, ii++, v5);
  40374. if (type === Lines2D.ArrowCap) {
  40375. var rht = thickness / 2;
  40376. var v7 = storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt));
  40377. var v8 = storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt));
  40378. var v9 = storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f));
  40379. var v10 = storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)));
  40380. var v11 = storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)));
  40381. var v12 = storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)));
  40382. storeIndex(ib, ibi, ii++, v7);
  40383. storeIndex(ib, ibi, ii++, v8);
  40384. storeIndex(ib, ibi, ii++, v9);
  40385. storeIndex(ib, ibi, ii++, v7);
  40386. storeIndex(ib, ibi, ii++, v9);
  40387. storeIndex(ib, ibi, ii++, v4);
  40388. storeIndex(ib, ibi, ii++, v10);
  40389. storeIndex(ib, ibi, ii++, v12);
  40390. storeIndex(ib, ibi, ii++, v11);
  40391. storeIndex(ib, ibi, ii++, v10);
  40392. storeIndex(ib, ibi, ii++, v6);
  40393. storeIndex(ib, ibi, ii++, v12);
  40394. }
  40395. }
  40396. else {
  40397. var v1 = storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht));
  40398. var v2 = storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0));
  40399. var v3 = storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht));
  40400. storeIndex(ib, ibi, 0, v1);
  40401. storeIndex(ib, ibi, 1, v2);
  40402. storeIndex(ib, ibi, 2, v3);
  40403. }
  40404. break;
  40405. }
  40406. case Lines2D.RoundCap:
  40407. {
  40408. if (borderMode) {
  40409. var curA = -Math.PI / 2;
  40410. var incA = Math.PI / (sd / 2 - 1);
  40411. var ii = 0;
  40412. for (var i = 0; i < (sd / 2); i++) {
  40413. var v1 = storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht));
  40414. var v2 = storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * (ht + bt), Math.sin(curA) * (ht + bt)));
  40415. if (i > 0) {
  40416. storeIndex(ib, ibi, ii++, v1 - 2);
  40417. storeIndex(ib, ibi, ii++, v2 - 2);
  40418. storeIndex(ib, ibi, ii++, v2);
  40419. storeIndex(ib, ibi, ii++, v1 - 2);
  40420. storeIndex(ib, ibi, ii++, v2);
  40421. storeIndex(ib, ibi, ii++, v1);
  40422. }
  40423. curA += incA;
  40424. }
  40425. }
  40426. else {
  40427. var c = storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0));
  40428. var curA = -Math.PI / 2;
  40429. var incA = Math.PI / (sd / 2 - 1);
  40430. storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht));
  40431. curA += incA;
  40432. for (var i = 1; i < (sd / 2); i++) {
  40433. var v2 = storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht));
  40434. storeIndex(ib, ibi, i * 3 + 0, c);
  40435. storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  40436. storeIndex(ib, ibi, i * 3 + 2, v2);
  40437. curA += incA;
  40438. }
  40439. }
  40440. break;
  40441. }
  40442. case Lines2D.SquareAnchorCap:
  40443. {
  40444. var vi = 0;
  40445. var v1 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t));
  40446. var v2 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t));
  40447. var v3 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t));
  40448. var v4 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t));
  40449. if (borderMode) {
  40450. var v5 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt));
  40451. var v6 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt));
  40452. var v7 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt));
  40453. var v8 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt));
  40454. var v9 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)));
  40455. var v10 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)));
  40456. var v11 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)));
  40457. var v12 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)));
  40458. var ii = 0;
  40459. storeIndex(ib, ibi, ii++, v6);
  40460. storeIndex(ib, ibi, ii++, v1);
  40461. storeIndex(ib, ibi, ii++, v5);
  40462. storeIndex(ib, ibi, ii++, v6);
  40463. storeIndex(ib, ibi, ii++, v7);
  40464. storeIndex(ib, ibi, ii++, v1);
  40465. storeIndex(ib, ibi, ii++, v1);
  40466. storeIndex(ib, ibi, ii++, v7);
  40467. storeIndex(ib, ibi, ii++, v8);
  40468. storeIndex(ib, ibi, ii++, v1);
  40469. storeIndex(ib, ibi, ii++, v8);
  40470. storeIndex(ib, ibi, ii++, v2);
  40471. storeIndex(ib, ibi, ii++, v2);
  40472. storeIndex(ib, ibi, ii++, v8);
  40473. storeIndex(ib, ibi, ii++, v9);
  40474. storeIndex(ib, ibi, ii++, v2);
  40475. storeIndex(ib, ibi, ii++, v9);
  40476. storeIndex(ib, ibi, ii++, v3);
  40477. storeIndex(ib, ibi, ii++, v3);
  40478. storeIndex(ib, ibi, ii++, v9);
  40479. storeIndex(ib, ibi, ii++, v10);
  40480. storeIndex(ib, ibi, ii++, v3);
  40481. storeIndex(ib, ibi, ii++, v10);
  40482. storeIndex(ib, ibi, ii++, v4);
  40483. storeIndex(ib, ibi, ii++, v10);
  40484. storeIndex(ib, ibi, ii++, v11);
  40485. storeIndex(ib, ibi, ii++, v4);
  40486. storeIndex(ib, ibi, ii++, v11);
  40487. storeIndex(ib, ibi, ii++, v12);
  40488. storeIndex(ib, ibi, ii++, v4);
  40489. }
  40490. else {
  40491. storeIndex(ib, ibi, 0, v1);
  40492. storeIndex(ib, ibi, 1, v2);
  40493. storeIndex(ib, ibi, 2, v3);
  40494. storeIndex(ib, ibi, 3, v1);
  40495. storeIndex(ib, ibi, 4, v3);
  40496. storeIndex(ib, ibi, 5, v4);
  40497. }
  40498. break;
  40499. }
  40500. case Lines2D.RoundAnchorCap:
  40501. {
  40502. var cpos = Math.sqrt(t * t - ht * ht);
  40503. var center = new BABYLON.Vector2(cpos, 0);
  40504. var curA = BABYLON.Tools.ToRadians(-150);
  40505. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  40506. if (borderMode) {
  40507. var ii = 0;
  40508. for (var i = 0; i < sd; i++) {
  40509. var v1 = storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t));
  40510. var v2 = storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * (t + bt), Math.sin(curA) * (t + bt)));
  40511. if (i > 0) {
  40512. storeIndex(ib, ibi, ii++, v1 - 2);
  40513. storeIndex(ib, ibi, ii++, v2 - 2);
  40514. storeIndex(ib, ibi, ii++, v2);
  40515. storeIndex(ib, ibi, ii++, v1 - 2);
  40516. storeIndex(ib, ibi, ii++, v2);
  40517. storeIndex(ib, ibi, ii++, v1);
  40518. }
  40519. curA += incA;
  40520. }
  40521. }
  40522. else {
  40523. var c = storeVertex(vb, vbi, 0, pos, angle, center);
  40524. storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t));
  40525. curA += incA;
  40526. for (var i = 1; i < sd; i++) {
  40527. var v2 = storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t));
  40528. storeIndex(ib, ibi, i * 3 + 0, c);
  40529. storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  40530. storeIndex(ib, ibi, i * 3 + 2, v2);
  40531. curA += incA;
  40532. }
  40533. storeIndex(ib, ibi, sd * 3 + 0, c);
  40534. storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  40535. storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  40536. }
  40537. break;
  40538. }
  40539. case Lines2D.DiamondAnchorCap:
  40540. {
  40541. var vi = 0;
  40542. var v1 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht));
  40543. var v2 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t));
  40544. var v3 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0));
  40545. var v4 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t));
  40546. var v5 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht));
  40547. if (borderMode) {
  40548. var f = Math.sqrt(bt * bt * 2);
  40549. var v6 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht));
  40550. var v7 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f));
  40551. var v8 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0));
  40552. var v9 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)));
  40553. var v10 = storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht));
  40554. var ii = 0;
  40555. storeIndex(ib, ibi, ii++, v6);
  40556. storeIndex(ib, ibi, ii++, v7);
  40557. storeIndex(ib, ibi, ii++, v1);
  40558. storeIndex(ib, ibi, ii++, v1);
  40559. storeIndex(ib, ibi, ii++, v7);
  40560. storeIndex(ib, ibi, ii++, v2);
  40561. storeIndex(ib, ibi, ii++, v2);
  40562. storeIndex(ib, ibi, ii++, v7);
  40563. storeIndex(ib, ibi, ii++, v8);
  40564. storeIndex(ib, ibi, ii++, v2);
  40565. storeIndex(ib, ibi, ii++, v8);
  40566. storeIndex(ib, ibi, ii++, v3);
  40567. storeIndex(ib, ibi, ii++, v3);
  40568. storeIndex(ib, ibi, ii++, v8);
  40569. storeIndex(ib, ibi, ii++, v9);
  40570. storeIndex(ib, ibi, ii++, v3);
  40571. storeIndex(ib, ibi, ii++, v9);
  40572. storeIndex(ib, ibi, ii++, v4);
  40573. storeIndex(ib, ibi, ii++, v4);
  40574. storeIndex(ib, ibi, ii++, v9);
  40575. storeIndex(ib, ibi, ii++, v10);
  40576. storeIndex(ib, ibi, ii++, v4);
  40577. storeIndex(ib, ibi, ii++, v10);
  40578. storeIndex(ib, ibi, ii++, v5);
  40579. }
  40580. else {
  40581. storeIndex(ib, ibi, 0, v1);
  40582. storeIndex(ib, ibi, 1, v2);
  40583. storeIndex(ib, ibi, 2, v3);
  40584. storeIndex(ib, ibi, 3, v1);
  40585. storeIndex(ib, ibi, 4, v3);
  40586. storeIndex(ib, ibi, 5, v5);
  40587. storeIndex(ib, ibi, 6, v5);
  40588. storeIndex(ib, ibi, 7, v3);
  40589. storeIndex(ib, ibi, 8, v4);
  40590. }
  40591. break;
  40592. }
  40593. }
  40594. return null;
  40595. };
  40596. var buildLine = function (vb, contour, ht, bt) {
  40597. var lineA = BABYLON.Vector2.Zero();
  40598. var lineB = BABYLON.Vector2.Zero();
  40599. var tangent = BABYLON.Vector2.Zero();
  40600. var miter = BABYLON.Vector2.Zero();
  40601. var curNormal = null;
  40602. if (_this.closed) {
  40603. _this.points.push(_this.points[0]);
  40604. }
  40605. var total = _this.points.length;
  40606. for (var i = 1; i < total; i++) {
  40607. var last = _this.points[i - 1];
  40608. var cur = _this.points[i];
  40609. var next = (i < (_this.points.length - 1)) ? _this.points[i + 1] : null;
  40610. direction(cur, last, lineA);
  40611. if (!curNormal) {
  40612. curNormal = BABYLON.Vector2.Zero();
  40613. perp(lineA, curNormal);
  40614. }
  40615. if (i === 1) {
  40616. store(vb, contour, 0, total, _this.points[0], curNormal, ht, bt);
  40617. }
  40618. if (!next) {
  40619. perp(lineA, curNormal);
  40620. store(vb, contour, i, total, _this.points[i], curNormal, ht, bt, i - 1);
  40621. }
  40622. else {
  40623. direction(next, cur, lineB);
  40624. var miterLen = computeMiter(tangent, miter, lineA, lineB);
  40625. store(vb, contour, i, total, _this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  40626. }
  40627. }
  40628. if (_this.points.length > 2 && _this.closed) {
  40629. var last2 = _this.points[total - 2];
  40630. var cur2 = _this.points[0];
  40631. var next2 = _this.points[1];
  40632. direction(cur2, last2, lineA);
  40633. direction(next2, cur2, lineB);
  40634. perp(lineA, curNormal);
  40635. var miterLen2 = computeMiter(tangent, miter, lineA, lineB);
  40636. store(vb, null, 0, total, _this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  40637. // Patch contour
  40638. if (contour) {
  40639. var off = (bt == null) ? 0 : 4;
  40640. contour[0].x = vb[off + 0];
  40641. contour[0].y = vb[off + 1];
  40642. contour[1].x = vb[off + 2];
  40643. contour[1].y = vb[off + 3];
  40644. }
  40645. }
  40646. // Remove the point we added at the beginning
  40647. if (_this.closed) {
  40648. _this.points.splice(total - 1);
  40649. }
  40650. };
  40651. var contour = new Array();
  40652. // Need to create WebGL resources for fill part?
  40653. if (this.fill) {
  40654. var startCapInfo = getCapSize(this.startCap);
  40655. var endCapInfo = getCapSize(this.endCap);
  40656. var count = this.points.length;
  40657. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  40658. var vb = new Float32Array(vbSize);
  40659. var ht = this.fillThickness / 2;
  40660. var total = this.points.length;
  40661. buildLine(vb, this.border ? null : contour, ht);
  40662. var max = total * 2;
  40663. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  40664. var ib = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  40665. for (var i = 0; i < triCount; i += 2) {
  40666. ib[i * 3 + 0] = i + 0;
  40667. ib[i * 3 + 1] = i + 1;
  40668. ib[i * 3 + 2] = (i + 2) % max;
  40669. ib[i * 3 + 3] = i + 1;
  40670. ib[i * 3 + 4] = (i + 3) % max;
  40671. ib[i * 3 + 5] = (i + 2) % max;
  40672. }
  40673. buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, startDir);
  40674. buildCap(vb, (count * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, null, this.endCap, endDir);
  40675. renderCache.fillVB = engine.createVertexBuffer(vb);
  40676. renderCache.fillIB = engine.createIndexBuffer(ib);
  40677. renderCache.fillIndicesCount = ib.length;
  40678. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"]);
  40679. renderCache.effectFill = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  40680. }
  40681. // Need to create WebGL resources for border part?
  40682. if (this.border) {
  40683. var startCapInfo = getCapSize(this.startCap, true);
  40684. var endCapInfo = getCapSize(this.endCap, true);
  40685. var count = this.points.length;
  40686. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  40687. var vb = new Float32Array(vbSize);
  40688. var ht = this.fillThickness / 2;
  40689. var bt = this.borderThickness;
  40690. var total = this.points.length;
  40691. buildLine(vb, contour, ht, bt);
  40692. var max = total * 2 * 2;
  40693. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  40694. var ib = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  40695. for (var i = 0; i < triCount; i += 4) {
  40696. ib[i * 3 + 0] = i + 0;
  40697. ib[i * 3 + 1] = i + 2;
  40698. ib[i * 3 + 2] = (i + 6) % max;
  40699. ib[i * 3 + 3] = i + 0;
  40700. ib[i * 3 + 4] = (i + 6) % max;
  40701. ib[i * 3 + 5] = (i + 4) % max;
  40702. ib[i * 3 + 6] = i + 3;
  40703. ib[i * 3 + 7] = i + 1;
  40704. ib[i * 3 + 8] = (i + 5) % max;
  40705. ib[i * 3 + 9] = i + 3;
  40706. ib[i * 3 + 10] = (i + 5) % max;
  40707. ib[i * 3 + 11] = (i + 7) % max;
  40708. }
  40709. buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, startDir);
  40710. buildCap(vb, (count * 2 * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, this.borderThickness, this.endCap, endDir);
  40711. renderCache.borderVB = engine.createVertexBuffer(vb);
  40712. renderCache.borderIB = engine.createIndexBuffer(ib);
  40713. renderCache.borderIndicesCount = ib.length;
  40714. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"]);
  40715. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  40716. }
  40717. this._contour = contour;
  40718. var bs = this._boundingMax.subtract(this._boundingMin);
  40719. this._size.width = bs.x;
  40720. this._size.height = bs.y;
  40721. return renderCache;
  40722. };
  40723. Lines2D.prototype.createInstanceDataParts = function () {
  40724. var res = new Array();
  40725. if (this.border) {
  40726. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  40727. }
  40728. if (this.fill) {
  40729. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  40730. }
  40731. return res;
  40732. };
  40733. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  40734. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  40735. return false;
  40736. }
  40737. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  40738. var d = part;
  40739. d.boundingMin = this.boundingMin;
  40740. d.boundingMax = this.boundingMax;
  40741. }
  40742. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  40743. var d = part;
  40744. d.boundingMin = this.boundingMin;
  40745. d.boundingMax = this.boundingMax;
  40746. }
  40747. return true;
  40748. };
  40749. Lines2D._noCap = 0;
  40750. Lines2D._roundCap = 1;
  40751. Lines2D._triangleCap = 2;
  40752. Lines2D._squareAnchorCap = 3;
  40753. Lines2D._roundAnchorCap = 4;
  40754. Lines2D._diamondAnchorCap = 5;
  40755. Lines2D._arrowCap = 6;
  40756. Lines2D._roundCapSubDiv = 36;
  40757. __decorate([
  40758. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  40759. ], Lines2D.prototype, "points", null);
  40760. __decorate([
  40761. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  40762. ], Lines2D.prototype, "fillThickness", null);
  40763. __decorate([
  40764. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  40765. ], Lines2D.prototype, "closed", null);
  40766. __decorate([
  40767. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  40768. ], Lines2D.prototype, "startCap", null);
  40769. __decorate([
  40770. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  40771. ], Lines2D.prototype, "endCap", null);
  40772. Lines2D = __decorate([
  40773. BABYLON.className("Lines2D")
  40774. ], Lines2D);
  40775. return Lines2D;
  40776. })(BABYLON.Shape2D);
  40777. BABYLON.Lines2D = Lines2D;
  40778. })(BABYLON || (BABYLON = {}));
  40779. var BABYLON;
  40780. (function (BABYLON) {
  40781. var Canvas2DEngineBoundData = (function () {
  40782. function Canvas2DEngineBoundData() {
  40783. this._modelCache = new BABYLON.StringDictionary();
  40784. }
  40785. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  40786. return this._modelCache.getOrAddWithFactory(key, factory);
  40787. };
  40788. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  40789. if (!modelRenderCache.isDisposed) {
  40790. return false;
  40791. }
  40792. this._modelCache.remove(modelRenderCache.modelKey);
  40793. return true;
  40794. };
  40795. return Canvas2DEngineBoundData;
  40796. })();
  40797. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  40798. var Canvas2D = (function (_super) {
  40799. __extends(Canvas2D, _super);
  40800. function Canvas2D() {
  40801. _super.apply(this, arguments);
  40802. this._notifDebugMode = false;
  40803. this._mapCounter = 0;
  40804. }
  40805. /**
  40806. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the bottom/left corner of the screen.
  40807. * 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.
  40808. * All caching strategies will be available.
  40809. * 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]
  40810. * @param scene the Scene that owns the Canvas
  40811. * Options:
  40812. * - id: a text identifier, for information purpose only
  40813. * - pos: the position of the canvas, relative from the bottom/left of the scene's viewport
  40814. * - 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
  40815. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS
  40816. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property.
  40817. */
  40818. Canvas2D.CreateScreenSpace = function (scene, options) {
  40819. var c = new Canvas2D();
  40820. c.setupCanvas(scene, options && options.id || null, options && options.size || null, true, options && options.cachingStrategy || Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS, options && options.enableInteraction || true);
  40821. c.position = options && options.pos || BABYLON.Vector2.Zero();
  40822. c.origin = options && options.origin || BABYLON.Vector2.Zero();
  40823. return c;
  40824. };
  40825. /**
  40826. * 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.
  40827. * 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.
  40828. * @param scene the Scene that owns the Canvas
  40829. * @param size the dimension of the Canvas in World Space
  40830. * Options:
  40831. * - id: a text identifier, for information purpose only, default is null.
  40832. * - position the position of the Canvas in World Space, default is [0,0,0]
  40833. * - rotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  40834. * - 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. Default value is 1.
  40835. * BE AWARE that the Canvas true dimension will be size*renderScaleFactor, then all coordinates and size will have to be express regarding this size.
  40836. * 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.
  40837. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  40838. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  40839. */
  40840. Canvas2D.CreateWorldSpace = function (scene, size, options) {
  40841. var cs = options && options.cachingStrategy || Canvas2D.CACHESTRATEGY_CANVAS;
  40842. if (cs !== Canvas2D.CACHESTRATEGY_CANVAS) {
  40843. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  40844. }
  40845. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  40846. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  40847. //}
  40848. var id = options && options.id || null;
  40849. var rsf = options && options.renderScaleFactor || 1;
  40850. var c = new Canvas2D();
  40851. c.setupCanvas(scene, id, new BABYLON.Size(size.width * rsf, size.height * rsf), false, cs, options && options.enableInteraction || true);
  40852. var plane = new BABYLON.WorldSpaceCanvas2D(id, scene, c);
  40853. var vertexData = BABYLON.VertexData.CreatePlane({ width: size.width / 2, height: size.height / 2, sideOrientation: options && options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE });
  40854. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  40855. c.applyCachedTexture(vertexData, mtl);
  40856. vertexData.applyToMesh(plane, false);
  40857. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  40858. mtl.disableLighting = true;
  40859. mtl.useAlphaFromDiffuseTexture = true;
  40860. plane.position = options && options.position || BABYLON.Vector3.Zero();
  40861. plane.rotationQuaternion = options && options.rotation || BABYLON.Quaternion.Identity();
  40862. plane.material = mtl;
  40863. c._worldSpaceNode = plane;
  40864. return c;
  40865. };
  40866. Canvas2D.prototype.setupCanvas = function (scene, name, size, isScreenSpace, cachingstrategy, enableInteraction) {
  40867. var _this = this;
  40868. var engine = scene.getEngine();
  40869. this._fitRenderingDevice = !size;
  40870. if (!size) {
  40871. size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  40872. }
  40873. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  40874. this._cachingStrategy = cachingstrategy;
  40875. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  40876. this._capturedPointers = new BABYLON.StringDictionary();
  40877. this._pickStartingPosition = BABYLON.Vector2.Zero();
  40878. this.setupGroup2D(this, null, name, BABYLON.Vector2.Zero(), null, size, this._cachingStrategy === Canvas2D.CACHESTRATEGY_ALLGROUPS ? BABYLON.Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE : BABYLON.Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY);
  40879. this._hierarchyLevelMaxSiblingCount = 100;
  40880. this._hierarchyDepthOffset = 0;
  40881. this._siblingDepthOffset = 1 / this._hierarchyLevelMaxSiblingCount;
  40882. this._scene = scene;
  40883. this._engine = engine;
  40884. this._renderingSize = new BABYLON.Size(0, 0);
  40885. // Register scene dispose to also dispose the canvas when it'll happens
  40886. scene.onDisposeObservable.add(function (d, s) {
  40887. _this.dispose();
  40888. });
  40889. if (cachingstrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  40890. this._background = BABYLON.Rectangle2D.Create(this, { id: "###CANVAS BACKGROUND###", width: size.width, height: size.height });
  40891. this._background.isPickable = false;
  40892. this._background.origin = BABYLON.Vector2.Zero();
  40893. this._background.levelVisible = false;
  40894. }
  40895. this._isScreeSpace = isScreenSpace;
  40896. if (this._isScreeSpace) {
  40897. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  40898. _this._engine.clear(null, false, true);
  40899. _this._render();
  40900. });
  40901. }
  40902. else {
  40903. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  40904. _this._render();
  40905. });
  40906. }
  40907. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  40908. // this._supprtInstancedArray = false; // TODO REMOVE!!!
  40909. this._setupInteraction(enableInteraction);
  40910. };
  40911. Object.defineProperty(Canvas2D.prototype, "hierarchyLevelMaxSiblingCount", {
  40912. get: function () {
  40913. return this._hierarchyLevelMaxSiblingCount;
  40914. },
  40915. enumerable: true,
  40916. configurable: true
  40917. });
  40918. Canvas2D.prototype._setupInteraction = function (enable) {
  40919. var _this = this;
  40920. // No change detection
  40921. if (enable === this._interactionEnabled) {
  40922. return;
  40923. }
  40924. // Set the new state
  40925. this._interactionEnabled = enable;
  40926. // Disable interaction
  40927. if (!enable) {
  40928. if (this._scenePrePointerObserver) {
  40929. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  40930. this._scenePrePointerObserver = null;
  40931. }
  40932. return;
  40933. }
  40934. // Enable Interaction
  40935. // Register the observable
  40936. this.scene.onPrePointerObservable.add(function (e, s) { return _this._handlePointerEventForInteraction(e, s); });
  40937. };
  40938. /**
  40939. * Internal method, you should use the Prim2DBase version instead
  40940. */
  40941. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  40942. if (this.isPointerCaptured(pointerId)) {
  40943. return false;
  40944. }
  40945. // Try to capture the pointer on the HTML side
  40946. try {
  40947. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  40948. }
  40949. catch (e) {
  40950. }
  40951. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  40952. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  40953. this._capturedPointers.add(pointerId.toString(), primitive);
  40954. return true;
  40955. };
  40956. /**
  40957. * Internal method, you should use the Prim2DBase version instead
  40958. */
  40959. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  40960. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  40961. return false;
  40962. }
  40963. // Try to release the pointer on the HTML side
  40964. try {
  40965. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  40966. }
  40967. catch (e) {
  40968. }
  40969. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  40970. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  40971. this._capturedPointers.remove(pointerId.toString());
  40972. return true;
  40973. };
  40974. /**
  40975. * Determine if the given pointer is captured or not
  40976. * @param pointerId the Id of the pointer
  40977. * @return true if it's captured, false otherwise
  40978. */
  40979. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  40980. return this._capturedPointers.contains(pointerId.toString());
  40981. };
  40982. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  40983. // Avoid unnecessary lookup
  40984. if (this._capturedPointers.count === 0) {
  40985. return null;
  40986. }
  40987. return this._capturedPointers.get(pointerId.toString());
  40988. };
  40989. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, eventState) {
  40990. // Dispose check
  40991. if (this.isDisposed) {
  40992. return;
  40993. }
  40994. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  40995. this._updatePointerInfo(eventData);
  40996. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  40997. // 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.
  40998. // 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.
  40999. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  41000. // 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
  41001. this._updateOverStatus();
  41002. // Check if we have nothing to raise
  41003. if (!this._actualOverPrimitive && !capturedPrim) {
  41004. return;
  41005. }
  41006. // Update the relatedTarget info with the over primitive or the captured one (if any)
  41007. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  41008. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  41009. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  41010. // Analyze the pointer event type and fire proper events on the primitive
  41011. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  41012. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  41013. }
  41014. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41015. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  41016. }
  41017. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  41018. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  41019. }
  41020. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  41021. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  41022. }
  41023. };
  41024. Canvas2D.prototype._updatePointerInfo = function (eventData) {
  41025. var pii = this._primPointerInfo;
  41026. if (!pii.canvasPointerPos) {
  41027. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  41028. }
  41029. pii.canvasPointerPos.x = eventData.localPosition.x - this.position.x;
  41030. pii.canvasPointerPos.y = (this.engine.getRenderHeight() - eventData.localPosition.y) - this.position.y;
  41031. pii.mouseWheelDelta = 0;
  41032. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  41033. var event = eventData.event;
  41034. if (event.wheelDelta) {
  41035. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  41036. }
  41037. else if (event.detail) {
  41038. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  41039. }
  41040. }
  41041. else {
  41042. var pe = eventData.event;
  41043. pii.ctrlKey = pe.ctrlKey;
  41044. pii.altKey = pe.altKey;
  41045. pii.shiftKey = pe.shiftKey;
  41046. pii.metaKey = pe.metaKey;
  41047. pii.button = pe.button;
  41048. pii.buttons = pe.buttons;
  41049. pii.pointerId = pe.pointerId;
  41050. pii.width = pe.width;
  41051. pii.height = pe.height;
  41052. pii.presssure = pe.pressure;
  41053. pii.tilt.x = pe.tiltX;
  41054. pii.tilt.y = pe.tiltY;
  41055. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  41056. }
  41057. };
  41058. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  41059. if (this.scene.getRenderId() === this._intersectionRenderId) {
  41060. return;
  41061. }
  41062. var ii = Canvas2D._interInfo;
  41063. ii.pickPosition.x = mouseLocalPos.x;
  41064. ii.pickPosition.y = mouseLocalPos.y;
  41065. ii.findFirstOnly = false;
  41066. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  41067. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  41068. this._previousIntersectionList = this._actualIntersectionList;
  41069. this._actualIntersectionList = null;
  41070. this._previousOverPrimitive = this._actualOverPrimitive;
  41071. this._actualOverPrimitive = null;
  41072. return;
  41073. }
  41074. this._updateCanvasState();
  41075. this.intersect(ii);
  41076. this._previousIntersectionList = this._actualIntersectionList;
  41077. this._actualIntersectionList = ii.intersectedPrimitives;
  41078. this._previousOverPrimitive = this._actualOverPrimitive;
  41079. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  41080. this._intersectionRenderId = this.scene.getRenderId();
  41081. };
  41082. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  41083. Canvas2D.prototype._updateOverStatus = function () {
  41084. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  41085. return;
  41086. }
  41087. // Detect a change of over
  41088. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  41089. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  41090. if (prevPrim !== actualPrim) {
  41091. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  41092. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  41093. // Notify the previous "over" prim that the pointer is no longer over it
  41094. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  41095. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  41096. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  41097. }
  41098. // Notify the new "over" prim that the pointer is over it
  41099. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  41100. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  41101. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  41102. }
  41103. }
  41104. this._hoverStatusRenderId = this.scene.getRenderId();
  41105. };
  41106. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  41107. if (this._primPointerInfo.isCaptured) {
  41108. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  41109. }
  41110. else {
  41111. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  41112. var pii = _a[_i];
  41113. if (pii.prim === prim) {
  41114. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  41115. return;
  41116. }
  41117. }
  41118. }
  41119. };
  41120. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  41121. if (!this._notifDebugMode) {
  41122. return;
  41123. }
  41124. var debug = "";
  41125. for (var i = 0; i < prim.hierarchyDepth; i++) {
  41126. debug += " ";
  41127. }
  41128. var pii = this._primPointerInfo;
  41129. 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();
  41130. console.log(debug);
  41131. };
  41132. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  41133. var ppi = this._primPointerInfo;
  41134. // In case of PointerOver/Out we will first notify the children (but the deepest to the closest) with PointerEnter/Leave
  41135. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  41136. this._notifChildren(prim, mask);
  41137. }
  41138. var bubbleCancelled = false;
  41139. var cur = prim;
  41140. while (cur) {
  41141. // Only trigger the observers if the primitive is intersected (except for out)
  41142. if (!bubbleCancelled) {
  41143. this._updatePrimPointerPos(cur);
  41144. // Exec the observers
  41145. this._debugExecObserver(cur, mask);
  41146. cur._pointerEventObservable.notifyObservers(ppi, mask);
  41147. this._triggerActionManager(cur, ppi, mask, eventData);
  41148. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  41149. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  41150. if (ppi.cancelBubble) {
  41151. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  41152. return;
  41153. }
  41154. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  41155. bubbleCancelled = true;
  41156. }
  41157. }
  41158. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  41159. if (bubbleCancelled) {
  41160. this._updatePrimPointerPos(cur);
  41161. }
  41162. // Trigger a PointerEnter corresponding to the PointerOver
  41163. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  41164. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  41165. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  41166. }
  41167. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  41168. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  41169. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  41170. }
  41171. // Loop to the parent
  41172. cur = cur.parent;
  41173. }
  41174. };
  41175. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  41176. var _this = this;
  41177. // Process Trigger related to PointerDown
  41178. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  41179. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  41180. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  41181. this._pickStartingTime = new Date().getTime();
  41182. this._pickedDownPrim = null;
  41183. if (prim.actionManager) {
  41184. this._pickedDownPrim = prim;
  41185. if (prim.actionManager.hasPickTriggers) {
  41186. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  41187. switch (eventData.button) {
  41188. case 0:
  41189. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  41190. break;
  41191. case 1:
  41192. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  41193. break;
  41194. case 2:
  41195. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  41196. break;
  41197. }
  41198. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  41199. }
  41200. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  41201. window.setTimeout(function () {
  41202. var ppi = _this._primPointerInfo;
  41203. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  41204. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  41205. var ii = new BABYLON.IntersectInfo2D();
  41206. ii.pickPosition = ppi.canvasPointerPos.clone();
  41207. ii.findFirstOnly = false;
  41208. _this.intersect(ii);
  41209. if (ii.isPrimIntersected(prim) !== null) {
  41210. if (prim.actionManager) {
  41211. if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.ActionManager.DragMovementThreshold)) {
  41212. _this._pickStartingTime = 0;
  41213. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  41214. }
  41215. }
  41216. }
  41217. }, BABYLON.ActionManager.LongPressDelay);
  41218. }
  41219. }
  41220. }
  41221. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  41222. this._pickStartingTime = 0;
  41223. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  41224. if (prim.actionManager) {
  41225. // OnPickUpTrigger
  41226. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  41227. // OnPickTrigger
  41228. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  41229. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  41230. }
  41231. }
  41232. // OnPickOutTrigger
  41233. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  41234. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  41235. }
  41236. }
  41237. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  41238. if (prim.actionManager) {
  41239. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  41240. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  41241. }
  41242. }
  41243. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  41244. if (prim.actionManager) {
  41245. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  41246. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  41247. }
  41248. }
  41249. };
  41250. Canvas2D.prototype._notifChildren = function (prim, mask) {
  41251. var _this = this;
  41252. var pii = this._primPointerInfo;
  41253. prim.children.forEach(function (curChild) {
  41254. // Recurse first, we want the deepest to be notified first
  41255. _this._notifChildren(curChild, mask);
  41256. _this._updatePrimPointerPos(curChild);
  41257. // Fire the proper notification
  41258. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  41259. _this._debugExecObserver(curChild, BABYLON.PrimitivePointerInfo.PointerEnter);
  41260. curChild._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  41261. }
  41262. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  41263. _this._debugExecObserver(curChild, BABYLON.PrimitivePointerInfo.PointerLeave);
  41264. curChild._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  41265. }
  41266. });
  41267. };
  41268. /**
  41269. * Don't forget to call the dispose method when you're done with the Canvas instance.
  41270. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  41271. */
  41272. Canvas2D.prototype.dispose = function () {
  41273. if (!_super.prototype.dispose.call(this)) {
  41274. return false;
  41275. }
  41276. if (this.interactionEnabled) {
  41277. this._setupInteraction(false);
  41278. }
  41279. if (this._beforeRenderObserver) {
  41280. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  41281. this._beforeRenderObserver = null;
  41282. }
  41283. if (this._afterRenderObserver) {
  41284. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  41285. this._afterRenderObserver = null;
  41286. }
  41287. if (this._groupCacheMaps) {
  41288. this._groupCacheMaps.forEach(function (m) { return m.dispose(); });
  41289. this._groupCacheMaps = null;
  41290. }
  41291. };
  41292. Object.defineProperty(Canvas2D.prototype, "scene", {
  41293. /**
  41294. * Accessor to the Scene that owns the Canvas
  41295. * @returns The instance of the Scene object
  41296. */
  41297. get: function () {
  41298. return this._scene;
  41299. },
  41300. enumerable: true,
  41301. configurable: true
  41302. });
  41303. Object.defineProperty(Canvas2D.prototype, "engine", {
  41304. /**
  41305. * Accessor to the Engine that drives the Scene used by this Canvas
  41306. * @returns The instance of the Engine object
  41307. */
  41308. get: function () {
  41309. return this._engine;
  41310. },
  41311. enumerable: true,
  41312. configurable: true
  41313. });
  41314. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  41315. /**
  41316. * Accessor of the Caching Strategy used by this Canvas.
  41317. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  41318. * @returns the value corresponding to the used strategy.
  41319. */
  41320. get: function () {
  41321. return this._cachingStrategy;
  41322. },
  41323. enumerable: true,
  41324. configurable: true
  41325. });
  41326. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  41327. /**
  41328. * Only valid for World Space Canvas, returns the scene node that display the canvas
  41329. */
  41330. get: function () {
  41331. return this._worldSpaceNode;
  41332. },
  41333. enumerable: true,
  41334. configurable: true
  41335. });
  41336. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  41337. /**
  41338. * Check if the WebGL Instanced Array extension is supported or not
  41339. * @returns {}
  41340. */
  41341. get: function () {
  41342. return this._supprtInstancedArray;
  41343. },
  41344. enumerable: true,
  41345. configurable: true
  41346. });
  41347. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  41348. /**
  41349. * Property that defines the fill object used to draw the background of the Canvas.
  41350. * Note that Canvas with a Caching Strategy of
  41351. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  41352. */
  41353. get: function () {
  41354. if (!this._background || !this._background.isVisible) {
  41355. return null;
  41356. }
  41357. return this._background.fill;
  41358. },
  41359. set: function (value) {
  41360. this.checkBackgroundAvailability();
  41361. if (value === this._background.fill) {
  41362. return;
  41363. }
  41364. this._background.fill = value;
  41365. this._background.levelVisible = true;
  41366. },
  41367. enumerable: true,
  41368. configurable: true
  41369. });
  41370. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  41371. /**
  41372. * Property that defines the border object used to draw the background of the Canvas.
  41373. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  41374. */
  41375. get: function () {
  41376. if (!this._background || !this._background.isVisible) {
  41377. return null;
  41378. }
  41379. return this._background.border;
  41380. },
  41381. set: function (value) {
  41382. this.checkBackgroundAvailability();
  41383. if (value === this._background.border) {
  41384. return;
  41385. }
  41386. this._background.border = value;
  41387. this._background.levelVisible = true;
  41388. },
  41389. enumerable: true,
  41390. configurable: true
  41391. });
  41392. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  41393. /**
  41394. * You can set the roundRadius of the background
  41395. * @returns The current roundRadius
  41396. */
  41397. get: function () {
  41398. if (!this._background || !this._background.isVisible) {
  41399. return null;
  41400. }
  41401. return this._background.roundRadius;
  41402. },
  41403. set: function (value) {
  41404. this.checkBackgroundAvailability();
  41405. if (value === this._background.roundRadius) {
  41406. return;
  41407. }
  41408. this._background.roundRadius = value;
  41409. this._background.levelVisible = true;
  41410. },
  41411. enumerable: true,
  41412. configurable: true
  41413. });
  41414. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  41415. /**
  41416. * Enable/Disable interaction for this Canvas
  41417. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  41418. */
  41419. get: function () {
  41420. return this._interactionEnabled;
  41421. },
  41422. set: function (enable) {
  41423. this._setupInteraction(enable);
  41424. },
  41425. enumerable: true,
  41426. configurable: true
  41427. });
  41428. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  41429. get: function () {
  41430. return this.__engineData;
  41431. },
  41432. enumerable: true,
  41433. configurable: true
  41434. });
  41435. Canvas2D.prototype.checkBackgroundAvailability = function () {
  41436. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  41437. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  41438. }
  41439. };
  41440. Canvas2D.prototype.onPrimBecomesDirty = function () {
  41441. this._addPrimToDirtyList(this);
  41442. };
  41443. Canvas2D.prototype._updateCanvasState = function () {
  41444. // Check if the update has already been made for this render Frame
  41445. if (this.scene.getRenderId() === this._updateRenderId) {
  41446. return;
  41447. }
  41448. this._renderingSize.width = this.engine.getRenderWidth();
  41449. this._renderingSize.height = this.engine.getRenderHeight();
  41450. if (this._fitRenderingDevice) {
  41451. this.size = this._renderingSize;
  41452. if (this._background) {
  41453. this._background.size = this.size;
  41454. }
  41455. }
  41456. var context = new BABYLON.Render2DContext();
  41457. context.forceRefreshPrimitive = false;
  41458. ++this._globalTransformProcessStep;
  41459. this.updateGlobalTransVis(false);
  41460. this._prepareGroupRender(context);
  41461. this._updateRenderId = this.scene.getRenderId();
  41462. };
  41463. /**
  41464. * Method that renders the Canvas, you should not invoke
  41465. */
  41466. Canvas2D.prototype._render = function () {
  41467. this._updateCanvasState();
  41468. if (this._primPointerInfo.canvasPointerPos) {
  41469. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  41470. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  41471. }
  41472. var context = new BABYLON.Render2DContext();
  41473. this._groupRender(context);
  41474. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  41475. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  41476. this._cachedCanvasGroup._renderCachedCanvas(context);
  41477. }
  41478. };
  41479. /**
  41480. * Internal method that allocate a cache for the given group.
  41481. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  41482. * @param group The group to allocate the cache of.
  41483. * @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.
  41484. */
  41485. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize) {
  41486. // Determine size
  41487. var size = group.actualSize;
  41488. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  41489. if (minSize) {
  41490. size.width = Math.max(minSize.width, size.width);
  41491. size.height = Math.max(minSize.height, size.height);
  41492. }
  41493. if (!this._groupCacheMaps) {
  41494. this._groupCacheMaps = new Array();
  41495. }
  41496. // Try to find a spot in one of the cached texture
  41497. var res = null;
  41498. for (var _i = 0, _a = this._groupCacheMaps; _i < _a.length; _i++) {
  41499. var map = _a[_i];
  41500. var node = map.allocateRect(size);
  41501. if (node) {
  41502. res = { node: node, texture: map };
  41503. break;
  41504. }
  41505. }
  41506. // Couldn't find a map that could fit the rect, create a new map for it
  41507. if (!res) {
  41508. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  41509. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  41510. if (size.width > mapSize.width || size.height > mapSize.height) {
  41511. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  41512. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  41513. }
  41514. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  41515. map = new BABYLON.MapTexture(id, this._scene, mapSize);
  41516. this._groupCacheMaps.push(map);
  41517. var node = map.allocateRect(size);
  41518. res = { node: node, texture: map };
  41519. }
  41520. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  41521. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  41522. if (group !== this || this._isScreeSpace) {
  41523. var node = res.node;
  41524. // 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
  41525. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  41526. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  41527. var sprite = BABYLON.Sprite2D.Create(this._cachedCanvasGroup, map, { id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  41528. sprite.zOrder = 1;
  41529. sprite.origin = BABYLON.Vector2.Zero();
  41530. }
  41531. else {
  41532. var sprite = BABYLON.Sprite2D.Create(parent, map, { id: "__cachedSpriteOfGroup__" + group.id, x: group.position.x, y: group.position.y, spriteSize: node.contentSize, spriteLocation: node.pos });
  41533. sprite.origin = group.origin.clone();
  41534. res.sprite = sprite;
  41535. }
  41536. }
  41537. return res;
  41538. };
  41539. /**
  41540. * Get a Solid Color Brush instance matching the given color.
  41541. * @param color The color to retrieve
  41542. * @return A shared instance of the SolidColorBrush2D class that use the given color
  41543. */
  41544. Canvas2D.GetSolidColorBrush = function (color) {
  41545. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  41546. };
  41547. /**
  41548. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  41549. * @param color The color to retrieve
  41550. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  41551. */
  41552. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  41553. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  41554. };
  41555. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  41556. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  41557. if (rotation === void 0) { rotation = 0; }
  41558. if (scale === void 0) { scale = 1; }
  41559. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  41560. };
  41561. /**
  41562. * 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.
  41563. * This strategy doesn't allow primitives added directly as children of the Canvas.
  41564. * 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.
  41565. */
  41566. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  41567. /**
  41568. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  41569. * 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.
  41570. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  41571. * 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.
  41572. */
  41573. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  41574. /**
  41575. * 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).
  41576. */
  41577. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  41578. /**
  41579. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  41580. * 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).
  41581. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  41582. */
  41583. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  41584. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  41585. /**
  41586. * Define the default size used for both the width and height of a MapTexture to allocate.
  41587. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  41588. */
  41589. Canvas2D._groupTextureCacheSize = 1024;
  41590. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  41591. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  41592. Canvas2D = __decorate([
  41593. BABYLON.className("Canvas2D")
  41594. ], Canvas2D);
  41595. return Canvas2D;
  41596. })(BABYLON.Group2D);
  41597. BABYLON.Canvas2D = Canvas2D;
  41598. })(BABYLON || (BABYLON = {}));
  41599. var BABYLON;
  41600. (function (BABYLON) {
  41601. /**
  41602. * This is the class that is used to display a World Space Canvas into a scene
  41603. */
  41604. var WorldSpaceCanvas2D = (function (_super) {
  41605. __extends(WorldSpaceCanvas2D, _super);
  41606. function WorldSpaceCanvas2D(name, scene, canvas) {
  41607. _super.call(this, name, scene);
  41608. this._canvas = canvas;
  41609. }
  41610. WorldSpaceCanvas2D.prototype.dispose = function () {
  41611. _super.prototype.dispose.call(this);
  41612. if (this._canvas) {
  41613. this._canvas.dispose();
  41614. this._canvas = null;
  41615. }
  41616. };
  41617. return WorldSpaceCanvas2D;
  41618. })(BABYLON.Mesh);
  41619. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  41620. })(BABYLON || (BABYLON = {}));
  41621. var BABYLON;
  41622. (function (BABYLON) {
  41623. var ShaderMaterial = (function (_super) {
  41624. __extends(ShaderMaterial, _super);
  41625. function ShaderMaterial(name, scene, shaderPath, options) {
  41626. _super.call(this, name, scene);
  41627. this._textures = {};
  41628. this._floats = {};
  41629. this._floatsArrays = {};
  41630. this._colors3 = {};
  41631. this._colors4 = {};
  41632. this._vectors2 = {};
  41633. this._vectors3 = {};
  41634. this._vectors4 = {};
  41635. this._matrices = {};
  41636. this._matrices3x3 = {};
  41637. this._matrices2x2 = {};
  41638. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  41639. this._shaderPath = shaderPath;
  41640. options.needAlphaBlending = options.needAlphaBlending || false;
  41641. options.needAlphaTesting = options.needAlphaTesting || false;
  41642. options.attributes = options.attributes || ["position", "normal", "uv"];
  41643. options.uniforms = options.uniforms || ["worldViewProjection"];
  41644. options.samplers = options.samplers || [];
  41645. options.defines = options.defines || [];
  41646. this._options = options;
  41647. }
  41648. ShaderMaterial.prototype.needAlphaBlending = function () {
  41649. return this._options.needAlphaBlending;
  41650. };
  41651. ShaderMaterial.prototype.needAlphaTesting = function () {
  41652. return this._options.needAlphaTesting;
  41653. };
  41654. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41655. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41656. this._options.uniforms.push(uniformName);
  41657. }
  41658. };
  41659. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41660. if (this._options.samplers.indexOf(name) === -1) {
  41661. this._options.samplers.push(name);
  41662. }
  41663. this._textures[name] = texture;
  41664. return this;
  41665. };
  41666. ShaderMaterial.prototype.setFloat = function (name, value) {
  41667. this._checkUniform(name);
  41668. this._floats[name] = value;
  41669. return this;
  41670. };
  41671. ShaderMaterial.prototype.setFloats = function (name, value) {
  41672. this._checkUniform(name);
  41673. this._floatsArrays[name] = value;
  41674. return this;
  41675. };
  41676. ShaderMaterial.prototype.setColor3 = function (name, value) {
  41677. this._checkUniform(name);
  41678. this._colors3[name] = value;
  41679. return this;
  41680. };
  41681. ShaderMaterial.prototype.setColor4 = function (name, value) {
  41682. this._checkUniform(name);
  41683. this._colors4[name] = value;
  41684. return this;
  41685. };
  41686. ShaderMaterial.prototype.setVector2 = function (name, value) {
  41687. this._checkUniform(name);
  41688. this._vectors2[name] = value;
  41689. return this;
  41690. };
  41691. ShaderMaterial.prototype.setVector3 = function (name, value) {
  41692. this._checkUniform(name);
  41693. this._vectors3[name] = value;
  41694. return this;
  41695. };
  41696. ShaderMaterial.prototype.setVector4 = function (name, value) {
  41697. this._checkUniform(name);
  41698. this._vectors4[name] = value;
  41699. return this;
  41700. };
  41701. ShaderMaterial.prototype.setMatrix = function (name, value) {
  41702. this._checkUniform(name);
  41703. this._matrices[name] = value;
  41704. return this;
  41705. };
  41706. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  41707. this._checkUniform(name);
  41708. this._matrices3x3[name] = value;
  41709. return this;
  41710. };
  41711. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  41712. this._checkUniform(name);
  41713. this._matrices2x2[name] = value;
  41714. return this;
  41715. };
  41716. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  41717. var scene = this.getScene();
  41718. var engine = scene.getEngine();
  41719. if (!this.checkReadyOnEveryCall) {
  41720. if (this._renderId === scene.getRenderId()) {
  41721. return true;
  41722. }
  41723. }
  41724. // Instances
  41725. var defines = [];
  41726. var fallbacks = new BABYLON.EffectFallbacks();
  41727. if (useInstances) {
  41728. defines.push("#define INSTANCES");
  41729. }
  41730. for (var index = 0; index < this._options.defines.length; index++) {
  41731. defines.push(this._options.defines[index]);
  41732. }
  41733. // Bones
  41734. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41735. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41736. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41737. fallbacks.addCPUSkinningFallback(0, mesh);
  41738. }
  41739. // Alpha test
  41740. if (engine.getAlphaTesting()) {
  41741. defines.push("#define ALPHATEST");
  41742. }
  41743. var previousEffect = this._effect;
  41744. var join = defines.join("\n");
  41745. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  41746. if (!this._effect.isReady()) {
  41747. return false;
  41748. }
  41749. if (previousEffect !== this._effect) {
  41750. scene.resetCachedMaterial();
  41751. }
  41752. this._renderId = scene.getRenderId();
  41753. return true;
  41754. };
  41755. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41756. var scene = this.getScene();
  41757. if (this._options.uniforms.indexOf("world") !== -1) {
  41758. this._effect.setMatrix("world", world);
  41759. }
  41760. if (this._options.uniforms.indexOf("worldView") !== -1) {
  41761. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  41762. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  41763. }
  41764. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  41765. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  41766. }
  41767. };
  41768. ShaderMaterial.prototype.bind = function (world, mesh) {
  41769. // Std values
  41770. this.bindOnlyWorldMatrix(world);
  41771. if (this.getScene().getCachedMaterial() !== this) {
  41772. if (this._options.uniforms.indexOf("view") !== -1) {
  41773. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  41774. }
  41775. if (this._options.uniforms.indexOf("projection") !== -1) {
  41776. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  41777. }
  41778. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  41779. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  41780. }
  41781. // Bones
  41782. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41783. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  41784. }
  41785. // Texture
  41786. for (var name in this._textures) {
  41787. this._effect.setTexture(name, this._textures[name]);
  41788. }
  41789. // Float
  41790. for (name in this._floats) {
  41791. this._effect.setFloat(name, this._floats[name]);
  41792. }
  41793. // Float s
  41794. for (name in this._floatsArrays) {
  41795. this._effect.setArray(name, this._floatsArrays[name]);
  41796. }
  41797. // Color3
  41798. for (name in this._colors3) {
  41799. this._effect.setColor3(name, this._colors3[name]);
  41800. }
  41801. // Color4
  41802. for (name in this._colors4) {
  41803. var color = this._colors4[name];
  41804. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  41805. }
  41806. // Vector2
  41807. for (name in this._vectors2) {
  41808. this._effect.setVector2(name, this._vectors2[name]);
  41809. }
  41810. // Vector3
  41811. for (name in this._vectors3) {
  41812. this._effect.setVector3(name, this._vectors3[name]);
  41813. }
  41814. // Vector4
  41815. for (name in this._vectors4) {
  41816. this._effect.setVector4(name, this._vectors4[name]);
  41817. }
  41818. // Matrix
  41819. for (name in this._matrices) {
  41820. this._effect.setMatrix(name, this._matrices[name]);
  41821. }
  41822. // Matrix 3x3
  41823. for (name in this._matrices3x3) {
  41824. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  41825. }
  41826. // Matrix 2x2
  41827. for (name in this._matrices2x2) {
  41828. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  41829. }
  41830. }
  41831. _super.prototype.bind.call(this, world, mesh);
  41832. };
  41833. ShaderMaterial.prototype.clone = function (name) {
  41834. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  41835. return newShaderMaterial;
  41836. };
  41837. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41838. if (forceDisposeTextures) {
  41839. for (var name in this._textures) {
  41840. this._textures[name].dispose();
  41841. }
  41842. }
  41843. this._textures = {};
  41844. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41845. };
  41846. ShaderMaterial.prototype.serialize = function () {
  41847. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41848. serializationObject.customType = "BABYLON.ShaderMaterial";
  41849. serializationObject.options = this._options;
  41850. serializationObject.shaderPath = this._shaderPath;
  41851. // Texture
  41852. serializationObject.textures = {};
  41853. for (var name in this._textures) {
  41854. serializationObject.textures[name] = this._textures[name].serialize();
  41855. }
  41856. // Float
  41857. serializationObject.floats = {};
  41858. for (name in this._floats) {
  41859. serializationObject.floats[name] = this._floats[name];
  41860. }
  41861. // Float s
  41862. serializationObject.floatArrays = {};
  41863. for (name in this._floatsArrays) {
  41864. serializationObject.floatArrays[name] = this._floatsArrays[name];
  41865. }
  41866. // Color3
  41867. serializationObject.colors3 = {};
  41868. for (name in this._colors3) {
  41869. serializationObject.colors3[name] = this._colors3[name].asArray();
  41870. }
  41871. // Color4
  41872. serializationObject.colors4 = {};
  41873. for (name in this._colors4) {
  41874. serializationObject.colors4[name] = this._colors4[name].asArray();
  41875. }
  41876. // Vector2
  41877. serializationObject.vectors2 = {};
  41878. for (name in this._vectors2) {
  41879. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  41880. }
  41881. // Vector3
  41882. serializationObject.vectors3 = {};
  41883. for (name in this._vectors3) {
  41884. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  41885. }
  41886. // Vector4
  41887. serializationObject.vectors4 = {};
  41888. for (name in this._vectors4) {
  41889. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  41890. }
  41891. // Matrix
  41892. serializationObject.matrices = {};
  41893. for (name in this._matrices) {
  41894. serializationObject.matrices[name] = this._matrices[name].asArray();
  41895. }
  41896. // Matrix 3x3
  41897. serializationObject.matrices3x3 = {};
  41898. for (name in this._matrices3x3) {
  41899. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  41900. }
  41901. // Matrix 2x2
  41902. serializationObject.matrices2x2 = {};
  41903. for (name in this._matrices2x2) {
  41904. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  41905. }
  41906. return serializationObject;
  41907. };
  41908. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  41909. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  41910. // Texture
  41911. for (var name in source.textures) {
  41912. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  41913. }
  41914. // Float
  41915. for (name in source.floats) {
  41916. material.setFloat(name, source.floats[name]);
  41917. }
  41918. // Float s
  41919. for (name in source.floatsArrays) {
  41920. material.setFloats(name, source.floatsArrays[name]);
  41921. }
  41922. // Color3
  41923. for (name in source.colors3) {
  41924. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  41925. }
  41926. // Color4
  41927. for (name in source.colors4) {
  41928. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  41929. }
  41930. // Vector2
  41931. for (name in source.vectors2) {
  41932. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  41933. }
  41934. // Vector3
  41935. for (name in source.vectors3) {
  41936. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  41937. }
  41938. // Vector4
  41939. for (name in source.vectors4) {
  41940. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  41941. }
  41942. // Matrix
  41943. for (name in source.matrices) {
  41944. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  41945. }
  41946. // Matrix 3x3
  41947. for (name in source.matrices3x3) {
  41948. material.setMatrix3x3(name, source.matrices3x3[name]);
  41949. }
  41950. // Matrix 2x2
  41951. for (name in source.matrices2x2) {
  41952. material.setMatrix2x2(name, source.matrices2x2[name]);
  41953. }
  41954. return material;
  41955. };
  41956. return ShaderMaterial;
  41957. })(BABYLON.Material);
  41958. BABYLON.ShaderMaterial = ShaderMaterial;
  41959. })(BABYLON || (BABYLON = {}));
  41960. var BABYLON;
  41961. (function (BABYLON) {
  41962. var Internals;
  41963. (function (Internals) {
  41964. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  41965. // All values and structures referenced from:
  41966. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  41967. var DDS_MAGIC = 0x20534444;
  41968. 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;
  41969. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  41970. 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;
  41971. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  41972. function FourCCToInt32(value) {
  41973. return value.charCodeAt(0) +
  41974. (value.charCodeAt(1) << 8) +
  41975. (value.charCodeAt(2) << 16) +
  41976. (value.charCodeAt(3) << 24);
  41977. }
  41978. function Int32ToFourCC(value) {
  41979. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  41980. }
  41981. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  41982. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  41983. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  41984. var headerLengthInt = 31; // The header length in 32 bit ints
  41985. // Offsets into the header array
  41986. var off_magic = 0;
  41987. var off_size = 1;
  41988. var off_flags = 2;
  41989. var off_height = 3;
  41990. var off_width = 4;
  41991. var off_mipmapCount = 7;
  41992. var off_pfFlags = 20;
  41993. var off_pfFourCC = 21;
  41994. var off_RGBbpp = 22;
  41995. var off_RMask = 23;
  41996. var off_GMask = 24;
  41997. var off_BMask = 25;
  41998. var off_AMask = 26;
  41999. var off_caps1 = 27;
  42000. var off_caps2 = 28;
  42001. ;
  42002. var DDSTools = (function () {
  42003. function DDSTools() {
  42004. }
  42005. DDSTools.GetDDSInfo = function (arrayBuffer) {
  42006. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  42007. var mipmapCount = 1;
  42008. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  42009. mipmapCount = Math.max(1, header[off_mipmapCount]);
  42010. }
  42011. return {
  42012. width: header[off_width],
  42013. height: header[off_height],
  42014. mipmapCount: mipmapCount,
  42015. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  42016. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  42017. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  42018. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  42019. };
  42020. };
  42021. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  42022. var byteArray = new Uint8Array(dataLength);
  42023. var srcData = new Uint8Array(arrayBuffer);
  42024. var index = 0;
  42025. for (var y = height - 1; y >= 0; y--) {
  42026. for (var x = 0; x < width; x++) {
  42027. var srcPos = dataOffset + (x + y * width) * 4;
  42028. byteArray[index + 2] = srcData[srcPos];
  42029. byteArray[index + 1] = srcData[srcPos + 1];
  42030. byteArray[index] = srcData[srcPos + 2];
  42031. byteArray[index + 3] = srcData[srcPos + 3];
  42032. index += 4;
  42033. }
  42034. }
  42035. return byteArray;
  42036. };
  42037. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  42038. var byteArray = new Uint8Array(dataLength);
  42039. var srcData = new Uint8Array(arrayBuffer);
  42040. var index = 0;
  42041. for (var y = height - 1; y >= 0; y--) {
  42042. for (var x = 0; x < width; x++) {
  42043. var srcPos = dataOffset + (x + y * width) * 3;
  42044. byteArray[index + 2] = srcData[srcPos];
  42045. byteArray[index + 1] = srcData[srcPos + 1];
  42046. byteArray[index] = srcData[srcPos + 2];
  42047. index += 3;
  42048. }
  42049. }
  42050. return byteArray;
  42051. };
  42052. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  42053. var byteArray = new Uint8Array(dataLength);
  42054. var srcData = new Uint8Array(arrayBuffer);
  42055. var index = 0;
  42056. for (var y = height - 1; y >= 0; y--) {
  42057. for (var x = 0; x < width; x++) {
  42058. var srcPos = dataOffset + (x + y * width);
  42059. byteArray[index] = srcData[srcPos];
  42060. index++;
  42061. }
  42062. }
  42063. return byteArray;
  42064. };
  42065. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  42066. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  42067. if (header[off_magic] != DDS_MAGIC) {
  42068. BABYLON.Tools.Error("Invalid magic number in DDS header");
  42069. return;
  42070. }
  42071. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  42072. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  42073. return;
  42074. }
  42075. if (info.isFourCC) {
  42076. fourCC = header[off_pfFourCC];
  42077. switch (fourCC) {
  42078. case FOURCC_DXT1:
  42079. blockBytes = 8;
  42080. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  42081. break;
  42082. case FOURCC_DXT3:
  42083. blockBytes = 16;
  42084. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  42085. break;
  42086. case FOURCC_DXT5:
  42087. blockBytes = 16;
  42088. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  42089. break;
  42090. default:
  42091. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  42092. return;
  42093. }
  42094. }
  42095. mipmapCount = 1;
  42096. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  42097. mipmapCount = Math.max(1, header[off_mipmapCount]);
  42098. }
  42099. var bpp = header[off_RGBbpp];
  42100. for (var face = 0; face < faces; face++) {
  42101. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  42102. width = header[off_width];
  42103. height = header[off_height];
  42104. dataOffset = header[off_size] + 4;
  42105. for (i = 0; i < mipmapCount; ++i) {
  42106. if (info.isRGB) {
  42107. if (bpp === 24) {
  42108. dataLength = width * height * 3;
  42109. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  42110. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  42111. }
  42112. else {
  42113. dataLength = width * height * 4;
  42114. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  42115. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  42116. }
  42117. }
  42118. else if (info.isLuminance) {
  42119. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  42120. var unpaddedRowSize = width;
  42121. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  42122. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  42123. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  42124. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  42125. }
  42126. else {
  42127. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  42128. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  42129. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  42130. }
  42131. dataOffset += dataLength;
  42132. width *= 0.5;
  42133. height *= 0.5;
  42134. width = Math.max(1.0, width);
  42135. height = Math.max(1.0, height);
  42136. }
  42137. }
  42138. };
  42139. return DDSTools;
  42140. })();
  42141. Internals.DDSTools = DDSTools;
  42142. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42143. })(BABYLON || (BABYLON = {}));
  42144. var BABYLON;
  42145. (function (BABYLON) {
  42146. var CannonJSPlugin = (function () {
  42147. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  42148. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  42149. if (iterations === void 0) { iterations = 10; }
  42150. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  42151. this.name = "CannonJSPlugin";
  42152. this._physicsMaterials = [];
  42153. this._fixedTimeStep = 1 / 60;
  42154. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  42155. this._currentCollisionGroup = 2;
  42156. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  42157. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  42158. this._tmpPosition = BABYLON.Vector3.Zero();
  42159. this._tmpQuaternion = new BABYLON.Quaternion();
  42160. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  42161. this._tmpDeltaRotation = new BABYLON.Quaternion();
  42162. this._tmpUnityRotation = new BABYLON.Quaternion();
  42163. if (!this.isSupported()) {
  42164. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  42165. return;
  42166. }
  42167. this.world = new CANNON.World();
  42168. this.world.broadphase = new CANNON.NaiveBroadphase();
  42169. this.world.solver.iterations = iterations;
  42170. }
  42171. CannonJSPlugin.prototype.setGravity = function (gravity) {
  42172. this.world.gravity.copy(gravity);
  42173. };
  42174. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  42175. this._fixedTimeStep = timeStep;
  42176. };
  42177. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  42178. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  42179. };
  42180. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  42181. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  42182. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  42183. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  42184. };
  42185. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  42186. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  42187. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  42188. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  42189. };
  42190. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  42191. //parent-child relationship. Does this impostor has a parent impostor?
  42192. if (impostor.parent) {
  42193. if (impostor.physicsBody) {
  42194. this.removePhysicsBody(impostor);
  42195. //TODO is that needed?
  42196. impostor.forceUpdate();
  42197. }
  42198. return;
  42199. }
  42200. //should a new body be created for this impostor?
  42201. if (impostor.isBodyInitRequired()) {
  42202. var shape = this._createShape(impostor);
  42203. //unregister events, if body is being changed
  42204. var oldBody = impostor.physicsBody;
  42205. if (oldBody) {
  42206. this.removePhysicsBody(impostor);
  42207. }
  42208. //create the body and material
  42209. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  42210. var bodyCreationObject = {
  42211. mass: impostor.getParam("mass"),
  42212. material: material
  42213. };
  42214. // A simple extend, in case native options were used.
  42215. var nativeOptions = impostor.getParam("nativeOptions");
  42216. for (var key in nativeOptions) {
  42217. if (nativeOptions.hasOwnProperty(key)) {
  42218. bodyCreationObject[key] = nativeOptions[key];
  42219. }
  42220. }
  42221. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  42222. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  42223. this.world.addEventListener("preStep", impostor.beforeStep);
  42224. this.world.addEventListener("postStep", impostor.afterStep);
  42225. impostor.physicsBody.addShape(shape);
  42226. this.world.add(impostor.physicsBody);
  42227. //try to keep the body moving in the right direction by taking old properties.
  42228. //Should be tested!
  42229. if (oldBody) {
  42230. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  42231. impostor.physicsBody[param].copy(oldBody[param]);
  42232. });
  42233. }
  42234. this._processChildMeshes(impostor);
  42235. }
  42236. //now update the body's transformation
  42237. this._updatePhysicsBodyTransformation(impostor);
  42238. };
  42239. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  42240. var _this = this;
  42241. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  42242. if (meshChildren.length) {
  42243. var processMesh = function (localPosition, mesh) {
  42244. var childImpostor = mesh.getPhysicsImpostor();
  42245. if (childImpostor) {
  42246. var parent = childImpostor.parent;
  42247. if (parent !== mainImpostor) {
  42248. var localPosition = mesh.position;
  42249. if (childImpostor.physicsBody) {
  42250. _this.removePhysicsBody(childImpostor);
  42251. childImpostor.physicsBody = null;
  42252. }
  42253. childImpostor.parent = mainImpostor;
  42254. childImpostor.resetUpdateFlags();
  42255. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  42256. //Add the mass of the children.
  42257. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  42258. }
  42259. }
  42260. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  42261. };
  42262. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  42263. }
  42264. };
  42265. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  42266. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  42267. this.world.removeEventListener("preStep", impostor.beforeStep);
  42268. this.world.removeEventListener("postStep", impostor.afterStep);
  42269. this.world.remove(impostor.physicsBody);
  42270. };
  42271. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  42272. var mainBody = impostorJoint.mainImpostor.physicsBody;
  42273. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  42274. if (!mainBody || !connectedBody) {
  42275. return;
  42276. }
  42277. var constraint;
  42278. var jointData = impostorJoint.joint.jointData;
  42279. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  42280. var constraintData = {
  42281. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  42282. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  42283. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  42284. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  42285. maxForce: jointData.nativeParams.maxForce,
  42286. collideConnected: !!jointData.collision
  42287. };
  42288. //Not needed, Cannon has a collideConnected flag
  42289. /*if (!jointData.collision) {
  42290. //add 1st body to a collision group of its own, if it is not in 1
  42291. if (mainBody.collisionFilterGroup === 1) {
  42292. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  42293. this._currentCollisionGroup <<= 1;
  42294. }
  42295. if (connectedBody.collisionFilterGroup === 1) {
  42296. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  42297. this._currentCollisionGroup <<= 1;
  42298. }
  42299. //add their mask to the collisionFilterMask of each other:
  42300. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  42301. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  42302. }*/
  42303. switch (impostorJoint.joint.type) {
  42304. case BABYLON.PhysicsJoint.HingeJoint:
  42305. case BABYLON.PhysicsJoint.Hinge2Joint:
  42306. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  42307. break;
  42308. case BABYLON.PhysicsJoint.DistanceJoint:
  42309. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  42310. break;
  42311. case BABYLON.PhysicsJoint.SpringJoint:
  42312. var springData = jointData;
  42313. constraint = new CANNON.Spring(mainBody, connectedBody, {
  42314. restLength: springData.length,
  42315. stiffness: springData.stiffness,
  42316. damping: springData.damping,
  42317. localAnchorA: constraintData.pivotA,
  42318. localAnchorB: constraintData.pivotB
  42319. });
  42320. break;
  42321. case BABYLON.PhysicsJoint.PointToPointJoint:
  42322. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42323. default:
  42324. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  42325. break;
  42326. }
  42327. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  42328. constraint.collideConnected = !!jointData.collision;
  42329. impostorJoint.joint.physicsJoint = constraint;
  42330. //don't add spring as constraint, as it is not one.
  42331. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  42332. this.world.addConstraint(constraint);
  42333. }
  42334. else {
  42335. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  42336. constraint.applyForce();
  42337. });
  42338. }
  42339. };
  42340. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42341. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  42342. };
  42343. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  42344. var index;
  42345. var mat;
  42346. for (index = 0; index < this._physicsMaterials.length; index++) {
  42347. mat = this._physicsMaterials[index];
  42348. if (mat.friction === friction && mat.restitution === restitution) {
  42349. return mat;
  42350. }
  42351. }
  42352. var currentMat = new CANNON.Material(name);
  42353. currentMat.friction = friction;
  42354. currentMat.restitution = restitution;
  42355. this._physicsMaterials.push(currentMat);
  42356. return currentMat;
  42357. };
  42358. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  42359. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  42360. };
  42361. CannonJSPlugin.prototype._createShape = function (impostor) {
  42362. var object = impostor.object;
  42363. var returnValue;
  42364. var extendSize = impostor.getObjectExtendSize();
  42365. switch (impostor.type) {
  42366. case BABYLON.PhysicsEngine.SphereImpostor:
  42367. var radiusX = extendSize.x;
  42368. var radiusY = extendSize.y;
  42369. var radiusZ = extendSize.z;
  42370. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  42371. break;
  42372. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  42373. case BABYLON.PhysicsImpostor.CylinderImpostor:
  42374. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  42375. break;
  42376. case BABYLON.PhysicsImpostor.BoxImpostor:
  42377. var box = extendSize.scale(0.5);
  42378. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  42379. break;
  42380. case BABYLON.PhysicsImpostor.PlaneImpostor:
  42381. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  42382. returnValue = new CANNON.Plane();
  42383. break;
  42384. case BABYLON.PhysicsImpostor.MeshImpostor:
  42385. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  42386. var rawFaces = object.getIndices ? object.getIndices() : [];
  42387. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  42388. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  42389. break;
  42390. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  42391. returnValue = this._createHeightmap(object);
  42392. break;
  42393. case BABYLON.PhysicsImpostor.ParticleImpostor:
  42394. returnValue = new CANNON.Particle();
  42395. break;
  42396. }
  42397. return returnValue;
  42398. };
  42399. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  42400. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42401. var matrix = [];
  42402. //For now pointDepth will not be used and will be automatically calculated.
  42403. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  42404. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  42405. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  42406. var elementSize = dim * 2 / arraySize;
  42407. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  42408. for (var i = 0; i < pos.length; i = i + 3) {
  42409. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  42410. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  42411. var y = pos[i + 1] + minY;
  42412. if (!matrix[x]) {
  42413. matrix[x] = [];
  42414. }
  42415. if (!matrix[x][z]) {
  42416. matrix[x][z] = y;
  42417. }
  42418. matrix[x][z] = Math.max(y, matrix[x][z]);
  42419. }
  42420. for (var x = 0; x <= arraySize; ++x) {
  42421. if (!matrix[x]) {
  42422. var loc = 1;
  42423. while (!matrix[(x + loc) % arraySize]) {
  42424. loc++;
  42425. }
  42426. matrix[x] = matrix[(x + loc) % arraySize].slice();
  42427. }
  42428. for (var z = 0; z <= arraySize; ++z) {
  42429. if (!matrix[x][z]) {
  42430. var loc = 1;
  42431. var newValue;
  42432. while (newValue === undefined) {
  42433. newValue = matrix[x][(z + loc++) % arraySize];
  42434. }
  42435. matrix[x][z] = newValue;
  42436. }
  42437. }
  42438. }
  42439. var shape = new CANNON.Heightfield(matrix, {
  42440. elementSize: elementSize
  42441. });
  42442. //For future reference, needed for body transformation
  42443. shape.minY = minY;
  42444. return shape;
  42445. };
  42446. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  42447. var object = impostor.object;
  42448. //make sure it is updated...
  42449. object.computeWorldMatrix && object.computeWorldMatrix(true);
  42450. // The delta between the mesh position and the mesh bounding box center
  42451. var center = impostor.getObjectCenter();
  42452. var extendSize = impostor.getObjectExtendSize();
  42453. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  42454. this._tmpPosition.copyFrom(center);
  42455. var quaternion = object.rotationQuaternion;
  42456. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  42457. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  42458. //-90 DEG in X, precalculated
  42459. quaternion = quaternion.multiply(this._minus90X);
  42460. //Invert! (Precalculated, 90 deg in X)
  42461. //No need to clone. this will never change.
  42462. impostor.setDeltaRotation(this._plus90X);
  42463. }
  42464. //If it is a heightfield, if should be centered.
  42465. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  42466. var mesh = object;
  42467. //calculate the correct body position:
  42468. var rotationQuaternion = mesh.rotationQuaternion;
  42469. mesh.rotationQuaternion = this._tmpUnityRotation;
  42470. mesh.computeWorldMatrix(true);
  42471. //get original center with no rotation
  42472. var c = center.clone();
  42473. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  42474. //rotation is back
  42475. mesh.rotationQuaternion = rotationQuaternion;
  42476. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  42477. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  42478. mesh.setPivotMatrix(p);
  42479. mesh.computeWorldMatrix(true);
  42480. //calculate the translation
  42481. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  42482. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  42483. //add it inverted to the delta
  42484. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  42485. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  42486. mesh.setPivotMatrix(oldPivot);
  42487. mesh.computeWorldMatrix(true);
  42488. }
  42489. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  42490. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  42491. this._tmpPosition.copyFrom(object.position);
  42492. }
  42493. impostor.setDeltaPosition(this._tmpDeltaPosition);
  42494. //Now update the impostor object
  42495. impostor.physicsBody.position.copy(this._tmpPosition);
  42496. impostor.physicsBody.quaternion.copy(quaternion);
  42497. };
  42498. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42499. impostor.object.position.copyFrom(impostor.physicsBody.position);
  42500. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  42501. };
  42502. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42503. impostor.physicsBody.position.copy(newPosition);
  42504. impostor.physicsBody.quaternion.copy(newRotation);
  42505. };
  42506. CannonJSPlugin.prototype.isSupported = function () {
  42507. return window.CANNON !== undefined;
  42508. };
  42509. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42510. impostor.physicsBody.velocity.copy(velocity);
  42511. };
  42512. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42513. impostor.physicsBody.angularVelocity.copy(velocity);
  42514. };
  42515. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42516. var v = impostor.physicsBody.velocity;
  42517. if (!v)
  42518. return null;
  42519. return new BABYLON.Vector3(v.x, v.y, v.z);
  42520. };
  42521. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42522. var v = impostor.physicsBody.angularVelocity;
  42523. if (!v)
  42524. return null;
  42525. return new BABYLON.Vector3(v.x, v.y, v.z);
  42526. };
  42527. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42528. impostor.physicsBody.mass = mass;
  42529. impostor.physicsBody.updateMassProperties();
  42530. };
  42531. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  42532. impostor.physicsBody.sleep();
  42533. };
  42534. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  42535. impostor.physicsBody.wakeUp();
  42536. };
  42537. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42538. joint.physicsJoint.distance = maxDistance;
  42539. };
  42540. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  42541. if (!motorIndex) {
  42542. joint.physicsJoint.enableMotor();
  42543. }
  42544. };
  42545. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  42546. if (!motorIndex) {
  42547. joint.physicsJoint.disableMotor();
  42548. }
  42549. };
  42550. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42551. if (!motorIndex) {
  42552. joint.physicsJoint.enableMotor();
  42553. joint.physicsJoint.setMotorSpeed(speed);
  42554. if (maxForce) {
  42555. this.setLimit(joint, maxForce);
  42556. }
  42557. }
  42558. };
  42559. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  42560. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  42561. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  42562. };
  42563. CannonJSPlugin.prototype.dispose = function () {
  42564. //nothing to do, actually.
  42565. };
  42566. return CannonJSPlugin;
  42567. })();
  42568. BABYLON.CannonJSPlugin = CannonJSPlugin;
  42569. })(BABYLON || (BABYLON = {}));
  42570. var BABYLON;
  42571. (function (BABYLON) {
  42572. var OimoJSPlugin = (function () {
  42573. function OimoJSPlugin(iterations) {
  42574. this.name = "OimoJSPlugin";
  42575. this._tmpImpostorsArray = [];
  42576. this._tmpPositionVector = BABYLON.Vector3.Zero();
  42577. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  42578. this.world.clear();
  42579. //making sure no stats are calculated
  42580. this.world.isNoStat = true;
  42581. }
  42582. OimoJSPlugin.prototype.setGravity = function (gravity) {
  42583. this.world.gravity.copy(gravity);
  42584. };
  42585. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  42586. this.world.timeStep = timeStep;
  42587. };
  42588. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  42589. var _this = this;
  42590. impostors.forEach(function (impostor) {
  42591. impostor.beforeStep();
  42592. });
  42593. this.world.step();
  42594. impostors.forEach(function (impostor) {
  42595. impostor.afterStep();
  42596. //update the ordered impostors array
  42597. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  42598. });
  42599. //check for collisions
  42600. var contact = this.world.contacts;
  42601. while (contact !== null) {
  42602. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  42603. contact = contact.next;
  42604. continue;
  42605. }
  42606. //is this body colliding with any other? get the impostor
  42607. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  42608. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  42609. if (!mainImpostor || !collidingImpostor) {
  42610. contact = contact.next;
  42611. continue;
  42612. }
  42613. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  42614. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  42615. contact = contact.next;
  42616. }
  42617. };
  42618. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  42619. var mass = impostor.physicsBody.massInfo.mass;
  42620. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  42621. };
  42622. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  42623. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  42624. this.applyImpulse(impostor, force, contactPoint);
  42625. };
  42626. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  42627. var _this = this;
  42628. //parent-child relationship. Does this impostor has a parent impostor?
  42629. if (impostor.parent) {
  42630. if (impostor.physicsBody) {
  42631. this.removePhysicsBody(impostor);
  42632. //TODO is that needed?
  42633. impostor.forceUpdate();
  42634. }
  42635. return;
  42636. }
  42637. if (impostor.isBodyInitRequired()) {
  42638. var bodyConfig = {
  42639. name: impostor.uniqueId,
  42640. //Oimo must have mass, also for static objects.
  42641. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  42642. size: [],
  42643. type: [],
  42644. pos: [],
  42645. rot: [],
  42646. move: impostor.getParam("mass") !== 0,
  42647. //Supporting older versions of Oimo
  42648. world: this.world
  42649. };
  42650. var impostors = [impostor];
  42651. function addToArray(parent) {
  42652. if (!parent.getChildMeshes)
  42653. return;
  42654. parent.getChildMeshes().forEach(function (m) {
  42655. if (m.physicsImpostor) {
  42656. impostors.push(m.physicsImpostor);
  42657. m.physicsImpostor._init();
  42658. }
  42659. });
  42660. }
  42661. addToArray(impostor.object);
  42662. function checkWithEpsilon(value) {
  42663. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  42664. }
  42665. impostors.forEach(function (i) {
  42666. //get the correct bounding box
  42667. var oldQuaternion = i.object.rotationQuaternion;
  42668. var rot = new OIMO.Euler().setFromQuaternion({
  42669. x: impostor.object.rotationQuaternion.x,
  42670. y: impostor.object.rotationQuaternion.y,
  42671. z: impostor.object.rotationQuaternion.z,
  42672. s: impostor.object.rotationQuaternion.w
  42673. });
  42674. var extendSize = i.getObjectExtendSize();
  42675. if (i === impostor) {
  42676. var center = impostor.getObjectCenter();
  42677. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  42678. //Can also use Array.prototype.push.apply
  42679. bodyConfig.pos.push(center.x);
  42680. bodyConfig.pos.push(center.y);
  42681. bodyConfig.pos.push(center.z);
  42682. //tmp solution
  42683. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  42684. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  42685. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  42686. }
  42687. else {
  42688. bodyConfig.pos.push(i.object.position.x);
  42689. bodyConfig.pos.push(i.object.position.y);
  42690. bodyConfig.pos.push(i.object.position.z);
  42691. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  42692. bodyConfig.rot.push(0);
  42693. bodyConfig.rot.push(0);
  42694. bodyConfig.rot.push(0);
  42695. }
  42696. // register mesh
  42697. switch (i.type) {
  42698. case BABYLON.PhysicsImpostor.ParticleImpostor:
  42699. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  42700. case BABYLON.PhysicsImpostor.SphereImpostor:
  42701. var radiusX = extendSize.x;
  42702. var radiusY = extendSize.y;
  42703. var radiusZ = extendSize.z;
  42704. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  42705. bodyConfig.type.push('sphere');
  42706. //due to the way oimo works with compounds, add 3 times
  42707. bodyConfig.size.push(size);
  42708. bodyConfig.size.push(size);
  42709. bodyConfig.size.push(size);
  42710. break;
  42711. case BABYLON.PhysicsImpostor.CylinderImpostor:
  42712. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  42713. var sizeY = checkWithEpsilon(extendSize.y);
  42714. bodyConfig.type.push('cylinder');
  42715. bodyConfig.size.push(sizeX);
  42716. bodyConfig.size.push(sizeY);
  42717. //due to the way oimo works with compounds, add one more value.
  42718. bodyConfig.size.push(sizeY);
  42719. break;
  42720. case BABYLON.PhysicsImpostor.PlaneImpostor:
  42721. case BABYLON.PhysicsImpostor.BoxImpostor:
  42722. default:
  42723. var sizeX = checkWithEpsilon(extendSize.x);
  42724. var sizeY = checkWithEpsilon(extendSize.y);
  42725. var sizeZ = checkWithEpsilon(extendSize.z);
  42726. bodyConfig.type.push('box');
  42727. bodyConfig.size.push(sizeX);
  42728. bodyConfig.size.push(sizeY);
  42729. bodyConfig.size.push(sizeZ);
  42730. break;
  42731. }
  42732. //actually not needed, but hey...
  42733. i.object.rotationQuaternion = oldQuaternion;
  42734. });
  42735. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  42736. }
  42737. else {
  42738. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  42739. }
  42740. impostor.setDeltaPosition(this._tmpPositionVector);
  42741. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  42742. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  42743. };
  42744. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  42745. //impostor.physicsBody.dispose();
  42746. //Same as : (older oimo versions)
  42747. this.world.removeRigidBody(impostor.physicsBody);
  42748. };
  42749. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  42750. var mainBody = impostorJoint.mainImpostor.physicsBody;
  42751. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  42752. if (!mainBody || !connectedBody) {
  42753. return;
  42754. }
  42755. var jointData = impostorJoint.joint.jointData;
  42756. var options = jointData.nativeParams || {};
  42757. var type;
  42758. var nativeJointData = {
  42759. body1: mainBody,
  42760. body2: connectedBody,
  42761. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  42762. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  42763. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  42764. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  42765. min: options.min,
  42766. max: options.max,
  42767. collision: options.collision || jointData.collision,
  42768. spring: options.spring,
  42769. //supporting older version of Oimo
  42770. world: this.world
  42771. };
  42772. switch (impostorJoint.joint.type) {
  42773. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42774. type = "jointBall";
  42775. break;
  42776. case BABYLON.PhysicsJoint.SpringJoint:
  42777. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  42778. var springData = jointData;
  42779. nativeJointData.min = springData.length || nativeJointData.min;
  42780. //Max should also be set, just make sure it is at least min
  42781. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  42782. case BABYLON.PhysicsJoint.DistanceJoint:
  42783. type = "jointDistance";
  42784. nativeJointData.max = jointData.maxDistance;
  42785. break;
  42786. case BABYLON.PhysicsJoint.PrismaticJoint:
  42787. type = "jointPrisme";
  42788. break;
  42789. case BABYLON.PhysicsJoint.SliderJoint:
  42790. type = "jointSlide";
  42791. break;
  42792. case BABYLON.PhysicsJoint.WheelJoint:
  42793. type = "jointWheel";
  42794. break;
  42795. case BABYLON.PhysicsJoint.HingeJoint:
  42796. default:
  42797. type = "jointHinge";
  42798. break;
  42799. }
  42800. nativeJointData.type = type;
  42801. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  42802. };
  42803. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42804. //Bug in Oimo prevents us from disposing a joint in the playground
  42805. //joint.joint.physicsJoint.dispose();
  42806. //So we will bruteforce it!
  42807. try {
  42808. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  42809. }
  42810. catch (e) {
  42811. BABYLON.Tools.Warn(e);
  42812. }
  42813. };
  42814. OimoJSPlugin.prototype.isSupported = function () {
  42815. return OIMO !== undefined;
  42816. };
  42817. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42818. if (!impostor.physicsBody.sleeping) {
  42819. //TODO check that
  42820. if (impostor.physicsBody.shapes.next) {
  42821. var parentShape = this._getLastShape(impostor.physicsBody);
  42822. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  42823. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  42824. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  42825. }
  42826. else {
  42827. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  42828. }
  42829. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  42830. }
  42831. };
  42832. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42833. var body = impostor.physicsBody;
  42834. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  42835. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  42836. body.syncShapes();
  42837. body.awake();
  42838. };
  42839. OimoJSPlugin.prototype._getLastShape = function (body) {
  42840. var lastShape = body.shapes;
  42841. while (lastShape.next) {
  42842. lastShape = lastShape.next;
  42843. }
  42844. return lastShape;
  42845. };
  42846. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42847. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  42848. };
  42849. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42850. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  42851. };
  42852. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42853. var v = impostor.physicsBody.linearVelocity;
  42854. if (!v)
  42855. return null;
  42856. return new BABYLON.Vector3(v.x, v.y, v.z);
  42857. };
  42858. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42859. var v = impostor.physicsBody.angularVelocity;
  42860. if (!v)
  42861. return null;
  42862. return new BABYLON.Vector3(v.x, v.y, v.z);
  42863. };
  42864. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42865. var staticBody = mass === 0;
  42866. //this will actually set the body's density and not its mass.
  42867. //But this is how oimo treats the mass variable.
  42868. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  42869. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  42870. };
  42871. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  42872. impostor.physicsBody.sleep();
  42873. };
  42874. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  42875. impostor.physicsBody.awake();
  42876. };
  42877. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42878. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  42879. if (minDistance !== void 0) {
  42880. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  42881. }
  42882. };
  42883. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42884. //TODO separate rotational and transational motors.
  42885. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42886. if (motor) {
  42887. motor.setMotor(speed, maxForce);
  42888. }
  42889. };
  42890. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  42891. //TODO separate rotational and transational motors.
  42892. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42893. if (motor) {
  42894. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  42895. }
  42896. };
  42897. OimoJSPlugin.prototype.dispose = function () {
  42898. this.world.clear();
  42899. };
  42900. return OimoJSPlugin;
  42901. })();
  42902. BABYLON.OimoJSPlugin = OimoJSPlugin;
  42903. })(BABYLON || (BABYLON = {}));
  42904. var BABYLON;
  42905. (function (BABYLON) {
  42906. var DisplayPassPostProcess = (function (_super) {
  42907. __extends(DisplayPassPostProcess, _super);
  42908. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  42909. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  42910. }
  42911. return DisplayPassPostProcess;
  42912. })(BABYLON.PostProcess);
  42913. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  42914. })(BABYLON || (BABYLON = {}));
  42915. var BABYLON;
  42916. (function (BABYLON) {
  42917. var SimplificationSettings = (function () {
  42918. function SimplificationSettings(quality, distance, optimizeMesh) {
  42919. this.quality = quality;
  42920. this.distance = distance;
  42921. this.optimizeMesh = optimizeMesh;
  42922. }
  42923. return SimplificationSettings;
  42924. })();
  42925. BABYLON.SimplificationSettings = SimplificationSettings;
  42926. var SimplificationQueue = (function () {
  42927. function SimplificationQueue() {
  42928. this.running = false;
  42929. this._simplificationArray = [];
  42930. }
  42931. SimplificationQueue.prototype.addTask = function (task) {
  42932. this._simplificationArray.push(task);
  42933. };
  42934. SimplificationQueue.prototype.executeNext = function () {
  42935. var task = this._simplificationArray.pop();
  42936. if (task) {
  42937. this.running = true;
  42938. this.runSimplification(task);
  42939. }
  42940. else {
  42941. this.running = false;
  42942. }
  42943. };
  42944. SimplificationQueue.prototype.runSimplification = function (task) {
  42945. var _this = this;
  42946. if (task.parallelProcessing) {
  42947. //parallel simplifier
  42948. task.settings.forEach(function (setting) {
  42949. var simplifier = _this.getSimplifier(task);
  42950. simplifier.simplify(setting, function (newMesh) {
  42951. task.mesh.addLODLevel(setting.distance, newMesh);
  42952. newMesh.isVisible = true;
  42953. //check if it is the last
  42954. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  42955. //all done, run the success callback.
  42956. task.successCallback();
  42957. }
  42958. _this.executeNext();
  42959. });
  42960. });
  42961. }
  42962. else {
  42963. //single simplifier.
  42964. var simplifier = this.getSimplifier(task);
  42965. var runDecimation = function (setting, callback) {
  42966. simplifier.simplify(setting, function (newMesh) {
  42967. task.mesh.addLODLevel(setting.distance, newMesh);
  42968. newMesh.isVisible = true;
  42969. //run the next quality level
  42970. callback();
  42971. });
  42972. };
  42973. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  42974. runDecimation(task.settings[loop.index], function () {
  42975. loop.executeNext();
  42976. });
  42977. }, function () {
  42978. //execution ended, run the success callback.
  42979. if (task.successCallback) {
  42980. task.successCallback();
  42981. }
  42982. _this.executeNext();
  42983. });
  42984. }
  42985. };
  42986. SimplificationQueue.prototype.getSimplifier = function (task) {
  42987. switch (task.simplificationType) {
  42988. case SimplificationType.QUADRATIC:
  42989. default:
  42990. return new QuadraticErrorSimplification(task.mesh);
  42991. }
  42992. };
  42993. return SimplificationQueue;
  42994. })();
  42995. BABYLON.SimplificationQueue = SimplificationQueue;
  42996. /**
  42997. * The implemented types of simplification.
  42998. * At the moment only Quadratic Error Decimation is implemented.
  42999. */
  43000. (function (SimplificationType) {
  43001. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  43002. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  43003. var SimplificationType = BABYLON.SimplificationType;
  43004. var DecimationTriangle = (function () {
  43005. function DecimationTriangle(vertices) {
  43006. this.vertices = vertices;
  43007. this.error = new Array(4);
  43008. this.deleted = false;
  43009. this.isDirty = false;
  43010. this.deletePending = false;
  43011. this.borderFactor = 0;
  43012. }
  43013. return DecimationTriangle;
  43014. })();
  43015. BABYLON.DecimationTriangle = DecimationTriangle;
  43016. var DecimationVertex = (function () {
  43017. function DecimationVertex(position, id) {
  43018. this.position = position;
  43019. this.id = id;
  43020. this.isBorder = true;
  43021. this.q = new QuadraticMatrix();
  43022. this.triangleCount = 0;
  43023. this.triangleStart = 0;
  43024. this.originalOffsets = [];
  43025. }
  43026. DecimationVertex.prototype.updatePosition = function (newPosition) {
  43027. this.position.copyFrom(newPosition);
  43028. };
  43029. return DecimationVertex;
  43030. })();
  43031. BABYLON.DecimationVertex = DecimationVertex;
  43032. var QuadraticMatrix = (function () {
  43033. function QuadraticMatrix(data) {
  43034. this.data = new Array(10);
  43035. for (var i = 0; i < 10; ++i) {
  43036. if (data && data[i]) {
  43037. this.data[i] = data[i];
  43038. }
  43039. else {
  43040. this.data[i] = 0;
  43041. }
  43042. }
  43043. }
  43044. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  43045. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  43046. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  43047. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  43048. return det;
  43049. };
  43050. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  43051. for (var i = 0; i < 10; ++i) {
  43052. this.data[i] += matrix.data[i];
  43053. }
  43054. };
  43055. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  43056. for (var i = 0; i < 10; ++i) {
  43057. this.data[i] += data[i];
  43058. }
  43059. };
  43060. QuadraticMatrix.prototype.add = function (matrix) {
  43061. var m = new QuadraticMatrix();
  43062. for (var i = 0; i < 10; ++i) {
  43063. m.data[i] = this.data[i] + matrix.data[i];
  43064. }
  43065. return m;
  43066. };
  43067. QuadraticMatrix.FromData = function (a, b, c, d) {
  43068. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  43069. };
  43070. //returning an array to avoid garbage collection
  43071. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  43072. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  43073. };
  43074. return QuadraticMatrix;
  43075. })();
  43076. BABYLON.QuadraticMatrix = QuadraticMatrix;
  43077. var Reference = (function () {
  43078. function Reference(vertexId, triangleId) {
  43079. this.vertexId = vertexId;
  43080. this.triangleId = triangleId;
  43081. }
  43082. return Reference;
  43083. })();
  43084. BABYLON.Reference = Reference;
  43085. /**
  43086. * An implementation of the Quadratic Error simplification algorithm.
  43087. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  43088. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  43089. * @author RaananW
  43090. */
  43091. var QuadraticErrorSimplification = (function () {
  43092. function QuadraticErrorSimplification(_mesh) {
  43093. this._mesh = _mesh;
  43094. this.initialized = false;
  43095. this.syncIterations = 5000;
  43096. this.aggressiveness = 7;
  43097. this.decimationIterations = 100;
  43098. this.boundingBoxEpsilon = BABYLON.Epsilon;
  43099. }
  43100. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  43101. var _this = this;
  43102. this.initDecimatedMesh();
  43103. //iterating through the submeshes array, one after the other.
  43104. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  43105. _this.initWithMesh(loop.index, function () {
  43106. _this.runDecimation(settings, loop.index, function () {
  43107. loop.executeNext();
  43108. });
  43109. }, settings.optimizeMesh);
  43110. }, function () {
  43111. setTimeout(function () {
  43112. successCallback(_this._reconstructedMesh);
  43113. }, 0);
  43114. });
  43115. };
  43116. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  43117. var _this = this;
  43118. var gCount = 0;
  43119. triangle.vertices.forEach(function (vertex) {
  43120. var count = 0;
  43121. var vPos = vertex.position;
  43122. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  43123. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  43124. ++count;
  43125. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  43126. ++count;
  43127. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  43128. ++count;
  43129. if (count > 1) {
  43130. ++gCount;
  43131. }
  43132. ;
  43133. });
  43134. if (gCount > 1) {
  43135. console.log(triangle, gCount);
  43136. }
  43137. return gCount > 1;
  43138. };
  43139. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  43140. var _this = this;
  43141. var targetCount = ~~(this.triangles.length * settings.quality);
  43142. var deletedTriangles = 0;
  43143. var triangleCount = this.triangles.length;
  43144. var iterationFunction = function (iteration, callback) {
  43145. setTimeout(function () {
  43146. if (iteration % 5 === 0) {
  43147. _this.updateMesh(iteration === 0);
  43148. }
  43149. for (var i = 0; i < _this.triangles.length; ++i) {
  43150. _this.triangles[i].isDirty = false;
  43151. }
  43152. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  43153. var trianglesIterator = function (i) {
  43154. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  43155. var t = _this.triangles[tIdx];
  43156. if (!t)
  43157. return;
  43158. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  43159. return;
  43160. }
  43161. for (var j = 0; j < 3; ++j) {
  43162. if (t.error[j] < threshold) {
  43163. var deleted0 = [];
  43164. var deleted1 = [];
  43165. var v0 = t.vertices[j];
  43166. var v1 = t.vertices[(j + 1) % 3];
  43167. if (v0.isBorder || v1.isBorder)
  43168. continue;
  43169. var p = BABYLON.Vector3.Zero();
  43170. var n = BABYLON.Vector3.Zero();
  43171. var uv = BABYLON.Vector2.Zero();
  43172. var color = new BABYLON.Color4(0, 0, 0, 1);
  43173. _this.calculateError(v0, v1, p, n, uv, color);
  43174. var delTr = [];
  43175. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  43176. continue;
  43177. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  43178. continue;
  43179. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  43180. continue;
  43181. var uniqueArray = [];
  43182. delTr.forEach(function (deletedT) {
  43183. if (uniqueArray.indexOf(deletedT) === -1) {
  43184. deletedT.deletePending = true;
  43185. uniqueArray.push(deletedT);
  43186. }
  43187. });
  43188. if (uniqueArray.length % 2 !== 0) {
  43189. continue;
  43190. }
  43191. v0.q = v1.q.add(v0.q);
  43192. v0.updatePosition(p);
  43193. var tStart = _this.references.length;
  43194. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  43195. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  43196. var tCount = _this.references.length - tStart;
  43197. if (tCount <= v0.triangleCount) {
  43198. if (tCount) {
  43199. for (var c = 0; c < tCount; c++) {
  43200. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  43201. }
  43202. }
  43203. }
  43204. else {
  43205. v0.triangleStart = tStart;
  43206. }
  43207. v0.triangleCount = tCount;
  43208. break;
  43209. }
  43210. }
  43211. };
  43212. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  43213. }, 0);
  43214. };
  43215. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  43216. if (triangleCount - deletedTriangles <= targetCount)
  43217. loop.breakLoop();
  43218. else {
  43219. iterationFunction(loop.index, function () {
  43220. loop.executeNext();
  43221. });
  43222. }
  43223. }, function () {
  43224. setTimeout(function () {
  43225. //reconstruct this part of the mesh
  43226. _this.reconstructMesh(submeshIndex);
  43227. successCallback();
  43228. }, 0);
  43229. });
  43230. };
  43231. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  43232. var _this = this;
  43233. this.vertices = [];
  43234. this.triangles = [];
  43235. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43236. var indices = this._mesh.getIndices();
  43237. var submesh = this._mesh.subMeshes[submeshIndex];
  43238. var findInVertices = function (positionToSearch) {
  43239. if (optimizeMesh) {
  43240. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  43241. if (_this.vertices[ii].position.equals(positionToSearch)) {
  43242. return _this.vertices[ii];
  43243. }
  43244. }
  43245. }
  43246. return null;
  43247. };
  43248. var vertexReferences = [];
  43249. var vertexInit = function (i) {
  43250. var offset = i + submesh.verticesStart;
  43251. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  43252. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  43253. vertex.originalOffsets.push(offset);
  43254. if (vertex.id === _this.vertices.length) {
  43255. _this.vertices.push(vertex);
  43256. }
  43257. vertexReferences.push(vertex.id);
  43258. };
  43259. //var totalVertices = mesh.getTotalVertices();
  43260. var totalVertices = submesh.verticesCount;
  43261. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  43262. var indicesInit = function (i) {
  43263. var offset = (submesh.indexStart / 3) + i;
  43264. var pos = (offset * 3);
  43265. var i0 = indices[pos + 0];
  43266. var i1 = indices[pos + 1];
  43267. var i2 = indices[pos + 2];
  43268. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  43269. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  43270. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  43271. var triangle = new DecimationTriangle([v0, v1, v2]);
  43272. triangle.originalOffset = pos;
  43273. _this.triangles.push(triangle);
  43274. };
  43275. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  43276. _this.init(callback);
  43277. });
  43278. });
  43279. };
  43280. QuadraticErrorSimplification.prototype.init = function (callback) {
  43281. var _this = this;
  43282. var triangleInit1 = function (i) {
  43283. var t = _this.triangles[i];
  43284. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  43285. for (var j = 0; j < 3; j++) {
  43286. 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))));
  43287. }
  43288. };
  43289. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  43290. var triangleInit2 = function (i) {
  43291. var t = _this.triangles[i];
  43292. for (var j = 0; j < 3; ++j) {
  43293. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  43294. }
  43295. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  43296. };
  43297. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  43298. _this.initialized = true;
  43299. callback();
  43300. });
  43301. });
  43302. };
  43303. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  43304. var newTriangles = [];
  43305. var i;
  43306. for (i = 0; i < this.vertices.length; ++i) {
  43307. this.vertices[i].triangleCount = 0;
  43308. }
  43309. var t;
  43310. var j;
  43311. for (i = 0; i < this.triangles.length; ++i) {
  43312. if (!this.triangles[i].deleted) {
  43313. t = this.triangles[i];
  43314. for (j = 0; j < 3; ++j) {
  43315. t.vertices[j].triangleCount = 1;
  43316. }
  43317. newTriangles.push(t);
  43318. }
  43319. }
  43320. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  43321. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  43322. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  43323. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  43324. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43325. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43326. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43327. var vertexCount = 0;
  43328. for (i = 0; i < this.vertices.length; ++i) {
  43329. var vertex = this.vertices[i];
  43330. vertex.id = vertexCount;
  43331. if (vertex.triangleCount) {
  43332. vertex.originalOffsets.forEach(function (originalOffset) {
  43333. newPositionData.push(vertex.position.x);
  43334. newPositionData.push(vertex.position.y);
  43335. newPositionData.push(vertex.position.z);
  43336. newNormalData.push(normalData[originalOffset * 3]);
  43337. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  43338. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  43339. if (uvs && uvs.length) {
  43340. newUVsData.push(uvs[(originalOffset * 2)]);
  43341. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  43342. }
  43343. else if (colorsData && colorsData.length) {
  43344. newColorsData.push(colorsData[(originalOffset * 4)]);
  43345. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  43346. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  43347. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  43348. }
  43349. ++vertexCount;
  43350. });
  43351. }
  43352. }
  43353. var startingIndex = this._reconstructedMesh.getTotalIndices();
  43354. var startingVertex = this._reconstructedMesh.getTotalVertices();
  43355. var submeshesArray = this._reconstructedMesh.subMeshes;
  43356. this._reconstructedMesh.subMeshes = [];
  43357. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  43358. var originalIndices = this._mesh.getIndices();
  43359. for (i = 0; i < newTriangles.length; ++i) {
  43360. t = newTriangles[i]; //now get the new referencing point for each vertex
  43361. [0, 1, 2].forEach(function (idx) {
  43362. var id = originalIndices[t.originalOffset + idx];
  43363. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  43364. if (offset < 0)
  43365. offset = 0;
  43366. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  43367. });
  43368. }
  43369. //overwriting the old vertex buffers and indices.
  43370. this._reconstructedMesh.setIndices(newIndicesArray);
  43371. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  43372. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  43373. if (newUVsData.length > 0)
  43374. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  43375. if (newColorsData.length > 0)
  43376. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  43377. //create submesh
  43378. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  43379. if (submeshIndex > 0) {
  43380. this._reconstructedMesh.subMeshes = [];
  43381. submeshesArray.forEach(function (submesh) {
  43382. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  43383. });
  43384. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  43385. }
  43386. };
  43387. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  43388. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  43389. this._reconstructedMesh.material = this._mesh.material;
  43390. this._reconstructedMesh.parent = this._mesh.parent;
  43391. this._reconstructedMesh.isVisible = false;
  43392. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  43393. };
  43394. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  43395. for (var i = 0; i < vertex1.triangleCount; ++i) {
  43396. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  43397. if (t.deleted)
  43398. continue;
  43399. var s = this.references[vertex1.triangleStart + i].vertexId;
  43400. var v1 = t.vertices[(s + 1) % 3];
  43401. var v2 = t.vertices[(s + 2) % 3];
  43402. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  43403. deletedArray[i] = true;
  43404. delTr.push(t);
  43405. continue;
  43406. }
  43407. var d1 = v1.position.subtract(point);
  43408. d1 = d1.normalize();
  43409. var d2 = v2.position.subtract(point);
  43410. d2 = d2.normalize();
  43411. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  43412. return true;
  43413. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  43414. deletedArray[i] = false;
  43415. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  43416. return true;
  43417. }
  43418. return false;
  43419. };
  43420. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  43421. var newDeleted = deletedTriangles;
  43422. for (var i = 0; i < vertex.triangleCount; ++i) {
  43423. var ref = this.references[vertex.triangleStart + i];
  43424. var t = this.triangles[ref.triangleId];
  43425. if (t.deleted)
  43426. continue;
  43427. if (deletedArray[i] && t.deletePending) {
  43428. t.deleted = true;
  43429. newDeleted++;
  43430. continue;
  43431. }
  43432. t.vertices[ref.vertexId] = origVertex;
  43433. t.isDirty = true;
  43434. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  43435. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  43436. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  43437. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  43438. this.references.push(ref);
  43439. }
  43440. return newDeleted;
  43441. };
  43442. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  43443. for (var i = 0; i < this.vertices.length; ++i) {
  43444. var vCount = [];
  43445. var vId = [];
  43446. var v = this.vertices[i];
  43447. var j;
  43448. for (j = 0; j < v.triangleCount; ++j) {
  43449. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  43450. for (var ii = 0; ii < 3; ii++) {
  43451. var ofs = 0;
  43452. var vv = triangle.vertices[ii];
  43453. while (ofs < vCount.length) {
  43454. if (vId[ofs] === vv.id)
  43455. break;
  43456. ++ofs;
  43457. }
  43458. if (ofs === vCount.length) {
  43459. vCount.push(1);
  43460. vId.push(vv.id);
  43461. }
  43462. else {
  43463. vCount[ofs]++;
  43464. }
  43465. }
  43466. }
  43467. for (j = 0; j < vCount.length; ++j) {
  43468. if (vCount[j] === 1) {
  43469. this.vertices[vId[j]].isBorder = true;
  43470. }
  43471. else {
  43472. this.vertices[vId[j]].isBorder = false;
  43473. }
  43474. }
  43475. }
  43476. };
  43477. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  43478. if (identifyBorders === void 0) { identifyBorders = false; }
  43479. var i;
  43480. if (!identifyBorders) {
  43481. var newTrianglesVector = [];
  43482. for (i = 0; i < this.triangles.length; ++i) {
  43483. if (!this.triangles[i].deleted) {
  43484. newTrianglesVector.push(this.triangles[i]);
  43485. }
  43486. }
  43487. this.triangles = newTrianglesVector;
  43488. }
  43489. for (i = 0; i < this.vertices.length; ++i) {
  43490. this.vertices[i].triangleCount = 0;
  43491. this.vertices[i].triangleStart = 0;
  43492. }
  43493. var t;
  43494. var j;
  43495. var v;
  43496. for (i = 0; i < this.triangles.length; ++i) {
  43497. t = this.triangles[i];
  43498. for (j = 0; j < 3; ++j) {
  43499. v = t.vertices[j];
  43500. v.triangleCount++;
  43501. }
  43502. }
  43503. var tStart = 0;
  43504. for (i = 0; i < this.vertices.length; ++i) {
  43505. this.vertices[i].triangleStart = tStart;
  43506. tStart += this.vertices[i].triangleCount;
  43507. this.vertices[i].triangleCount = 0;
  43508. }
  43509. var newReferences = new Array(this.triangles.length * 3);
  43510. for (i = 0; i < this.triangles.length; ++i) {
  43511. t = this.triangles[i];
  43512. for (j = 0; j < 3; ++j) {
  43513. v = t.vertices[j];
  43514. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  43515. v.triangleCount++;
  43516. }
  43517. }
  43518. this.references = newReferences;
  43519. if (identifyBorders) {
  43520. this.identifyBorder();
  43521. }
  43522. };
  43523. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  43524. var x = point.x;
  43525. var y = point.y;
  43526. var z = point.z;
  43527. 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
  43528. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  43529. };
  43530. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  43531. var q = vertex1.q.add(vertex2.q);
  43532. var border = vertex1.isBorder && vertex2.isBorder;
  43533. var error = 0;
  43534. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  43535. if (qDet !== 0 && !border) {
  43536. if (!pointResult) {
  43537. pointResult = BABYLON.Vector3.Zero();
  43538. }
  43539. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  43540. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  43541. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  43542. error = this.vertexError(q, pointResult);
  43543. }
  43544. else {
  43545. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  43546. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  43547. var error1 = this.vertexError(q, vertex1.position);
  43548. var error2 = this.vertexError(q, vertex2.position);
  43549. var error3 = this.vertexError(q, p3);
  43550. error = Math.min(error1, error2, error3);
  43551. if (error === error1) {
  43552. if (pointResult) {
  43553. pointResult.copyFrom(vertex1.position);
  43554. }
  43555. }
  43556. else if (error === error2) {
  43557. if (pointResult) {
  43558. pointResult.copyFrom(vertex2.position);
  43559. }
  43560. }
  43561. else {
  43562. if (pointResult) {
  43563. pointResult.copyFrom(p3);
  43564. }
  43565. }
  43566. }
  43567. return error;
  43568. };
  43569. return QuadraticErrorSimplification;
  43570. })();
  43571. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  43572. })(BABYLON || (BABYLON = {}));
  43573. var BABYLON;
  43574. (function (BABYLON) {
  43575. var serializedGeometries = [];
  43576. var serializeGeometry = function (geometry, serializationGeometries) {
  43577. if (serializedGeometries[geometry.id]) {
  43578. return;
  43579. }
  43580. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  43581. serializationGeometries.boxes.push(geometry.serialize());
  43582. }
  43583. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  43584. serializationGeometries.spheres.push(geometry.serialize());
  43585. }
  43586. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  43587. serializationGeometries.cylinders.push(geometry.serialize());
  43588. }
  43589. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  43590. serializationGeometries.toruses.push(geometry.serialize());
  43591. }
  43592. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  43593. serializationGeometries.grounds.push(geometry.serialize());
  43594. }
  43595. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  43596. serializationGeometries.planes.push(geometry.serialize());
  43597. }
  43598. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  43599. serializationGeometries.torusKnots.push(geometry.serialize());
  43600. }
  43601. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  43602. throw new Error("Unknown primitive type");
  43603. }
  43604. else {
  43605. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  43606. }
  43607. serializedGeometries[geometry.id] = true;
  43608. };
  43609. var serializeMesh = function (mesh, serializationScene) {
  43610. var serializationObject = {};
  43611. serializationObject.name = mesh.name;
  43612. serializationObject.id = mesh.id;
  43613. if (BABYLON.Tags.HasTags(mesh)) {
  43614. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  43615. }
  43616. serializationObject.position = mesh.position.asArray();
  43617. if (mesh.rotationQuaternion) {
  43618. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  43619. }
  43620. else if (mesh.rotation) {
  43621. serializationObject.rotation = mesh.rotation.asArray();
  43622. }
  43623. serializationObject.scaling = mesh.scaling.asArray();
  43624. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  43625. serializationObject.isEnabled = mesh.isEnabled();
  43626. serializationObject.isVisible = mesh.isVisible;
  43627. serializationObject.infiniteDistance = mesh.infiniteDistance;
  43628. serializationObject.pickable = mesh.isPickable;
  43629. serializationObject.receiveShadows = mesh.receiveShadows;
  43630. serializationObject.billboardMode = mesh.billboardMode;
  43631. serializationObject.visibility = mesh.visibility;
  43632. serializationObject.checkCollisions = mesh.checkCollisions;
  43633. // Parent
  43634. if (mesh.parent) {
  43635. serializationObject.parentId = mesh.parent.id;
  43636. }
  43637. // Geometry
  43638. var geometry = mesh._geometry;
  43639. if (geometry) {
  43640. var geometryId = geometry.id;
  43641. serializationObject.geometryId = geometryId;
  43642. if (!mesh.getScene().getGeometryByID(geometryId)) {
  43643. // 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
  43644. serializeGeometry(geometry, serializationScene.geometries);
  43645. }
  43646. // SubMeshes
  43647. serializationObject.subMeshes = [];
  43648. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  43649. var subMesh = mesh.subMeshes[subIndex];
  43650. serializationObject.subMeshes.push({
  43651. materialIndex: subMesh.materialIndex,
  43652. verticesStart: subMesh.verticesStart,
  43653. verticesCount: subMesh.verticesCount,
  43654. indexStart: subMesh.indexStart,
  43655. indexCount: subMesh.indexCount
  43656. });
  43657. }
  43658. }
  43659. // Material
  43660. if (mesh.material) {
  43661. serializationObject.materialId = mesh.material.id;
  43662. }
  43663. else {
  43664. mesh.material = null;
  43665. }
  43666. // Skeleton
  43667. if (mesh.skeleton) {
  43668. serializationObject.skeletonId = mesh.skeleton.id;
  43669. }
  43670. // Physics
  43671. //TODO implement correct serialization for physics impostors.
  43672. if (mesh.getPhysicsImpostor()) {
  43673. serializationObject.physicsMass = mesh.getPhysicsMass();
  43674. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  43675. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  43676. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  43677. }
  43678. // Instances
  43679. serializationObject.instances = [];
  43680. for (var index = 0; index < mesh.instances.length; index++) {
  43681. var instance = mesh.instances[index];
  43682. var serializationInstance = {
  43683. name: instance.name,
  43684. position: instance.position.asArray(),
  43685. scaling: instance.scaling.asArray()
  43686. };
  43687. if (instance.rotationQuaternion) {
  43688. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  43689. }
  43690. else if (instance.rotation) {
  43691. serializationInstance.rotation = instance.rotation.asArray();
  43692. }
  43693. serializationObject.instances.push(serializationInstance);
  43694. // Animations
  43695. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  43696. serializationInstance.ranges = instance.serializeAnimationRanges();
  43697. }
  43698. // Animations
  43699. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  43700. serializationObject.ranges = mesh.serializeAnimationRanges();
  43701. // Layer mask
  43702. serializationObject.layerMask = mesh.layerMask;
  43703. // Action Manager
  43704. if (mesh.actionManager) {
  43705. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  43706. }
  43707. return serializationObject;
  43708. };
  43709. var finalizeSingleMesh = function (mesh, serializationObject) {
  43710. //only works if the mesh is already loaded
  43711. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43712. //serialize material
  43713. if (mesh.material) {
  43714. if (mesh.material instanceof BABYLON.StandardMaterial) {
  43715. serializationObject.materials = serializationObject.materials || [];
  43716. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43717. serializationObject.materials.push(mesh.material.serialize());
  43718. }
  43719. }
  43720. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  43721. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  43722. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43723. serializationObject.multiMaterials.push(mesh.material.serialize());
  43724. }
  43725. }
  43726. }
  43727. //serialize geometry
  43728. var geometry = mesh._geometry;
  43729. if (geometry) {
  43730. if (!serializationObject.geometries) {
  43731. serializationObject.geometries = {};
  43732. serializationObject.geometries.boxes = [];
  43733. serializationObject.geometries.spheres = [];
  43734. serializationObject.geometries.cylinders = [];
  43735. serializationObject.geometries.toruses = [];
  43736. serializationObject.geometries.grounds = [];
  43737. serializationObject.geometries.planes = [];
  43738. serializationObject.geometries.torusKnots = [];
  43739. serializationObject.geometries.vertexData = [];
  43740. }
  43741. serializeGeometry(geometry, serializationObject.geometries);
  43742. }
  43743. // Skeletons
  43744. if (mesh.skeleton) {
  43745. serializationObject.skeletons = serializationObject.skeletons || [];
  43746. serializationObject.skeletons.push(mesh.skeleton.serialize());
  43747. }
  43748. //serialize the actual mesh
  43749. serializationObject.meshes = serializationObject.meshes || [];
  43750. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43751. }
  43752. };
  43753. var SceneSerializer = (function () {
  43754. function SceneSerializer() {
  43755. }
  43756. SceneSerializer.ClearCache = function () {
  43757. serializedGeometries = [];
  43758. };
  43759. SceneSerializer.Serialize = function (scene) {
  43760. var serializationObject = {};
  43761. // Scene
  43762. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  43763. serializationObject.autoClear = scene.autoClear;
  43764. serializationObject.clearColor = scene.clearColor.asArray();
  43765. serializationObject.ambientColor = scene.ambientColor.asArray();
  43766. serializationObject.gravity = scene.gravity.asArray();
  43767. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  43768. serializationObject.workerCollisions = scene.workerCollisions;
  43769. // Fog
  43770. if (scene.fogMode && scene.fogMode !== 0) {
  43771. serializationObject.fogMode = scene.fogMode;
  43772. serializationObject.fogColor = scene.fogColor.asArray();
  43773. serializationObject.fogStart = scene.fogStart;
  43774. serializationObject.fogEnd = scene.fogEnd;
  43775. serializationObject.fogDensity = scene.fogDensity;
  43776. }
  43777. //Physics
  43778. if (scene.isPhysicsEnabled()) {
  43779. serializationObject.physicsEnabled = true;
  43780. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  43781. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  43782. }
  43783. // Lights
  43784. serializationObject.lights = [];
  43785. var index;
  43786. var light;
  43787. for (index = 0; index < scene.lights.length; index++) {
  43788. light = scene.lights[index];
  43789. serializationObject.lights.push(light.serialize());
  43790. }
  43791. // Cameras
  43792. serializationObject.cameras = [];
  43793. for (index = 0; index < scene.cameras.length; index++) {
  43794. var camera = scene.cameras[index];
  43795. serializationObject.cameras.push(camera.serialize());
  43796. }
  43797. if (scene.activeCamera) {
  43798. serializationObject.activeCameraID = scene.activeCamera.id;
  43799. }
  43800. // Animations
  43801. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  43802. // Materials
  43803. serializationObject.materials = [];
  43804. serializationObject.multiMaterials = [];
  43805. var material;
  43806. for (index = 0; index < scene.materials.length; index++) {
  43807. material = scene.materials[index];
  43808. serializationObject.materials.push(material.serialize());
  43809. }
  43810. // MultiMaterials
  43811. serializationObject.multiMaterials = [];
  43812. for (index = 0; index < scene.multiMaterials.length; index++) {
  43813. var multiMaterial = scene.multiMaterials[index];
  43814. serializationObject.multiMaterials.push(multiMaterial.serialize());
  43815. }
  43816. // Skeletons
  43817. serializationObject.skeletons = [];
  43818. for (index = 0; index < scene.skeletons.length; index++) {
  43819. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  43820. }
  43821. // Geometries
  43822. serializationObject.geometries = {};
  43823. serializationObject.geometries.boxes = [];
  43824. serializationObject.geometries.spheres = [];
  43825. serializationObject.geometries.cylinders = [];
  43826. serializationObject.geometries.toruses = [];
  43827. serializationObject.geometries.grounds = [];
  43828. serializationObject.geometries.planes = [];
  43829. serializationObject.geometries.torusKnots = [];
  43830. serializationObject.geometries.vertexData = [];
  43831. serializedGeometries = [];
  43832. var geometries = scene.getGeometries();
  43833. for (index = 0; index < geometries.length; index++) {
  43834. var geometry = geometries[index];
  43835. if (geometry.isReady()) {
  43836. serializeGeometry(geometry, serializationObject.geometries);
  43837. }
  43838. }
  43839. // Meshes
  43840. serializationObject.meshes = [];
  43841. for (index = 0; index < scene.meshes.length; index++) {
  43842. var abstractMesh = scene.meshes[index];
  43843. if (abstractMesh instanceof BABYLON.Mesh) {
  43844. var mesh = abstractMesh;
  43845. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43846. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43847. }
  43848. }
  43849. }
  43850. // Particles Systems
  43851. serializationObject.particleSystems = [];
  43852. for (index = 0; index < scene.particleSystems.length; index++) {
  43853. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  43854. }
  43855. // Lens flares
  43856. serializationObject.lensFlareSystems = [];
  43857. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  43858. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  43859. }
  43860. // Shadows
  43861. serializationObject.shadowGenerators = [];
  43862. for (index = 0; index < scene.lights.length; index++) {
  43863. light = scene.lights[index];
  43864. if (light.getShadowGenerator()) {
  43865. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  43866. }
  43867. }
  43868. // Action Manager
  43869. if (scene.actionManager) {
  43870. serializationObject.actions = scene.actionManager.serialize("scene");
  43871. }
  43872. return serializationObject;
  43873. };
  43874. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  43875. if (withParents === void 0) { withParents = false; }
  43876. if (withChildren === void 0) { withChildren = false; }
  43877. var serializationObject = {};
  43878. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  43879. if (withParents || withChildren) {
  43880. //deliberate for loop! not for each, appended should be processed as well.
  43881. for (var i = 0; i < toSerialize.length; ++i) {
  43882. if (withChildren) {
  43883. toSerialize[i].getDescendants().forEach(function (node) {
  43884. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  43885. toSerialize.push(node);
  43886. }
  43887. });
  43888. }
  43889. //make sure the array doesn't contain the object already
  43890. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  43891. toSerialize.push(toSerialize[i].parent);
  43892. }
  43893. }
  43894. }
  43895. toSerialize.forEach(function (mesh) {
  43896. finalizeSingleMesh(mesh, serializationObject);
  43897. });
  43898. return serializationObject;
  43899. };
  43900. return SceneSerializer;
  43901. })();
  43902. BABYLON.SceneSerializer = SceneSerializer;
  43903. })(BABYLON || (BABYLON = {}));
  43904. var BABYLON;
  43905. (function (BABYLON) {
  43906. // Unique ID when we import meshes from Babylon to CSG
  43907. var currentCSGMeshId = 0;
  43908. // # class Vertex
  43909. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43910. // one to provide additional features like texture coordinates and vertex
  43911. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43912. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43913. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43914. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43915. // is not used anywhere else.
  43916. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43917. var Vertex = (function () {
  43918. function Vertex(pos, normal, uv) {
  43919. this.pos = pos;
  43920. this.normal = normal;
  43921. this.uv = uv;
  43922. }
  43923. Vertex.prototype.clone = function () {
  43924. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43925. };
  43926. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43927. // orientation of a polygon is flipped.
  43928. Vertex.prototype.flip = function () {
  43929. this.normal = this.normal.scale(-1);
  43930. };
  43931. // Create a new vertex between this vertex and `other` by linearly
  43932. // interpolating all properties using a parameter of `t`. Subclasses should
  43933. // override this to interpolate additional properties.
  43934. Vertex.prototype.interpolate = function (other, t) {
  43935. 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));
  43936. };
  43937. return Vertex;
  43938. })();
  43939. // # class Plane
  43940. // Represents a plane in 3D space.
  43941. var Plane = (function () {
  43942. function Plane(normal, w) {
  43943. this.normal = normal;
  43944. this.w = w;
  43945. }
  43946. Plane.FromPoints = function (a, b, c) {
  43947. var v0 = c.subtract(a);
  43948. var v1 = b.subtract(a);
  43949. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43950. return null;
  43951. }
  43952. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43953. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43954. };
  43955. Plane.prototype.clone = function () {
  43956. return new Plane(this.normal.clone(), this.w);
  43957. };
  43958. Plane.prototype.flip = function () {
  43959. this.normal.scaleInPlace(-1);
  43960. this.w = -this.w;
  43961. };
  43962. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43963. // fragments in the appropriate lists. Coplanar polygons go into either
  43964. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43965. // respect to this plane. Polygons in front or in back of this plane go into
  43966. // either `front` or `back`.
  43967. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43968. var COPLANAR = 0;
  43969. var FRONT = 1;
  43970. var BACK = 2;
  43971. var SPANNING = 3;
  43972. // Classify each point as well as the entire polygon into one of the above
  43973. // four classes.
  43974. var polygonType = 0;
  43975. var types = [];
  43976. var i;
  43977. var t;
  43978. for (i = 0; i < polygon.vertices.length; i++) {
  43979. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43980. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43981. polygonType |= type;
  43982. types.push(type);
  43983. }
  43984. // Put the polygon in the correct list, splitting it when necessary.
  43985. switch (polygonType) {
  43986. case COPLANAR:
  43987. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43988. break;
  43989. case FRONT:
  43990. front.push(polygon);
  43991. break;
  43992. case BACK:
  43993. back.push(polygon);
  43994. break;
  43995. case SPANNING:
  43996. var f = [], b = [];
  43997. for (i = 0; i < polygon.vertices.length; i++) {
  43998. var j = (i + 1) % polygon.vertices.length;
  43999. var ti = types[i], tj = types[j];
  44000. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  44001. if (ti !== BACK)
  44002. f.push(vi);
  44003. if (ti !== FRONT)
  44004. b.push(ti !== BACK ? vi.clone() : vi);
  44005. if ((ti | tj) === SPANNING) {
  44006. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  44007. var v = vi.interpolate(vj, t);
  44008. f.push(v);
  44009. b.push(v.clone());
  44010. }
  44011. }
  44012. var poly;
  44013. if (f.length >= 3) {
  44014. poly = new Polygon(f, polygon.shared);
  44015. if (poly.plane)
  44016. front.push(poly);
  44017. }
  44018. if (b.length >= 3) {
  44019. poly = new Polygon(b, polygon.shared);
  44020. if (poly.plane)
  44021. back.push(poly);
  44022. }
  44023. break;
  44024. }
  44025. };
  44026. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  44027. // point is on the plane.
  44028. Plane.EPSILON = 1e-5;
  44029. return Plane;
  44030. })();
  44031. // # class Polygon
  44032. // Represents a convex polygon. The vertices used to initialize a polygon must
  44033. // be coplanar and form a convex loop.
  44034. //
  44035. // Each convex polygon has a `shared` property, which is shared between all
  44036. // polygons that are clones of each other or were split from the same polygon.
  44037. // This can be used to define per-polygon properties (such as surface color).
  44038. var Polygon = (function () {
  44039. function Polygon(vertices, shared) {
  44040. this.vertices = vertices;
  44041. this.shared = shared;
  44042. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  44043. }
  44044. Polygon.prototype.clone = function () {
  44045. var vertices = this.vertices.map(function (v) { return v.clone(); });
  44046. return new Polygon(vertices, this.shared);
  44047. };
  44048. Polygon.prototype.flip = function () {
  44049. this.vertices.reverse().map(function (v) { v.flip(); });
  44050. this.plane.flip();
  44051. };
  44052. return Polygon;
  44053. })();
  44054. // # class Node
  44055. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  44056. // by picking a polygon to split along. That polygon (and all other coplanar
  44057. // polygons) are added directly to that node and the other polygons are added to
  44058. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  44059. // no distinction between internal and leaf nodes.
  44060. var Node = (function () {
  44061. function Node(polygons) {
  44062. this.plane = null;
  44063. this.front = null;
  44064. this.back = null;
  44065. this.polygons = [];
  44066. if (polygons) {
  44067. this.build(polygons);
  44068. }
  44069. }
  44070. Node.prototype.clone = function () {
  44071. var node = new Node();
  44072. node.plane = this.plane && this.plane.clone();
  44073. node.front = this.front && this.front.clone();
  44074. node.back = this.back && this.back.clone();
  44075. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  44076. return node;
  44077. };
  44078. // Convert solid space to empty space and empty space to solid space.
  44079. Node.prototype.invert = function () {
  44080. for (var i = 0; i < this.polygons.length; i++) {
  44081. this.polygons[i].flip();
  44082. }
  44083. if (this.plane) {
  44084. this.plane.flip();
  44085. }
  44086. if (this.front) {
  44087. this.front.invert();
  44088. }
  44089. if (this.back) {
  44090. this.back.invert();
  44091. }
  44092. var temp = this.front;
  44093. this.front = this.back;
  44094. this.back = temp;
  44095. };
  44096. // Recursively remove all polygons in `polygons` that are inside this BSP
  44097. // tree.
  44098. Node.prototype.clipPolygons = function (polygons) {
  44099. if (!this.plane)
  44100. return polygons.slice();
  44101. var front = [], back = [];
  44102. for (var i = 0; i < polygons.length; i++) {
  44103. this.plane.splitPolygon(polygons[i], front, back, front, back);
  44104. }
  44105. if (this.front) {
  44106. front = this.front.clipPolygons(front);
  44107. }
  44108. if (this.back) {
  44109. back = this.back.clipPolygons(back);
  44110. }
  44111. else {
  44112. back = [];
  44113. }
  44114. return front.concat(back);
  44115. };
  44116. // Remove all polygons in this BSP tree that are inside the other BSP tree
  44117. // `bsp`.
  44118. Node.prototype.clipTo = function (bsp) {
  44119. this.polygons = bsp.clipPolygons(this.polygons);
  44120. if (this.front)
  44121. this.front.clipTo(bsp);
  44122. if (this.back)
  44123. this.back.clipTo(bsp);
  44124. };
  44125. // Return a list of all polygons in this BSP tree.
  44126. Node.prototype.allPolygons = function () {
  44127. var polygons = this.polygons.slice();
  44128. if (this.front)
  44129. polygons = polygons.concat(this.front.allPolygons());
  44130. if (this.back)
  44131. polygons = polygons.concat(this.back.allPolygons());
  44132. return polygons;
  44133. };
  44134. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  44135. // new polygons are filtered down to the bottom of the tree and become new
  44136. // nodes there. Each set of polygons is partitioned using the first polygon
  44137. // (no heuristic is used to pick a good split).
  44138. Node.prototype.build = function (polygons) {
  44139. if (!polygons.length)
  44140. return;
  44141. if (!this.plane)
  44142. this.plane = polygons[0].plane.clone();
  44143. var front = [], back = [];
  44144. for (var i = 0; i < polygons.length; i++) {
  44145. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  44146. }
  44147. if (front.length) {
  44148. if (!this.front)
  44149. this.front = new Node();
  44150. this.front.build(front);
  44151. }
  44152. if (back.length) {
  44153. if (!this.back)
  44154. this.back = new Node();
  44155. this.back.build(back);
  44156. }
  44157. };
  44158. return Node;
  44159. })();
  44160. var CSG = (function () {
  44161. function CSG() {
  44162. this.polygons = new Array();
  44163. }
  44164. // Convert BABYLON.Mesh to BABYLON.CSG
  44165. CSG.FromMesh = function (mesh) {
  44166. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  44167. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  44168. if (mesh instanceof BABYLON.Mesh) {
  44169. mesh.computeWorldMatrix(true);
  44170. matrix = mesh.getWorldMatrix();
  44171. meshPosition = mesh.position.clone();
  44172. meshRotation = mesh.rotation.clone();
  44173. if (mesh.rotationQuaternion) {
  44174. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  44175. }
  44176. meshScaling = mesh.scaling.clone();
  44177. }
  44178. else {
  44179. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  44180. }
  44181. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44182. var subMeshes = mesh.subMeshes;
  44183. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  44184. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  44185. vertices = [];
  44186. for (var j = 0; j < 3; j++) {
  44187. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  44188. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  44189. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  44190. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  44191. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  44192. vertex = new Vertex(position, normal, uv);
  44193. vertices.push(vertex);
  44194. }
  44195. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  44196. // To handle the case of degenerated triangle
  44197. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  44198. if (polygon.plane)
  44199. polygons.push(polygon);
  44200. }
  44201. }
  44202. var csg = CSG.FromPolygons(polygons);
  44203. csg.matrix = matrix;
  44204. csg.position = meshPosition;
  44205. csg.rotation = meshRotation;
  44206. csg.scaling = meshScaling;
  44207. csg.rotationQuaternion = meshRotationQuaternion;
  44208. currentCSGMeshId++;
  44209. return csg;
  44210. };
  44211. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  44212. CSG.FromPolygons = function (polygons) {
  44213. var csg = new CSG();
  44214. csg.polygons = polygons;
  44215. return csg;
  44216. };
  44217. CSG.prototype.clone = function () {
  44218. var csg = new CSG();
  44219. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  44220. csg.copyTransformAttributes(this);
  44221. return csg;
  44222. };
  44223. CSG.prototype.toPolygons = function () {
  44224. return this.polygons;
  44225. };
  44226. CSG.prototype.union = function (csg) {
  44227. var a = new Node(this.clone().polygons);
  44228. var b = new Node(csg.clone().polygons);
  44229. a.clipTo(b);
  44230. b.clipTo(a);
  44231. b.invert();
  44232. b.clipTo(a);
  44233. b.invert();
  44234. a.build(b.allPolygons());
  44235. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44236. };
  44237. CSG.prototype.unionInPlace = function (csg) {
  44238. var a = new Node(this.polygons);
  44239. var b = new Node(csg.polygons);
  44240. a.clipTo(b);
  44241. b.clipTo(a);
  44242. b.invert();
  44243. b.clipTo(a);
  44244. b.invert();
  44245. a.build(b.allPolygons());
  44246. this.polygons = a.allPolygons();
  44247. };
  44248. CSG.prototype.subtract = function (csg) {
  44249. var a = new Node(this.clone().polygons);
  44250. var b = new Node(csg.clone().polygons);
  44251. a.invert();
  44252. a.clipTo(b);
  44253. b.clipTo(a);
  44254. b.invert();
  44255. b.clipTo(a);
  44256. b.invert();
  44257. a.build(b.allPolygons());
  44258. a.invert();
  44259. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44260. };
  44261. CSG.prototype.subtractInPlace = function (csg) {
  44262. var a = new Node(this.polygons);
  44263. var b = new Node(csg.polygons);
  44264. a.invert();
  44265. a.clipTo(b);
  44266. b.clipTo(a);
  44267. b.invert();
  44268. b.clipTo(a);
  44269. b.invert();
  44270. a.build(b.allPolygons());
  44271. a.invert();
  44272. this.polygons = a.allPolygons();
  44273. };
  44274. CSG.prototype.intersect = function (csg) {
  44275. var a = new Node(this.clone().polygons);
  44276. var b = new Node(csg.clone().polygons);
  44277. a.invert();
  44278. b.clipTo(a);
  44279. b.invert();
  44280. a.clipTo(b);
  44281. b.clipTo(a);
  44282. a.build(b.allPolygons());
  44283. a.invert();
  44284. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44285. };
  44286. CSG.prototype.intersectInPlace = function (csg) {
  44287. var a = new Node(this.polygons);
  44288. var b = new Node(csg.polygons);
  44289. a.invert();
  44290. b.clipTo(a);
  44291. b.invert();
  44292. a.clipTo(b);
  44293. b.clipTo(a);
  44294. a.build(b.allPolygons());
  44295. a.invert();
  44296. this.polygons = a.allPolygons();
  44297. };
  44298. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  44299. // not modified.
  44300. CSG.prototype.inverse = function () {
  44301. var csg = this.clone();
  44302. csg.inverseInPlace();
  44303. return csg;
  44304. };
  44305. CSG.prototype.inverseInPlace = function () {
  44306. this.polygons.map(function (p) { p.flip(); });
  44307. };
  44308. // This is used to keep meshes transformations so they can be restored
  44309. // when we build back a Babylon Mesh
  44310. // NB : All CSG operations are performed in world coordinates
  44311. CSG.prototype.copyTransformAttributes = function (csg) {
  44312. this.matrix = csg.matrix;
  44313. this.position = csg.position;
  44314. this.rotation = csg.rotation;
  44315. this.scaling = csg.scaling;
  44316. this.rotationQuaternion = csg.rotationQuaternion;
  44317. return this;
  44318. };
  44319. // Build Raw mesh from CSG
  44320. // Coordinates here are in world space
  44321. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  44322. var matrix = this.matrix.clone();
  44323. matrix.invert();
  44324. 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;
  44325. if (keepSubMeshes) {
  44326. // Sort Polygons, since subMeshes are indices range
  44327. polygons.sort(function (a, b) {
  44328. if (a.shared.meshId === b.shared.meshId) {
  44329. return a.shared.subMeshId - b.shared.subMeshId;
  44330. }
  44331. else {
  44332. return a.shared.meshId - b.shared.meshId;
  44333. }
  44334. });
  44335. }
  44336. for (var i = 0, il = polygons.length; i < il; i++) {
  44337. polygon = polygons[i];
  44338. // Building SubMeshes
  44339. if (!subMesh_dict[polygon.shared.meshId]) {
  44340. subMesh_dict[polygon.shared.meshId] = {};
  44341. }
  44342. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  44343. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  44344. indexStart: +Infinity,
  44345. indexEnd: -Infinity,
  44346. materialIndex: polygon.shared.materialIndex
  44347. };
  44348. }
  44349. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  44350. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  44351. polygonIndices[0] = 0;
  44352. polygonIndices[1] = j - 1;
  44353. polygonIndices[2] = j;
  44354. for (var k = 0; k < 3; k++) {
  44355. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  44356. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  44357. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  44358. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  44359. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  44360. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  44361. // Check if 2 points can be merged
  44362. if (!(typeof vertex_idx !== 'undefined' &&
  44363. normals[vertex_idx * 3] === localNormal.x &&
  44364. normals[vertex_idx * 3 + 1] === localNormal.y &&
  44365. normals[vertex_idx * 3 + 2] === localNormal.z &&
  44366. uvs[vertex_idx * 2] === uv.x &&
  44367. uvs[vertex_idx * 2 + 1] === uv.y)) {
  44368. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  44369. uvs.push(uv.x, uv.y);
  44370. normals.push(normal.x, normal.y, normal.z);
  44371. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  44372. }
  44373. indices.push(vertex_idx);
  44374. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  44375. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  44376. currentIndex++;
  44377. }
  44378. }
  44379. }
  44380. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  44381. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  44382. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  44383. mesh.setIndices(indices);
  44384. if (keepSubMeshes) {
  44385. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  44386. var materialIndexOffset = 0, materialMaxIndex;
  44387. mesh.subMeshes = new Array();
  44388. for (var m in subMesh_dict) {
  44389. materialMaxIndex = -1;
  44390. for (var sm in subMesh_dict[m]) {
  44391. subMesh_obj = subMesh_dict[m][sm];
  44392. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  44393. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  44394. }
  44395. materialIndexOffset += ++materialMaxIndex;
  44396. }
  44397. }
  44398. return mesh;
  44399. };
  44400. // Build Mesh from CSG taking material and transforms into account
  44401. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44402. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44403. mesh.material = material;
  44404. mesh.position.copyFrom(this.position);
  44405. mesh.rotation.copyFrom(this.rotation);
  44406. if (this.rotationQuaternion) {
  44407. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44408. }
  44409. mesh.scaling.copyFrom(this.scaling);
  44410. mesh.computeWorldMatrix(true);
  44411. return mesh;
  44412. };
  44413. return CSG;
  44414. })();
  44415. BABYLON.CSG = CSG;
  44416. })(BABYLON || (BABYLON = {}));
  44417. var BABYLON;
  44418. (function (BABYLON) {
  44419. var VRDistortionCorrectionPostProcess = (function (_super) {
  44420. __extends(VRDistortionCorrectionPostProcess, _super);
  44421. //ANY
  44422. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44423. var _this = this;
  44424. _super.call(this, name, "vrDistortionCorrection", [
  44425. 'LensCenter',
  44426. 'Scale',
  44427. 'ScaleIn',
  44428. 'HmdWarpParam'
  44429. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  44430. this._isRightEye = isRightEye;
  44431. this._distortionFactors = vrMetrics.distortionK;
  44432. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44433. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44434. this.onSizeChangedObservable.add(function () {
  44435. _this.aspectRatio = _this.width * .5 / _this.height;
  44436. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44437. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44438. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44439. });
  44440. this.onApplyObservable.add(function (effect) {
  44441. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44442. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44443. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44444. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44445. });
  44446. }
  44447. return VRDistortionCorrectionPostProcess;
  44448. })(BABYLON.PostProcess);
  44449. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44450. })(BABYLON || (BABYLON = {}));
  44451. // Mainly based on these 2 articles :
  44452. // 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
  44453. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44454. var BABYLON;
  44455. (function (BABYLON) {
  44456. (function (JoystickAxis) {
  44457. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44458. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44459. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44460. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44461. var JoystickAxis = BABYLON.JoystickAxis;
  44462. var VirtualJoystick = (function () {
  44463. function VirtualJoystick(leftJoystick) {
  44464. var _this = this;
  44465. if (leftJoystick) {
  44466. this._leftJoystick = true;
  44467. }
  44468. else {
  44469. this._leftJoystick = false;
  44470. }
  44471. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44472. VirtualJoystick._globalJoystickIndex++;
  44473. // By default left & right arrow keys are moving the X
  44474. // and up & down keys are moving the Y
  44475. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44476. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44477. this.reverseLeftRight = false;
  44478. this.reverseUpDown = false;
  44479. // collections of pointers
  44480. this._touches = new BABYLON.StringDictionary();
  44481. this.deltaPosition = BABYLON.Vector3.Zero();
  44482. this._joystickSensibility = 25;
  44483. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44484. this._rotationSpeed = 25;
  44485. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44486. this._rotateOnAxisRelativeToMesh = false;
  44487. this._onResize = function (evt) {
  44488. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44489. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44490. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44491. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44492. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44493. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44494. };
  44495. // injecting a canvas element on top of the canvas 3D game
  44496. if (!VirtualJoystick.vjCanvas) {
  44497. window.addEventListener("resize", this._onResize, false);
  44498. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44499. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44500. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44501. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44502. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44503. VirtualJoystick.vjCanvas.style.width = "100%";
  44504. VirtualJoystick.vjCanvas.style.height = "100%";
  44505. VirtualJoystick.vjCanvas.style.position = "absolute";
  44506. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44507. VirtualJoystick.vjCanvas.style.top = "0px";
  44508. VirtualJoystick.vjCanvas.style.left = "0px";
  44509. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44510. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44511. // Support for jQuery PEP polyfill
  44512. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44513. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44514. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44515. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44516. document.body.appendChild(VirtualJoystick.vjCanvas);
  44517. }
  44518. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44519. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44520. this.pressed = false;
  44521. // default joystick color
  44522. this._joystickColor = "cyan";
  44523. this._joystickPointerID = -1;
  44524. // current joystick position
  44525. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44526. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44527. // origin joystick position
  44528. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44529. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44530. this._onPointerDownHandlerRef = function (evt) {
  44531. _this._onPointerDown(evt);
  44532. };
  44533. this._onPointerMoveHandlerRef = function (evt) {
  44534. _this._onPointerMove(evt);
  44535. };
  44536. this._onPointerOutHandlerRef = function (evt) {
  44537. _this._onPointerUp(evt);
  44538. };
  44539. this._onPointerUpHandlerRef = function (evt) {
  44540. _this._onPointerUp(evt);
  44541. };
  44542. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44543. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44544. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44545. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44546. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44547. evt.preventDefault(); // Disables system menu
  44548. }, false);
  44549. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44550. }
  44551. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44552. this._joystickSensibility = newJoystickSensibility;
  44553. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44554. };
  44555. VirtualJoystick.prototype._onPointerDown = function (e) {
  44556. var positionOnScreenCondition;
  44557. e.preventDefault();
  44558. if (this._leftJoystick === true) {
  44559. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44560. }
  44561. else {
  44562. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44563. }
  44564. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44565. // First contact will be dedicated to the virtual joystick
  44566. this._joystickPointerID = e.pointerId;
  44567. this._joystickPointerStartPos.x = e.clientX;
  44568. this._joystickPointerStartPos.y = e.clientY;
  44569. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44570. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44571. this._deltaJoystickVector.x = 0;
  44572. this._deltaJoystickVector.y = 0;
  44573. this.pressed = true;
  44574. this._touches.add(e.pointerId.toString(), e);
  44575. }
  44576. else {
  44577. // You can only trigger the action buttons with a joystick declared
  44578. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44579. this._action();
  44580. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44581. }
  44582. }
  44583. };
  44584. VirtualJoystick.prototype._onPointerMove = function (e) {
  44585. // If the current pointer is the one associated to the joystick (first touch contact)
  44586. if (this._joystickPointerID == e.pointerId) {
  44587. this._joystickPointerPos.x = e.clientX;
  44588. this._joystickPointerPos.y = e.clientY;
  44589. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44590. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44591. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44592. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44593. switch (this._axisTargetedByLeftAndRight) {
  44594. case JoystickAxis.X:
  44595. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44596. break;
  44597. case JoystickAxis.Y:
  44598. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44599. break;
  44600. case JoystickAxis.Z:
  44601. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44602. break;
  44603. }
  44604. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44605. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44606. switch (this._axisTargetedByUpAndDown) {
  44607. case JoystickAxis.X:
  44608. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44609. break;
  44610. case JoystickAxis.Y:
  44611. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44612. break;
  44613. case JoystickAxis.Z:
  44614. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44615. break;
  44616. }
  44617. }
  44618. else {
  44619. var data = this._touches.get(e.pointerId.toString());
  44620. if (data) {
  44621. data.x = e.clientX;
  44622. data.y = e.clientY;
  44623. }
  44624. }
  44625. };
  44626. VirtualJoystick.prototype._onPointerUp = function (e) {
  44627. if (this._joystickPointerID == e.pointerId) {
  44628. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44629. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44630. this._joystickPointerID = -1;
  44631. this.pressed = false;
  44632. }
  44633. else {
  44634. var touch = this._touches.get(e.pointerId.toString());
  44635. if (touch) {
  44636. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44637. }
  44638. }
  44639. this._deltaJoystickVector.x = 0;
  44640. this._deltaJoystickVector.y = 0;
  44641. this._touches.remove(e.pointerId.toString());
  44642. };
  44643. /**
  44644. * Change the color of the virtual joystick
  44645. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44646. */
  44647. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44648. this._joystickColor = newColor;
  44649. };
  44650. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44651. this._action = action;
  44652. };
  44653. // Define which axis you'd like to control for left & right
  44654. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44655. switch (axis) {
  44656. case JoystickAxis.X:
  44657. case JoystickAxis.Y:
  44658. case JoystickAxis.Z:
  44659. this._axisTargetedByLeftAndRight = axis;
  44660. break;
  44661. default:
  44662. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44663. break;
  44664. }
  44665. };
  44666. // Define which axis you'd like to control for up & down
  44667. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44668. switch (axis) {
  44669. case JoystickAxis.X:
  44670. case JoystickAxis.Y:
  44671. case JoystickAxis.Z:
  44672. this._axisTargetedByUpAndDown = axis;
  44673. break;
  44674. default:
  44675. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44676. break;
  44677. }
  44678. };
  44679. VirtualJoystick.prototype._clearCanvas = function () {
  44680. if (this._leftJoystick) {
  44681. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44682. }
  44683. else {
  44684. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44685. }
  44686. };
  44687. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44688. var _this = this;
  44689. if (this.pressed) {
  44690. this._touches.forEach(function (touch) {
  44691. if (touch.pointerId === _this._joystickPointerID) {
  44692. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44693. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44694. VirtualJoystick.vjCanvasContext.beginPath();
  44695. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44696. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44697. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44698. VirtualJoystick.vjCanvasContext.stroke();
  44699. VirtualJoystick.vjCanvasContext.closePath();
  44700. VirtualJoystick.vjCanvasContext.beginPath();
  44701. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44702. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44703. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44704. VirtualJoystick.vjCanvasContext.stroke();
  44705. VirtualJoystick.vjCanvasContext.closePath();
  44706. VirtualJoystick.vjCanvasContext.beginPath();
  44707. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44708. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44709. VirtualJoystick.vjCanvasContext.stroke();
  44710. VirtualJoystick.vjCanvasContext.closePath();
  44711. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44712. }
  44713. else {
  44714. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44715. VirtualJoystick.vjCanvasContext.beginPath();
  44716. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44717. VirtualJoystick.vjCanvasContext.beginPath();
  44718. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44719. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44720. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44721. VirtualJoystick.vjCanvasContext.stroke();
  44722. VirtualJoystick.vjCanvasContext.closePath();
  44723. touch.prevX = touch.x;
  44724. touch.prevY = touch.y;
  44725. }
  44726. ;
  44727. });
  44728. }
  44729. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44730. };
  44731. VirtualJoystick.prototype.releaseCanvas = function () {
  44732. if (VirtualJoystick.vjCanvas) {
  44733. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44734. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44735. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44736. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44737. window.removeEventListener("resize", this._onResize);
  44738. document.body.removeChild(VirtualJoystick.vjCanvas);
  44739. VirtualJoystick.vjCanvas = null;
  44740. }
  44741. };
  44742. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44743. VirtualJoystick._globalJoystickIndex = 0;
  44744. return VirtualJoystick;
  44745. })();
  44746. BABYLON.VirtualJoystick = VirtualJoystick;
  44747. })(BABYLON || (BABYLON = {}));
  44748. var BABYLON;
  44749. (function (BABYLON) {
  44750. // We're mainly based on the logic defined into the FreeCamera code
  44751. var VirtualJoysticksCamera = (function (_super) {
  44752. __extends(VirtualJoysticksCamera, _super);
  44753. function VirtualJoysticksCamera(name, position, scene) {
  44754. _super.call(this, name, position, scene);
  44755. this.inputs.addVirtualJoystick();
  44756. }
  44757. return VirtualJoysticksCamera;
  44758. })(BABYLON.FreeCamera);
  44759. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44760. })(BABYLON || (BABYLON = {}));
  44761. var BABYLON;
  44762. (function (BABYLON) {
  44763. var FreeCameraVirtualJoystickInput = (function () {
  44764. function FreeCameraVirtualJoystickInput() {
  44765. }
  44766. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44767. return this._leftjoystick;
  44768. };
  44769. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44770. return this._rightjoystick;
  44771. };
  44772. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44773. if (this._leftjoystick) {
  44774. var camera = this.camera;
  44775. var speed = camera._computeLocalCameraSpeed() * 50;
  44776. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44777. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44778. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44779. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44780. if (!this._leftjoystick.pressed) {
  44781. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44782. }
  44783. if (!this._rightjoystick.pressed) {
  44784. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44785. }
  44786. }
  44787. };
  44788. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44789. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44790. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44791. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44792. this._leftjoystick.setJoystickSensibility(0.15);
  44793. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44794. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44795. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44796. this._rightjoystick.reverseUpDown = true;
  44797. this._rightjoystick.setJoystickSensibility(0.05);
  44798. this._rightjoystick.setJoystickColor("yellow");
  44799. };
  44800. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44801. this._leftjoystick.releaseCanvas();
  44802. this._rightjoystick.releaseCanvas();
  44803. };
  44804. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44805. return "FreeCameraVirtualJoystickInput";
  44806. };
  44807. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44808. return "virtualJoystick";
  44809. };
  44810. return FreeCameraVirtualJoystickInput;
  44811. })();
  44812. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44813. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44814. })(BABYLON || (BABYLON = {}));
  44815. var BABYLON;
  44816. (function (BABYLON) {
  44817. var AnaglyphPostProcess = (function (_super) {
  44818. __extends(AnaglyphPostProcess, _super);
  44819. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44820. var _this = this;
  44821. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  44822. this._passedProcess = rigCameras[0]._rigPostProcess;
  44823. this.onApplyObservable.add(function (effect) {
  44824. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44825. });
  44826. }
  44827. return AnaglyphPostProcess;
  44828. })(BABYLON.PostProcess);
  44829. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44830. })(BABYLON || (BABYLON = {}));
  44831. var BABYLON;
  44832. (function (BABYLON) {
  44833. var OutlineRenderer = (function () {
  44834. function OutlineRenderer(scene) {
  44835. this._scene = scene;
  44836. }
  44837. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44838. var _this = this;
  44839. if (useOverlay === void 0) { useOverlay = false; }
  44840. var scene = this._scene;
  44841. var engine = this._scene.getEngine();
  44842. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44843. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44844. return;
  44845. }
  44846. var mesh = subMesh.getRenderingMesh();
  44847. var material = subMesh.getMaterial();
  44848. engine.enableEffect(this._effect);
  44849. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44850. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44851. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44852. // Bones
  44853. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44854. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44855. }
  44856. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44857. // Alpha test
  44858. if (material && material.needAlphaTesting()) {
  44859. var alphaTexture = material.getAlphaTestTexture();
  44860. this._effect.setTexture("diffuseSampler", alphaTexture);
  44861. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44862. }
  44863. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  44864. };
  44865. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  44866. var defines = [];
  44867. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  44868. var mesh = subMesh.getMesh();
  44869. var material = subMesh.getMaterial();
  44870. // Alpha test
  44871. if (material && material.needAlphaTesting()) {
  44872. defines.push("#define ALPHATEST");
  44873. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44874. attribs.push(BABYLON.VertexBuffer.UVKind);
  44875. defines.push("#define UV1");
  44876. }
  44877. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44878. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44879. defines.push("#define UV2");
  44880. }
  44881. }
  44882. // Bones
  44883. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44884. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44885. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44886. if (mesh.numBoneInfluencers > 4) {
  44887. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44888. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44889. }
  44890. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44891. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44892. }
  44893. else {
  44894. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44895. }
  44896. // Instances
  44897. if (useInstances) {
  44898. defines.push("#define INSTANCES");
  44899. attribs.push("world0");
  44900. attribs.push("world1");
  44901. attribs.push("world2");
  44902. attribs.push("world3");
  44903. }
  44904. // Get correct effect
  44905. var join = defines.join("\n");
  44906. if (this._cachedDefines !== join) {
  44907. this._cachedDefines = join;
  44908. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44909. }
  44910. return this._effect.isReady();
  44911. };
  44912. return OutlineRenderer;
  44913. })();
  44914. BABYLON.OutlineRenderer = OutlineRenderer;
  44915. })(BABYLON || (BABYLON = {}));
  44916. var BABYLON;
  44917. (function (BABYLON) {
  44918. var MeshAssetTask = (function () {
  44919. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44920. this.name = name;
  44921. this.meshesNames = meshesNames;
  44922. this.rootUrl = rootUrl;
  44923. this.sceneFilename = sceneFilename;
  44924. this.isCompleted = false;
  44925. }
  44926. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44927. var _this = this;
  44928. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44929. _this.loadedMeshes = meshes;
  44930. _this.loadedParticleSystems = particleSystems;
  44931. _this.loadedSkeletons = skeletons;
  44932. _this.isCompleted = true;
  44933. if (_this.onSuccess) {
  44934. _this.onSuccess(_this);
  44935. }
  44936. onSuccess();
  44937. }, null, function () {
  44938. if (_this.onError) {
  44939. _this.onError(_this);
  44940. }
  44941. onError();
  44942. });
  44943. };
  44944. return MeshAssetTask;
  44945. })();
  44946. BABYLON.MeshAssetTask = MeshAssetTask;
  44947. var TextFileAssetTask = (function () {
  44948. function TextFileAssetTask(name, url) {
  44949. this.name = name;
  44950. this.url = url;
  44951. this.isCompleted = false;
  44952. }
  44953. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44954. var _this = this;
  44955. BABYLON.Tools.LoadFile(this.url, function (data) {
  44956. _this.text = data;
  44957. _this.isCompleted = true;
  44958. if (_this.onSuccess) {
  44959. _this.onSuccess(_this);
  44960. }
  44961. onSuccess();
  44962. }, null, scene.database, false, function () {
  44963. if (_this.onError) {
  44964. _this.onError(_this);
  44965. }
  44966. onError();
  44967. });
  44968. };
  44969. return TextFileAssetTask;
  44970. })();
  44971. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44972. var BinaryFileAssetTask = (function () {
  44973. function BinaryFileAssetTask(name, url) {
  44974. this.name = name;
  44975. this.url = url;
  44976. this.isCompleted = false;
  44977. }
  44978. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44979. var _this = this;
  44980. BABYLON.Tools.LoadFile(this.url, function (data) {
  44981. _this.data = data;
  44982. _this.isCompleted = true;
  44983. if (_this.onSuccess) {
  44984. _this.onSuccess(_this);
  44985. }
  44986. onSuccess();
  44987. }, null, scene.database, true, function () {
  44988. if (_this.onError) {
  44989. _this.onError(_this);
  44990. }
  44991. onError();
  44992. });
  44993. };
  44994. return BinaryFileAssetTask;
  44995. })();
  44996. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44997. var ImageAssetTask = (function () {
  44998. function ImageAssetTask(name, url) {
  44999. this.name = name;
  45000. this.url = url;
  45001. this.isCompleted = false;
  45002. }
  45003. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45004. var _this = this;
  45005. var img = new Image();
  45006. img.onload = function () {
  45007. _this.image = img;
  45008. _this.isCompleted = true;
  45009. if (_this.onSuccess) {
  45010. _this.onSuccess(_this);
  45011. }
  45012. onSuccess();
  45013. };
  45014. img.onerror = function () {
  45015. if (_this.onError) {
  45016. _this.onError(_this);
  45017. }
  45018. onError();
  45019. };
  45020. img.src = this.url;
  45021. };
  45022. return ImageAssetTask;
  45023. })();
  45024. BABYLON.ImageAssetTask = ImageAssetTask;
  45025. var TextureAssetTask = (function () {
  45026. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  45027. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45028. this.name = name;
  45029. this.url = url;
  45030. this.noMipmap = noMipmap;
  45031. this.invertY = invertY;
  45032. this.samplingMode = samplingMode;
  45033. this.isCompleted = false;
  45034. }
  45035. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45036. var _this = this;
  45037. var onload = function () {
  45038. _this.isCompleted = true;
  45039. if (_this.onSuccess) {
  45040. _this.onSuccess(_this);
  45041. }
  45042. onSuccess();
  45043. };
  45044. var onerror = function () {
  45045. if (_this.onError) {
  45046. _this.onError(_this);
  45047. }
  45048. onError();
  45049. };
  45050. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  45051. };
  45052. return TextureAssetTask;
  45053. })();
  45054. BABYLON.TextureAssetTask = TextureAssetTask;
  45055. var AssetsManager = (function () {
  45056. function AssetsManager(scene) {
  45057. this._tasks = new Array();
  45058. this._waitingTasksCount = 0;
  45059. this.useDefaultLoadingScreen = true;
  45060. this._scene = scene;
  45061. }
  45062. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  45063. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  45064. this._tasks.push(task);
  45065. return task;
  45066. };
  45067. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  45068. var task = new TextFileAssetTask(taskName, url);
  45069. this._tasks.push(task);
  45070. return task;
  45071. };
  45072. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  45073. var task = new BinaryFileAssetTask(taskName, url);
  45074. this._tasks.push(task);
  45075. return task;
  45076. };
  45077. AssetsManager.prototype.addImageTask = function (taskName, url) {
  45078. var task = new ImageAssetTask(taskName, url);
  45079. this._tasks.push(task);
  45080. return task;
  45081. };
  45082. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  45083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45084. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  45085. this._tasks.push(task);
  45086. return task;
  45087. };
  45088. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  45089. this._waitingTasksCount--;
  45090. if (this._waitingTasksCount === 0) {
  45091. if (this.onFinish) {
  45092. this.onFinish(this._tasks);
  45093. }
  45094. this._scene.getEngine().hideLoadingUI();
  45095. }
  45096. };
  45097. AssetsManager.prototype._runTask = function (task) {
  45098. var _this = this;
  45099. task.run(this._scene, function () {
  45100. if (_this.onTaskSuccess) {
  45101. _this.onTaskSuccess(task);
  45102. }
  45103. _this._decreaseWaitingTasksCount();
  45104. }, function () {
  45105. if (_this.onTaskError) {
  45106. _this.onTaskError(task);
  45107. }
  45108. _this._decreaseWaitingTasksCount();
  45109. });
  45110. };
  45111. AssetsManager.prototype.reset = function () {
  45112. this._tasks = new Array();
  45113. return this;
  45114. };
  45115. AssetsManager.prototype.load = function () {
  45116. this._waitingTasksCount = this._tasks.length;
  45117. if (this._waitingTasksCount === 0) {
  45118. if (this.onFinish) {
  45119. this.onFinish(this._tasks);
  45120. }
  45121. return this;
  45122. }
  45123. if (this.useDefaultLoadingScreen) {
  45124. this._scene.getEngine().displayLoadingUI();
  45125. }
  45126. for (var index = 0; index < this._tasks.length; index++) {
  45127. var task = this._tasks[index];
  45128. this._runTask(task);
  45129. }
  45130. return this;
  45131. };
  45132. return AssetsManager;
  45133. })();
  45134. BABYLON.AssetsManager = AssetsManager;
  45135. })(BABYLON || (BABYLON = {}));
  45136. var BABYLON;
  45137. (function (BABYLON) {
  45138. var VRCameraMetrics = (function () {
  45139. function VRCameraMetrics() {
  45140. this.compensateDistortion = true;
  45141. }
  45142. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  45143. get: function () {
  45144. return this.hResolution / (2 * this.vResolution);
  45145. },
  45146. enumerable: true,
  45147. configurable: true
  45148. });
  45149. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  45150. get: function () {
  45151. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  45152. },
  45153. enumerable: true,
  45154. configurable: true
  45155. });
  45156. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  45157. get: function () {
  45158. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45159. var h = (4 * meters) / this.hScreenSize;
  45160. return BABYLON.Matrix.Translation(h, 0, 0);
  45161. },
  45162. enumerable: true,
  45163. configurable: true
  45164. });
  45165. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  45166. get: function () {
  45167. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45168. var h = (4 * meters) / this.hScreenSize;
  45169. return BABYLON.Matrix.Translation(-h, 0, 0);
  45170. },
  45171. enumerable: true,
  45172. configurable: true
  45173. });
  45174. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  45175. get: function () {
  45176. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  45177. },
  45178. enumerable: true,
  45179. configurable: true
  45180. });
  45181. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  45182. get: function () {
  45183. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  45184. },
  45185. enumerable: true,
  45186. configurable: true
  45187. });
  45188. VRCameraMetrics.GetDefault = function () {
  45189. var result = new VRCameraMetrics();
  45190. result.hResolution = 1280;
  45191. result.vResolution = 800;
  45192. result.hScreenSize = 0.149759993;
  45193. result.vScreenSize = 0.0935999975;
  45194. result.vScreenCenter = 0.0467999987,
  45195. result.eyeToScreenDistance = 0.0410000011;
  45196. result.lensSeparationDistance = 0.0635000020;
  45197. result.interpupillaryDistance = 0.0640000030;
  45198. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  45199. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  45200. result.postProcessScaleFactor = 1.714605507808412;
  45201. result.lensCenterOffset = 0.151976421;
  45202. return result;
  45203. };
  45204. return VRCameraMetrics;
  45205. })();
  45206. BABYLON.VRCameraMetrics = VRCameraMetrics;
  45207. })(BABYLON || (BABYLON = {}));
  45208. var BABYLON;
  45209. (function (BABYLON) {
  45210. var VRDeviceOrientationFreeCamera = (function (_super) {
  45211. __extends(VRDeviceOrientationFreeCamera, _super);
  45212. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  45213. if (compensateDistortion === void 0) { compensateDistortion = true; }
  45214. _super.call(this, name, position, scene);
  45215. this.rotationQuaternion = new BABYLON.Quaternion();
  45216. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  45217. metrics.compensateDistortion = compensateDistortion;
  45218. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  45219. this.inputs.addDeviceOrientation();
  45220. }
  45221. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  45222. return "VRDeviceOrientationFreeCamera";
  45223. };
  45224. return VRDeviceOrientationFreeCamera;
  45225. })(BABYLON.FreeCamera);
  45226. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  45227. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  45228. __extends(VRDeviceOrientationArcRotateCamera, _super);
  45229. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  45230. if (compensateDistortion === void 0) { compensateDistortion = true; }
  45231. _super.call(this, name, alpha, beta, radius, target, scene);
  45232. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  45233. metrics.compensateDistortion = compensateDistortion;
  45234. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  45235. this.inputs.addVRDeviceOrientation();
  45236. }
  45237. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  45238. return "VRDeviceOrientationArcRotateCamera";
  45239. };
  45240. return VRDeviceOrientationArcRotateCamera;
  45241. })(BABYLON.ArcRotateCamera);
  45242. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  45243. })(BABYLON || (BABYLON = {}));
  45244. var BABYLON;
  45245. (function (BABYLON) {
  45246. var WebVRFreeCamera = (function (_super) {
  45247. __extends(WebVRFreeCamera, _super);
  45248. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  45249. if (compensateDistortion === void 0) { compensateDistortion = true; }
  45250. _super.call(this, name, position, scene);
  45251. this._hmdDevice = null;
  45252. this._sensorDevice = null;
  45253. this._cacheState = null;
  45254. this._vrEnabled = false;
  45255. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  45256. metrics.compensateDistortion = compensateDistortion;
  45257. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  45258. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  45259. this.rotationQuaternion = new BABYLON.Quaternion();
  45260. }
  45261. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  45262. var size = devices.length;
  45263. var i = 0;
  45264. // Reset devices.
  45265. this._sensorDevice = null;
  45266. this._hmdDevice = null;
  45267. // Search for a HmdDevice.
  45268. while (i < size && this._hmdDevice === null) {
  45269. if (devices[i] instanceof HMDVRDevice) {
  45270. this._hmdDevice = devices[i];
  45271. }
  45272. i++;
  45273. }
  45274. i = 0;
  45275. while (i < size && this._sensorDevice === null) {
  45276. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  45277. this._sensorDevice = devices[i];
  45278. }
  45279. i++;
  45280. }
  45281. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  45282. };
  45283. WebVRFreeCamera.prototype._checkInputs = function () {
  45284. if (this._vrEnabled) {
  45285. this._cacheState = this._sensorDevice.getState();
  45286. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  45287. //Flip in XY plane
  45288. this.rotationQuaternion.z *= -1;
  45289. this.rotationQuaternion.w *= -1;
  45290. }
  45291. _super.prototype._checkInputs.call(this);
  45292. };
  45293. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  45294. _super.prototype.attachControl.call(this, element, noPreventDefault);
  45295. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45296. if (navigator.getVRDevices) {
  45297. navigator.getVRDevices().then(this._getWebVRDevices);
  45298. }
  45299. else if (navigator.mozGetVRDevices) {
  45300. navigator.mozGetVRDevices(this._getWebVRDevices);
  45301. }
  45302. };
  45303. WebVRFreeCamera.prototype.detachControl = function (element) {
  45304. _super.prototype.detachControl.call(this, element);
  45305. this._vrEnabled = false;
  45306. };
  45307. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  45308. if (!this._hmdDevice)
  45309. return;
  45310. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  45311. };
  45312. WebVRFreeCamera.prototype.getTypeName = function () {
  45313. return "WebVRFreeCamera";
  45314. };
  45315. return WebVRFreeCamera;
  45316. })(BABYLON.FreeCamera);
  45317. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  45318. })(BABYLON || (BABYLON = {}));
  45319. var BABYLON;
  45320. (function (BABYLON) {
  45321. // Standard optimizations
  45322. var SceneOptimization = (function () {
  45323. function SceneOptimization(priority) {
  45324. if (priority === void 0) { priority = 0; }
  45325. this.priority = priority;
  45326. this.apply = function (scene) {
  45327. return true; // Return true if everything that can be done was applied
  45328. };
  45329. }
  45330. return SceneOptimization;
  45331. })();
  45332. BABYLON.SceneOptimization = SceneOptimization;
  45333. var TextureOptimization = (function (_super) {
  45334. __extends(TextureOptimization, _super);
  45335. function TextureOptimization(priority, maximumSize) {
  45336. var _this = this;
  45337. if (priority === void 0) { priority = 0; }
  45338. if (maximumSize === void 0) { maximumSize = 1024; }
  45339. _super.call(this, priority);
  45340. this.priority = priority;
  45341. this.maximumSize = maximumSize;
  45342. this.apply = function (scene) {
  45343. var allDone = true;
  45344. for (var index = 0; index < scene.textures.length; index++) {
  45345. var texture = scene.textures[index];
  45346. if (!texture.canRescale) {
  45347. continue;
  45348. }
  45349. var currentSize = texture.getSize();
  45350. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45351. if (maxDimension > _this.maximumSize) {
  45352. texture.scale(0.5);
  45353. allDone = false;
  45354. }
  45355. }
  45356. return allDone;
  45357. };
  45358. }
  45359. return TextureOptimization;
  45360. })(SceneOptimization);
  45361. BABYLON.TextureOptimization = TextureOptimization;
  45362. var HardwareScalingOptimization = (function (_super) {
  45363. __extends(HardwareScalingOptimization, _super);
  45364. function HardwareScalingOptimization(priority, maximumScale) {
  45365. var _this = this;
  45366. if (priority === void 0) { priority = 0; }
  45367. if (maximumScale === void 0) { maximumScale = 2; }
  45368. _super.call(this, priority);
  45369. this.priority = priority;
  45370. this.maximumScale = maximumScale;
  45371. this._currentScale = 1;
  45372. this.apply = function (scene) {
  45373. _this._currentScale++;
  45374. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45375. return _this._currentScale >= _this.maximumScale;
  45376. };
  45377. }
  45378. return HardwareScalingOptimization;
  45379. })(SceneOptimization);
  45380. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45381. var ShadowsOptimization = (function (_super) {
  45382. __extends(ShadowsOptimization, _super);
  45383. function ShadowsOptimization() {
  45384. _super.apply(this, arguments);
  45385. this.apply = function (scene) {
  45386. scene.shadowsEnabled = false;
  45387. return true;
  45388. };
  45389. }
  45390. return ShadowsOptimization;
  45391. })(SceneOptimization);
  45392. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45393. var PostProcessesOptimization = (function (_super) {
  45394. __extends(PostProcessesOptimization, _super);
  45395. function PostProcessesOptimization() {
  45396. _super.apply(this, arguments);
  45397. this.apply = function (scene) {
  45398. scene.postProcessesEnabled = false;
  45399. return true;
  45400. };
  45401. }
  45402. return PostProcessesOptimization;
  45403. })(SceneOptimization);
  45404. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45405. var LensFlaresOptimization = (function (_super) {
  45406. __extends(LensFlaresOptimization, _super);
  45407. function LensFlaresOptimization() {
  45408. _super.apply(this, arguments);
  45409. this.apply = function (scene) {
  45410. scene.lensFlaresEnabled = false;
  45411. return true;
  45412. };
  45413. }
  45414. return LensFlaresOptimization;
  45415. })(SceneOptimization);
  45416. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45417. var ParticlesOptimization = (function (_super) {
  45418. __extends(ParticlesOptimization, _super);
  45419. function ParticlesOptimization() {
  45420. _super.apply(this, arguments);
  45421. this.apply = function (scene) {
  45422. scene.particlesEnabled = false;
  45423. return true;
  45424. };
  45425. }
  45426. return ParticlesOptimization;
  45427. })(SceneOptimization);
  45428. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45429. var RenderTargetsOptimization = (function (_super) {
  45430. __extends(RenderTargetsOptimization, _super);
  45431. function RenderTargetsOptimization() {
  45432. _super.apply(this, arguments);
  45433. this.apply = function (scene) {
  45434. scene.renderTargetsEnabled = false;
  45435. return true;
  45436. };
  45437. }
  45438. return RenderTargetsOptimization;
  45439. })(SceneOptimization);
  45440. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45441. var MergeMeshesOptimization = (function (_super) {
  45442. __extends(MergeMeshesOptimization, _super);
  45443. function MergeMeshesOptimization() {
  45444. var _this = this;
  45445. _super.apply(this, arguments);
  45446. this._canBeMerged = function (abstractMesh) {
  45447. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45448. return false;
  45449. }
  45450. var mesh = abstractMesh;
  45451. if (!mesh.isVisible || !mesh.isEnabled()) {
  45452. return false;
  45453. }
  45454. if (mesh.instances.length > 0) {
  45455. return false;
  45456. }
  45457. if (mesh.skeleton || mesh.hasLODLevels) {
  45458. return false;
  45459. }
  45460. if (mesh.parent) {
  45461. return false;
  45462. }
  45463. return true;
  45464. };
  45465. this.apply = function (scene, updateSelectionTree) {
  45466. var globalPool = scene.meshes.slice(0);
  45467. var globalLength = globalPool.length;
  45468. for (var index = 0; index < globalLength; index++) {
  45469. var currentPool = new Array();
  45470. var current = globalPool[index];
  45471. // Checks
  45472. if (!_this._canBeMerged(current)) {
  45473. continue;
  45474. }
  45475. currentPool.push(current);
  45476. // Find compatible meshes
  45477. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45478. var otherMesh = globalPool[subIndex];
  45479. if (!_this._canBeMerged(otherMesh)) {
  45480. continue;
  45481. }
  45482. if (otherMesh.material !== current.material) {
  45483. continue;
  45484. }
  45485. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45486. continue;
  45487. }
  45488. currentPool.push(otherMesh);
  45489. globalLength--;
  45490. globalPool.splice(subIndex, 1);
  45491. subIndex--;
  45492. }
  45493. if (currentPool.length < 2) {
  45494. continue;
  45495. }
  45496. // Merge meshes
  45497. BABYLON.Mesh.MergeMeshes(currentPool);
  45498. }
  45499. if (updateSelectionTree != undefined) {
  45500. if (updateSelectionTree) {
  45501. scene.createOrUpdateSelectionOctree();
  45502. }
  45503. }
  45504. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45505. scene.createOrUpdateSelectionOctree();
  45506. }
  45507. return true;
  45508. };
  45509. }
  45510. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45511. get: function () {
  45512. return MergeMeshesOptimization._UpdateSelectionTree;
  45513. },
  45514. set: function (value) {
  45515. MergeMeshesOptimization._UpdateSelectionTree = value;
  45516. },
  45517. enumerable: true,
  45518. configurable: true
  45519. });
  45520. MergeMeshesOptimization._UpdateSelectionTree = false;
  45521. return MergeMeshesOptimization;
  45522. })(SceneOptimization);
  45523. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45524. // Options
  45525. var SceneOptimizerOptions = (function () {
  45526. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45527. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45528. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45529. this.targetFrameRate = targetFrameRate;
  45530. this.trackerDuration = trackerDuration;
  45531. this.optimizations = new Array();
  45532. }
  45533. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45534. var result = new SceneOptimizerOptions(targetFrameRate);
  45535. var priority = 0;
  45536. result.optimizations.push(new MergeMeshesOptimization(priority));
  45537. result.optimizations.push(new ShadowsOptimization(priority));
  45538. result.optimizations.push(new LensFlaresOptimization(priority));
  45539. // Next priority
  45540. priority++;
  45541. result.optimizations.push(new PostProcessesOptimization(priority));
  45542. result.optimizations.push(new ParticlesOptimization(priority));
  45543. // Next priority
  45544. priority++;
  45545. result.optimizations.push(new TextureOptimization(priority, 1024));
  45546. return result;
  45547. };
  45548. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45549. var result = new SceneOptimizerOptions(targetFrameRate);
  45550. var priority = 0;
  45551. result.optimizations.push(new MergeMeshesOptimization(priority));
  45552. result.optimizations.push(new ShadowsOptimization(priority));
  45553. result.optimizations.push(new LensFlaresOptimization(priority));
  45554. // Next priority
  45555. priority++;
  45556. result.optimizations.push(new PostProcessesOptimization(priority));
  45557. result.optimizations.push(new ParticlesOptimization(priority));
  45558. // Next priority
  45559. priority++;
  45560. result.optimizations.push(new TextureOptimization(priority, 512));
  45561. // Next priority
  45562. priority++;
  45563. result.optimizations.push(new RenderTargetsOptimization(priority));
  45564. // Next priority
  45565. priority++;
  45566. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45567. return result;
  45568. };
  45569. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45570. var result = new SceneOptimizerOptions(targetFrameRate);
  45571. var priority = 0;
  45572. result.optimizations.push(new MergeMeshesOptimization(priority));
  45573. result.optimizations.push(new ShadowsOptimization(priority));
  45574. result.optimizations.push(new LensFlaresOptimization(priority));
  45575. // Next priority
  45576. priority++;
  45577. result.optimizations.push(new PostProcessesOptimization(priority));
  45578. result.optimizations.push(new ParticlesOptimization(priority));
  45579. // Next priority
  45580. priority++;
  45581. result.optimizations.push(new TextureOptimization(priority, 256));
  45582. // Next priority
  45583. priority++;
  45584. result.optimizations.push(new RenderTargetsOptimization(priority));
  45585. // Next priority
  45586. priority++;
  45587. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45588. return result;
  45589. };
  45590. return SceneOptimizerOptions;
  45591. })();
  45592. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45593. // Scene optimizer tool
  45594. var SceneOptimizer = (function () {
  45595. function SceneOptimizer() {
  45596. }
  45597. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45598. // TODO: add an epsilon
  45599. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45600. if (onSuccess) {
  45601. onSuccess();
  45602. }
  45603. return;
  45604. }
  45605. // Apply current level of optimizations
  45606. var allDone = true;
  45607. var noOptimizationApplied = true;
  45608. for (var index = 0; index < options.optimizations.length; index++) {
  45609. var optimization = options.optimizations[index];
  45610. if (optimization.priority === currentPriorityLevel) {
  45611. noOptimizationApplied = false;
  45612. allDone = allDone && optimization.apply(scene);
  45613. }
  45614. }
  45615. // If no optimization was applied, this is a failure :(
  45616. if (noOptimizationApplied) {
  45617. if (onFailure) {
  45618. onFailure();
  45619. }
  45620. return;
  45621. }
  45622. // If all optimizations were done, move to next level
  45623. if (allDone) {
  45624. currentPriorityLevel++;
  45625. }
  45626. // Let's the system running for a specific amount of time before checking FPS
  45627. scene.executeWhenReady(function () {
  45628. setTimeout(function () {
  45629. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45630. }, options.trackerDuration);
  45631. });
  45632. };
  45633. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45634. if (!options) {
  45635. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45636. }
  45637. // Let's the system running for a specific amount of time before checking FPS
  45638. scene.executeWhenReady(function () {
  45639. setTimeout(function () {
  45640. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45641. }, options.trackerDuration);
  45642. });
  45643. };
  45644. return SceneOptimizer;
  45645. })();
  45646. BABYLON.SceneOptimizer = SceneOptimizer;
  45647. })(BABYLON || (BABYLON = {}));
  45648. var BABYLON;
  45649. (function (BABYLON) {
  45650. var Internals;
  45651. (function (Internals) {
  45652. var MeshLODLevel = (function () {
  45653. function MeshLODLevel(distance, mesh) {
  45654. this.distance = distance;
  45655. this.mesh = mesh;
  45656. }
  45657. return MeshLODLevel;
  45658. })();
  45659. Internals.MeshLODLevel = MeshLODLevel;
  45660. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45661. })(BABYLON || (BABYLON = {}));
  45662. var BABYLON;
  45663. (function (BABYLON) {
  45664. var RawTexture = (function (_super) {
  45665. __extends(RawTexture, _super);
  45666. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45667. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45668. if (invertY === void 0) { invertY = false; }
  45669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45670. _super.call(this, null, scene, !generateMipMaps, invertY);
  45671. this.format = format;
  45672. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45673. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45674. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45675. }
  45676. RawTexture.prototype.update = function (data) {
  45677. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45678. };
  45679. // Statics
  45680. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45681. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45682. if (invertY === void 0) { invertY = false; }
  45683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45684. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45685. };
  45686. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45687. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45688. if (invertY === void 0) { invertY = false; }
  45689. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45690. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45691. };
  45692. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45693. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45694. if (invertY === void 0) { invertY = false; }
  45695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45696. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45697. };
  45698. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45699. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45700. if (invertY === void 0) { invertY = false; }
  45701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45702. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45703. };
  45704. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45705. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45706. if (invertY === void 0) { invertY = false; }
  45707. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45708. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45709. };
  45710. return RawTexture;
  45711. })(BABYLON.Texture);
  45712. BABYLON.RawTexture = RawTexture;
  45713. })(BABYLON || (BABYLON = {}));
  45714. var BABYLON;
  45715. (function (BABYLON) {
  45716. var IndexedVector2 = (function (_super) {
  45717. __extends(IndexedVector2, _super);
  45718. function IndexedVector2(original, index) {
  45719. _super.call(this, original.x, original.y);
  45720. this.index = index;
  45721. }
  45722. return IndexedVector2;
  45723. })(BABYLON.Vector2);
  45724. var PolygonPoints = (function () {
  45725. function PolygonPoints() {
  45726. this.elements = new Array();
  45727. }
  45728. PolygonPoints.prototype.add = function (originalPoints) {
  45729. var _this = this;
  45730. var result = new Array();
  45731. originalPoints.forEach(function (point) {
  45732. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45733. var newPoint = new IndexedVector2(point, _this.elements.length);
  45734. result.push(newPoint);
  45735. _this.elements.push(newPoint);
  45736. }
  45737. });
  45738. return result;
  45739. };
  45740. PolygonPoints.prototype.computeBounds = function () {
  45741. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45742. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45743. this.elements.forEach(function (point) {
  45744. // x
  45745. if (point.x < lmin.x) {
  45746. lmin.x = point.x;
  45747. }
  45748. else if (point.x > lmax.x) {
  45749. lmax.x = point.x;
  45750. }
  45751. // y
  45752. if (point.y < lmin.y) {
  45753. lmin.y = point.y;
  45754. }
  45755. else if (point.y > lmax.y) {
  45756. lmax.y = point.y;
  45757. }
  45758. });
  45759. return {
  45760. min: lmin,
  45761. max: lmax,
  45762. width: lmax.x - lmin.x,
  45763. height: lmax.y - lmin.y
  45764. };
  45765. };
  45766. return PolygonPoints;
  45767. })();
  45768. var Polygon = (function () {
  45769. function Polygon() {
  45770. }
  45771. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45772. return [
  45773. new BABYLON.Vector2(xmin, ymin),
  45774. new BABYLON.Vector2(xmax, ymin),
  45775. new BABYLON.Vector2(xmax, ymax),
  45776. new BABYLON.Vector2(xmin, ymax)
  45777. ];
  45778. };
  45779. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45780. if (cx === void 0) { cx = 0; }
  45781. if (cy === void 0) { cy = 0; }
  45782. if (numberOfSides === void 0) { numberOfSides = 32; }
  45783. var result = new Array();
  45784. var angle = 0;
  45785. var increment = (Math.PI * 2) / numberOfSides;
  45786. for (var i = 0; i < numberOfSides; i++) {
  45787. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45788. angle -= increment;
  45789. }
  45790. return result;
  45791. };
  45792. Polygon.Parse = function (input) {
  45793. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45794. var i, result = [];
  45795. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45796. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45797. }
  45798. return result;
  45799. };
  45800. Polygon.StartingAt = function (x, y) {
  45801. return BABYLON.Path2.StartingAt(x, y);
  45802. };
  45803. return Polygon;
  45804. })();
  45805. BABYLON.Polygon = Polygon;
  45806. var PolygonMeshBuilder = (function () {
  45807. function PolygonMeshBuilder(name, contours, scene) {
  45808. this._points = new PolygonPoints();
  45809. this._outlinepoints = new PolygonPoints();
  45810. this._holes = [];
  45811. if (!("poly2tri" in window)) {
  45812. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  45813. }
  45814. this._name = name;
  45815. this._scene = scene;
  45816. var points;
  45817. if (contours instanceof BABYLON.Path2) {
  45818. points = contours.getPoints();
  45819. }
  45820. else {
  45821. points = contours;
  45822. }
  45823. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  45824. this._outlinepoints.add(points);
  45825. }
  45826. PolygonMeshBuilder.prototype.addHole = function (hole) {
  45827. this._swctx.addHole(this._points.add(hole));
  45828. var holepoints = new PolygonPoints();
  45829. holepoints.add(hole);
  45830. this._holes.push(holepoints);
  45831. return this;
  45832. };
  45833. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  45834. var _this = this;
  45835. if (updatable === void 0) { updatable = false; }
  45836. var result = new BABYLON.Mesh(this._name, this._scene);
  45837. var normals = [];
  45838. var positions = [];
  45839. var uvs = [];
  45840. var bounds = this._points.computeBounds();
  45841. this._points.elements.forEach(function (p) {
  45842. normals.push(0, 1.0, 0);
  45843. positions.push(p.x, 0, p.y);
  45844. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45845. });
  45846. var indices = [];
  45847. this._swctx.triangulate();
  45848. this._swctx.getTriangles().forEach(function (triangle) {
  45849. triangle.getPoints().forEach(function (point) {
  45850. indices.push(point.index);
  45851. });
  45852. });
  45853. if (depth > 0) {
  45854. var positionscount = (positions.length / 3); //get the current pointcount
  45855. this._points.elements.forEach(function (p) {
  45856. normals.push(0, -1.0, 0);
  45857. positions.push(p.x, -depth, p.y);
  45858. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45859. });
  45860. var p1; //we need to change order of point so the triangles are made in the rigth way.
  45861. var p2;
  45862. var poscounter = 0;
  45863. this._swctx.getTriangles().forEach(function (triangle) {
  45864. triangle.getPoints().forEach(function (point) {
  45865. switch (poscounter) {
  45866. case 0:
  45867. p1 = point;
  45868. break;
  45869. case 1:
  45870. p2 = point;
  45871. break;
  45872. case 2:
  45873. indices.push(point.index + positionscount);
  45874. indices.push(p2.index + positionscount);
  45875. indices.push(p1.index + positionscount);
  45876. poscounter = -1;
  45877. break;
  45878. }
  45879. poscounter++;
  45880. //indices.push((<IndexedVector2>point).index + positionscount);
  45881. });
  45882. });
  45883. //Add the sides
  45884. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45885. this._holes.forEach(function (hole) {
  45886. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45887. });
  45888. }
  45889. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45890. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45891. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45892. result.setIndices(indices);
  45893. return result;
  45894. };
  45895. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45896. var StartIndex = positions.length / 3;
  45897. var ulength = 0;
  45898. for (var i = 0; i < points.elements.length; i++) {
  45899. var p = points.elements[i];
  45900. var p1;
  45901. if ((i + 1) > points.elements.length - 1) {
  45902. p1 = points.elements[0];
  45903. }
  45904. else {
  45905. p1 = points.elements[i + 1];
  45906. }
  45907. positions.push(p.x, 0, p.y);
  45908. positions.push(p.x, -depth, p.y);
  45909. positions.push(p1.x, 0, p1.y);
  45910. positions.push(p1.x, -depth, p1.y);
  45911. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45912. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45913. var v3 = v2.subtract(v1);
  45914. var v4 = new BABYLON.Vector3(0, 1, 0);
  45915. var vn = BABYLON.Vector3.Cross(v3, v4);
  45916. vn = vn.normalize();
  45917. uvs.push(ulength / bounds.width, 0);
  45918. uvs.push(ulength / bounds.width, 1);
  45919. ulength += v3.length();
  45920. uvs.push((ulength / bounds.width), 0);
  45921. uvs.push((ulength / bounds.width), 1);
  45922. if (!flip) {
  45923. normals.push(-vn.x, -vn.y, -vn.z);
  45924. normals.push(-vn.x, -vn.y, -vn.z);
  45925. normals.push(-vn.x, -vn.y, -vn.z);
  45926. normals.push(-vn.x, -vn.y, -vn.z);
  45927. indices.push(StartIndex);
  45928. indices.push(StartIndex + 1);
  45929. indices.push(StartIndex + 2);
  45930. indices.push(StartIndex + 1);
  45931. indices.push(StartIndex + 3);
  45932. indices.push(StartIndex + 2);
  45933. }
  45934. else {
  45935. normals.push(vn.x, vn.y, vn.z);
  45936. normals.push(vn.x, vn.y, vn.z);
  45937. normals.push(vn.x, vn.y, vn.z);
  45938. normals.push(vn.x, vn.y, vn.z);
  45939. indices.push(StartIndex);
  45940. indices.push(StartIndex + 2);
  45941. indices.push(StartIndex + 1);
  45942. indices.push(StartIndex + 1);
  45943. indices.push(StartIndex + 2);
  45944. indices.push(StartIndex + 3);
  45945. }
  45946. StartIndex += 4;
  45947. }
  45948. ;
  45949. };
  45950. return PolygonMeshBuilder;
  45951. })();
  45952. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45953. })(BABYLON || (BABYLON = {}));
  45954. var BABYLON;
  45955. (function (BABYLON) {
  45956. var Octree = (function () {
  45957. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45958. if (maxDepth === void 0) { maxDepth = 2; }
  45959. this.maxDepth = maxDepth;
  45960. this.dynamicContent = new Array();
  45961. this._maxBlockCapacity = maxBlockCapacity || 64;
  45962. this._selectionContent = new BABYLON.SmartArray(1024);
  45963. this._creationFunc = creationFunc;
  45964. }
  45965. // Methods
  45966. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45967. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45968. };
  45969. Octree.prototype.addMesh = function (entry) {
  45970. for (var index = 0; index < this.blocks.length; index++) {
  45971. var block = this.blocks[index];
  45972. block.addEntry(entry);
  45973. }
  45974. };
  45975. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45976. this._selectionContent.reset();
  45977. for (var index = 0; index < this.blocks.length; index++) {
  45978. var block = this.blocks[index];
  45979. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45980. }
  45981. if (allowDuplicate) {
  45982. this._selectionContent.concat(this.dynamicContent);
  45983. }
  45984. else {
  45985. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45986. }
  45987. return this._selectionContent;
  45988. };
  45989. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45990. this._selectionContent.reset();
  45991. for (var index = 0; index < this.blocks.length; index++) {
  45992. var block = this.blocks[index];
  45993. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45994. }
  45995. if (allowDuplicate) {
  45996. this._selectionContent.concat(this.dynamicContent);
  45997. }
  45998. else {
  45999. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46000. }
  46001. return this._selectionContent;
  46002. };
  46003. Octree.prototype.intersectsRay = function (ray) {
  46004. this._selectionContent.reset();
  46005. for (var index = 0; index < this.blocks.length; index++) {
  46006. var block = this.blocks[index];
  46007. block.intersectsRay(ray, this._selectionContent);
  46008. }
  46009. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46010. return this._selectionContent;
  46011. };
  46012. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  46013. target.blocks = new Array();
  46014. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  46015. // Segmenting space
  46016. for (var x = 0; x < 2; x++) {
  46017. for (var y = 0; y < 2; y++) {
  46018. for (var z = 0; z < 2; z++) {
  46019. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  46020. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  46021. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  46022. block.addEntries(entries);
  46023. target.blocks.push(block);
  46024. }
  46025. }
  46026. }
  46027. };
  46028. Octree.CreationFuncForMeshes = function (entry, block) {
  46029. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46030. block.entries.push(entry);
  46031. }
  46032. };
  46033. Octree.CreationFuncForSubMeshes = function (entry, block) {
  46034. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46035. block.entries.push(entry);
  46036. }
  46037. };
  46038. return Octree;
  46039. })();
  46040. BABYLON.Octree = Octree;
  46041. })(BABYLON || (BABYLON = {}));
  46042. var BABYLON;
  46043. (function (BABYLON) {
  46044. var OctreeBlock = (function () {
  46045. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  46046. this.entries = new Array();
  46047. this._boundingVectors = new Array();
  46048. this._capacity = capacity;
  46049. this._depth = depth;
  46050. this._maxDepth = maxDepth;
  46051. this._creationFunc = creationFunc;
  46052. this._minPoint = minPoint;
  46053. this._maxPoint = maxPoint;
  46054. this._boundingVectors.push(minPoint.clone());
  46055. this._boundingVectors.push(maxPoint.clone());
  46056. this._boundingVectors.push(minPoint.clone());
  46057. this._boundingVectors[2].x = maxPoint.x;
  46058. this._boundingVectors.push(minPoint.clone());
  46059. this._boundingVectors[3].y = maxPoint.y;
  46060. this._boundingVectors.push(minPoint.clone());
  46061. this._boundingVectors[4].z = maxPoint.z;
  46062. this._boundingVectors.push(maxPoint.clone());
  46063. this._boundingVectors[5].z = minPoint.z;
  46064. this._boundingVectors.push(maxPoint.clone());
  46065. this._boundingVectors[6].x = minPoint.x;
  46066. this._boundingVectors.push(maxPoint.clone());
  46067. this._boundingVectors[7].y = minPoint.y;
  46068. }
  46069. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  46070. // Property
  46071. get: function () {
  46072. return this._capacity;
  46073. },
  46074. enumerable: true,
  46075. configurable: true
  46076. });
  46077. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  46078. get: function () {
  46079. return this._minPoint;
  46080. },
  46081. enumerable: true,
  46082. configurable: true
  46083. });
  46084. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  46085. get: function () {
  46086. return this._maxPoint;
  46087. },
  46088. enumerable: true,
  46089. configurable: true
  46090. });
  46091. // Methods
  46092. OctreeBlock.prototype.addEntry = function (entry) {
  46093. if (this.blocks) {
  46094. for (var index = 0; index < this.blocks.length; index++) {
  46095. var block = this.blocks[index];
  46096. block.addEntry(entry);
  46097. }
  46098. return;
  46099. }
  46100. this._creationFunc(entry, this);
  46101. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  46102. this.createInnerBlocks();
  46103. }
  46104. };
  46105. OctreeBlock.prototype.addEntries = function (entries) {
  46106. for (var index = 0; index < entries.length; index++) {
  46107. var mesh = entries[index];
  46108. this.addEntry(mesh);
  46109. }
  46110. };
  46111. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  46112. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  46113. if (this.blocks) {
  46114. for (var index = 0; index < this.blocks.length; index++) {
  46115. var block = this.blocks[index];
  46116. block.select(frustumPlanes, selection, allowDuplicate);
  46117. }
  46118. return;
  46119. }
  46120. if (allowDuplicate) {
  46121. selection.concat(this.entries);
  46122. }
  46123. else {
  46124. selection.concatWithNoDuplicate(this.entries);
  46125. }
  46126. }
  46127. };
  46128. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  46129. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  46130. if (this.blocks) {
  46131. for (var index = 0; index < this.blocks.length; index++) {
  46132. var block = this.blocks[index];
  46133. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  46134. }
  46135. return;
  46136. }
  46137. if (allowDuplicate) {
  46138. selection.concat(this.entries);
  46139. }
  46140. else {
  46141. selection.concatWithNoDuplicate(this.entries);
  46142. }
  46143. }
  46144. };
  46145. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  46146. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  46147. if (this.blocks) {
  46148. for (var index = 0; index < this.blocks.length; index++) {
  46149. var block = this.blocks[index];
  46150. block.intersectsRay(ray, selection);
  46151. }
  46152. return;
  46153. }
  46154. selection.concatWithNoDuplicate(this.entries);
  46155. }
  46156. };
  46157. OctreeBlock.prototype.createInnerBlocks = function () {
  46158. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  46159. };
  46160. return OctreeBlock;
  46161. })();
  46162. BABYLON.OctreeBlock = OctreeBlock;
  46163. })(BABYLON || (BABYLON = {}));
  46164. var BABYLON;
  46165. (function (BABYLON) {
  46166. var BlurPostProcess = (function (_super) {
  46167. __extends(BlurPostProcess, _super);
  46168. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  46169. var _this = this;
  46170. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46171. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  46172. this.direction = direction;
  46173. this.blurWidth = blurWidth;
  46174. this.onApplyObservable.add(function (effect) {
  46175. effect.setFloat2("screenSize", _this.width, _this.height);
  46176. effect.setVector2("direction", _this.direction);
  46177. effect.setFloat("blurWidth", _this.blurWidth);
  46178. });
  46179. }
  46180. return BlurPostProcess;
  46181. })(BABYLON.PostProcess);
  46182. BABYLON.BlurPostProcess = BlurPostProcess;
  46183. })(BABYLON || (BABYLON = {}));
  46184. var BABYLON;
  46185. (function (BABYLON) {
  46186. var RefractionPostProcess = (function (_super) {
  46187. __extends(RefractionPostProcess, _super);
  46188. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  46189. var _this = this;
  46190. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  46191. this.color = color;
  46192. this.depth = depth;
  46193. this.colorLevel = colorLevel;
  46194. this.onActivateObservable.add(function (cam) {
  46195. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  46196. });
  46197. this.onApplyObservable.add(function (effect) {
  46198. effect.setColor3("baseColor", _this.color);
  46199. effect.setFloat("depth", _this.depth);
  46200. effect.setFloat("colorLevel", _this.colorLevel);
  46201. effect.setTexture("refractionSampler", _this._refRexture);
  46202. });
  46203. }
  46204. // Methods
  46205. RefractionPostProcess.prototype.dispose = function (camera) {
  46206. if (this._refRexture) {
  46207. this._refRexture.dispose();
  46208. }
  46209. _super.prototype.dispose.call(this, camera);
  46210. };
  46211. return RefractionPostProcess;
  46212. })(BABYLON.PostProcess);
  46213. BABYLON.RefractionPostProcess = RefractionPostProcess;
  46214. })(BABYLON || (BABYLON = {}));
  46215. var BABYLON;
  46216. (function (BABYLON) {
  46217. var BlackAndWhitePostProcess = (function (_super) {
  46218. __extends(BlackAndWhitePostProcess, _super);
  46219. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  46220. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  46221. }
  46222. return BlackAndWhitePostProcess;
  46223. })(BABYLON.PostProcess);
  46224. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  46225. })(BABYLON || (BABYLON = {}));
  46226. var BABYLON;
  46227. (function (BABYLON) {
  46228. var ConvolutionPostProcess = (function (_super) {
  46229. __extends(ConvolutionPostProcess, _super);
  46230. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  46231. var _this = this;
  46232. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  46233. this.kernel = kernel;
  46234. this.onApply = function (effect) {
  46235. effect.setFloat2("screenSize", _this.width, _this.height);
  46236. effect.setArray("kernel", _this.kernel);
  46237. };
  46238. }
  46239. // Statics
  46240. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  46241. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  46242. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  46243. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  46244. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  46245. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  46246. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  46247. return ConvolutionPostProcess;
  46248. })(BABYLON.PostProcess);
  46249. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  46250. })(BABYLON || (BABYLON = {}));
  46251. var BABYLON;
  46252. (function (BABYLON) {
  46253. var FilterPostProcess = (function (_super) {
  46254. __extends(FilterPostProcess, _super);
  46255. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  46256. var _this = this;
  46257. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  46258. this.kernelMatrix = kernelMatrix;
  46259. this.onApply = function (effect) {
  46260. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  46261. };
  46262. }
  46263. return FilterPostProcess;
  46264. })(BABYLON.PostProcess);
  46265. BABYLON.FilterPostProcess = FilterPostProcess;
  46266. })(BABYLON || (BABYLON = {}));
  46267. var BABYLON;
  46268. (function (BABYLON) {
  46269. var FxaaPostProcess = (function (_super) {
  46270. __extends(FxaaPostProcess, _super);
  46271. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46272. var _this = this;
  46273. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  46274. this.onSizeChangedObservable.add(function () {
  46275. _this.texelWidth = 1.0 / _this.width;
  46276. _this.texelHeight = 1.0 / _this.height;
  46277. });
  46278. this.onApplyObservable.add(function (effect) {
  46279. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  46280. });
  46281. }
  46282. return FxaaPostProcess;
  46283. })(BABYLON.PostProcess);
  46284. BABYLON.FxaaPostProcess = FxaaPostProcess;
  46285. })(BABYLON || (BABYLON = {}));
  46286. var BABYLON;
  46287. (function (BABYLON) {
  46288. var StereoscopicInterlacePostProcess = (function (_super) {
  46289. __extends(StereoscopicInterlacePostProcess, _super);
  46290. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  46291. var _this = this;
  46292. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  46293. this._passedProcess = rigCameras[0]._rigPostProcess;
  46294. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  46295. this.onSizeChangedObservable.add(function () {
  46296. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46297. });
  46298. this.onApplyObservable.add(function (effect) {
  46299. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  46300. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  46301. });
  46302. }
  46303. return StereoscopicInterlacePostProcess;
  46304. })(BABYLON.PostProcess);
  46305. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  46306. })(BABYLON || (BABYLON = {}));
  46307. var BABYLON;
  46308. (function (BABYLON) {
  46309. var LensFlare = (function () {
  46310. function LensFlare(size, position, color, imgUrl, system) {
  46311. this.size = size;
  46312. this.position = position;
  46313. this.dispose = function () {
  46314. if (this.texture) {
  46315. this.texture.dispose();
  46316. }
  46317. // Remove from scene
  46318. var index = this._system.lensFlares.indexOf(this);
  46319. this._system.lensFlares.splice(index, 1);
  46320. };
  46321. this.color = color || new BABYLON.Color3(1, 1, 1);
  46322. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  46323. this._system = system;
  46324. system.lensFlares.push(this);
  46325. }
  46326. return LensFlare;
  46327. })();
  46328. BABYLON.LensFlare = LensFlare;
  46329. })(BABYLON || (BABYLON = {}));
  46330. var BABYLON;
  46331. (function (BABYLON) {
  46332. var LensFlareSystem = (function () {
  46333. function LensFlareSystem(name, emitter, scene) {
  46334. this.name = name;
  46335. this.lensFlares = new Array();
  46336. this.borderLimit = 300;
  46337. this.layerMask = 0x0FFFFFFF;
  46338. this._vertexDeclaration = [2];
  46339. this._vertexStrideSize = 2 * 4;
  46340. this._isEnabled = true;
  46341. this._scene = scene;
  46342. this._emitter = emitter;
  46343. this.id = name;
  46344. scene.lensFlareSystems.push(this);
  46345. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46346. // VBO
  46347. var vertices = [];
  46348. vertices.push(1, 1);
  46349. vertices.push(-1, 1);
  46350. vertices.push(-1, -1);
  46351. vertices.push(1, -1);
  46352. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  46353. // Indices
  46354. var indices = [];
  46355. indices.push(0);
  46356. indices.push(1);
  46357. indices.push(2);
  46358. indices.push(0);
  46359. indices.push(2);
  46360. indices.push(3);
  46361. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46362. // Effects
  46363. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  46364. }
  46365. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46366. get: function () {
  46367. return this._isEnabled;
  46368. },
  46369. set: function (value) {
  46370. this._isEnabled = value;
  46371. },
  46372. enumerable: true,
  46373. configurable: true
  46374. });
  46375. LensFlareSystem.prototype.getScene = function () {
  46376. return this._scene;
  46377. };
  46378. LensFlareSystem.prototype.getEmitter = function () {
  46379. return this._emitter;
  46380. };
  46381. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46382. this._emitter = newEmitter;
  46383. };
  46384. LensFlareSystem.prototype.getEmitterPosition = function () {
  46385. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46386. };
  46387. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46388. var position = this.getEmitterPosition();
  46389. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46390. this._positionX = position.x;
  46391. this._positionY = position.y;
  46392. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46393. if (position.z > 0) {
  46394. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46395. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46396. return true;
  46397. }
  46398. }
  46399. return false;
  46400. };
  46401. LensFlareSystem.prototype._isVisible = function () {
  46402. if (!this._isEnabled) {
  46403. return false;
  46404. }
  46405. var emitterPosition = this.getEmitterPosition();
  46406. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  46407. var distance = direction.length();
  46408. direction.normalize();
  46409. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  46410. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46411. return !pickInfo.hit || pickInfo.distance > distance;
  46412. };
  46413. LensFlareSystem.prototype.render = function () {
  46414. if (!this._effect.isReady())
  46415. return false;
  46416. var engine = this._scene.getEngine();
  46417. var viewport = this._scene.activeCamera.viewport;
  46418. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46419. // Position
  46420. if (!this.computeEffectivePosition(globalViewport)) {
  46421. return false;
  46422. }
  46423. // Visibility
  46424. if (!this._isVisible()) {
  46425. return false;
  46426. }
  46427. // Intensity
  46428. var awayX;
  46429. var awayY;
  46430. if (this._positionX < this.borderLimit + globalViewport.x) {
  46431. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46432. }
  46433. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46434. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46435. }
  46436. else {
  46437. awayX = 0;
  46438. }
  46439. if (this._positionY < this.borderLimit + globalViewport.y) {
  46440. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46441. }
  46442. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46443. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46444. }
  46445. else {
  46446. awayY = 0;
  46447. }
  46448. var away = (awayX > awayY) ? awayX : awayY;
  46449. if (away > this.borderLimit) {
  46450. away = this.borderLimit;
  46451. }
  46452. var intensity = 1.0 - (away / this.borderLimit);
  46453. if (intensity < 0) {
  46454. return false;
  46455. }
  46456. if (intensity > 1.0) {
  46457. intensity = 1.0;
  46458. }
  46459. // Position
  46460. var centerX = globalViewport.x + globalViewport.width / 2;
  46461. var centerY = globalViewport.y + globalViewport.height / 2;
  46462. var distX = centerX - this._positionX;
  46463. var distY = centerY - this._positionY;
  46464. // Effects
  46465. engine.enableEffect(this._effect);
  46466. engine.setState(false);
  46467. engine.setDepthBuffer(false);
  46468. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46469. // VBOs
  46470. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  46471. // Flares
  46472. for (var index = 0; index < this.lensFlares.length; index++) {
  46473. var flare = this.lensFlares[index];
  46474. var x = centerX - (distX * flare.position);
  46475. var y = centerY - (distY * flare.position);
  46476. var cw = flare.size;
  46477. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46478. var cx = 2 * (x / globalViewport.width) - 1.0;
  46479. var cy = 1.0 - 2 * (y / globalViewport.height);
  46480. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46481. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46482. // Texture
  46483. this._effect.setTexture("textureSampler", flare.texture);
  46484. // Color
  46485. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46486. // Draw order
  46487. engine.draw(true, 0, 6);
  46488. }
  46489. engine.setDepthBuffer(true);
  46490. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46491. return true;
  46492. };
  46493. LensFlareSystem.prototype.dispose = function () {
  46494. if (this._vertexBuffer) {
  46495. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  46496. this._vertexBuffer = null;
  46497. }
  46498. if (this._indexBuffer) {
  46499. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46500. this._indexBuffer = null;
  46501. }
  46502. while (this.lensFlares.length) {
  46503. this.lensFlares[0].dispose();
  46504. }
  46505. // Remove from scene
  46506. var index = this._scene.lensFlareSystems.indexOf(this);
  46507. this._scene.lensFlareSystems.splice(index, 1);
  46508. };
  46509. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46510. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46511. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46512. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46513. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46514. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46515. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46516. var parsedFlare = parsedLensFlareSystem.flares[index];
  46517. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46518. }
  46519. return lensFlareSystem;
  46520. };
  46521. LensFlareSystem.prototype.serialize = function () {
  46522. var serializationObject = {};
  46523. serializationObject.id = this.id;
  46524. serializationObject.name = this.name;
  46525. serializationObject.emitterId = this.getEmitter().id;
  46526. serializationObject.borderLimit = this.borderLimit;
  46527. serializationObject.flares = [];
  46528. for (var index = 0; index < this.lensFlares.length; index++) {
  46529. var flare = this.lensFlares[index];
  46530. serializationObject.flares.push({
  46531. size: flare.size,
  46532. position: flare.position,
  46533. color: flare.color.asArray(),
  46534. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46535. });
  46536. }
  46537. return serializationObject;
  46538. };
  46539. return LensFlareSystem;
  46540. })();
  46541. BABYLON.LensFlareSystem = LensFlareSystem;
  46542. })(BABYLON || (BABYLON = {}));
  46543. var BABYLON;
  46544. (function (BABYLON) {
  46545. // We're mainly based on the logic defined into the FreeCamera code
  46546. var DeviceOrientationCamera = (function (_super) {
  46547. __extends(DeviceOrientationCamera, _super);
  46548. //-- end properties for backward compatibility for inputs
  46549. function DeviceOrientationCamera(name, position, scene) {
  46550. _super.call(this, name, position, scene);
  46551. this.inputs.addDeviceOrientation();
  46552. }
  46553. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  46554. //-- Begin properties for backward compatibility for inputs
  46555. get: function () {
  46556. return 0;
  46557. },
  46558. set: function (value) {
  46559. },
  46560. enumerable: true,
  46561. configurable: true
  46562. });
  46563. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  46564. get: function () {
  46565. return 0;
  46566. },
  46567. set: function (value) {
  46568. },
  46569. enumerable: true,
  46570. configurable: true
  46571. });
  46572. DeviceOrientationCamera.prototype.getTypeName = function () {
  46573. return "DeviceOrientationCamera";
  46574. };
  46575. return DeviceOrientationCamera;
  46576. })(BABYLON.FreeCamera);
  46577. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46578. })(BABYLON || (BABYLON = {}));
  46579. var BABYLON;
  46580. (function (BABYLON) {
  46581. // We're mainly based on the logic defined into the FreeCamera code
  46582. var UniversalCamera = (function (_super) {
  46583. __extends(UniversalCamera, _super);
  46584. //-- end properties for backward compatibility for inputs
  46585. function UniversalCamera(name, position, scene) {
  46586. _super.call(this, name, position, scene);
  46587. this.inputs.addGamepad();
  46588. }
  46589. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46590. //-- Begin properties for backward compatibility for inputs
  46591. get: function () {
  46592. var gamepad = this.inputs.attached["gamepad"];
  46593. if (gamepad)
  46594. return gamepad.gamepadAngularSensibility;
  46595. },
  46596. set: function (value) {
  46597. var gamepad = this.inputs.attached["gamepad"];
  46598. if (gamepad)
  46599. gamepad.gamepadAngularSensibility = value;
  46600. },
  46601. enumerable: true,
  46602. configurable: true
  46603. });
  46604. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46605. get: function () {
  46606. var gamepad = this.inputs.attached["gamepad"];
  46607. if (gamepad)
  46608. return gamepad.gamepadMoveSensibility;
  46609. },
  46610. set: function (value) {
  46611. var gamepad = this.inputs.attached["gamepad"];
  46612. if (gamepad)
  46613. gamepad.gamepadMoveSensibility = value;
  46614. },
  46615. enumerable: true,
  46616. configurable: true
  46617. });
  46618. UniversalCamera.prototype.getTypeName = function () {
  46619. return "UniversalCamera";
  46620. };
  46621. return UniversalCamera;
  46622. })(BABYLON.TouchCamera);
  46623. BABYLON.UniversalCamera = UniversalCamera;
  46624. })(BABYLON || (BABYLON = {}));
  46625. var BABYLON;
  46626. (function (BABYLON) {
  46627. var Gamepads = (function () {
  46628. function Gamepads(ongamedpadconnected) {
  46629. var _this = this;
  46630. this.babylonGamepads = [];
  46631. this.oneGamepadConnected = false;
  46632. this.isMonitoring = false;
  46633. this.gamepadEventSupported = 'GamepadEvent' in window;
  46634. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46635. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46636. this._callbackGamepadConnected = ongamedpadconnected;
  46637. if (this.gamepadSupportAvailable) {
  46638. // Checking if the gamepad connected event is supported (like in Firefox)
  46639. if (this.gamepadEventSupported) {
  46640. this._onGamepadConnectedEvent = function (evt) {
  46641. _this._onGamepadConnected(evt);
  46642. };
  46643. this._onGamepadDisonnectedEvent = function (evt) {
  46644. _this._onGamepadDisconnected(evt);
  46645. };
  46646. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46647. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46648. }
  46649. else {
  46650. this._startMonitoringGamepads();
  46651. }
  46652. }
  46653. }
  46654. Gamepads.prototype.dispose = function () {
  46655. if (Gamepads.gamepadDOMInfo) {
  46656. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46657. }
  46658. if (this._onGamepadConnectedEvent) {
  46659. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46660. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46661. this._onGamepadConnectedEvent = null;
  46662. this._onGamepadDisonnectedEvent = null;
  46663. }
  46664. };
  46665. Gamepads.prototype._onGamepadConnected = function (evt) {
  46666. var newGamepad = this._addNewGamepad(evt.gamepad);
  46667. if (this._callbackGamepadConnected)
  46668. this._callbackGamepadConnected(newGamepad);
  46669. this._startMonitoringGamepads();
  46670. };
  46671. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46672. if (!this.oneGamepadConnected) {
  46673. this.oneGamepadConnected = true;
  46674. if (Gamepads.gamepadDOMInfo) {
  46675. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46676. Gamepads.gamepadDOMInfo = null;
  46677. }
  46678. }
  46679. var newGamepad;
  46680. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46681. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  46682. }
  46683. else {
  46684. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46685. }
  46686. this.babylonGamepads.push(newGamepad);
  46687. return newGamepad;
  46688. };
  46689. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46690. // Remove the gamepad from the list of gamepads to monitor.
  46691. for (var i in this.babylonGamepads) {
  46692. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46693. this.babylonGamepads.splice(+i, 1);
  46694. break;
  46695. }
  46696. }
  46697. // If no gamepads are left, stop the polling loop.
  46698. if (this.babylonGamepads.length == 0) {
  46699. this._stopMonitoringGamepads();
  46700. }
  46701. };
  46702. Gamepads.prototype._startMonitoringGamepads = function () {
  46703. if (!this.isMonitoring) {
  46704. this.isMonitoring = true;
  46705. this._checkGamepadsStatus();
  46706. }
  46707. };
  46708. Gamepads.prototype._stopMonitoringGamepads = function () {
  46709. this.isMonitoring = false;
  46710. };
  46711. Gamepads.prototype._checkGamepadsStatus = function () {
  46712. var _this = this;
  46713. // updating gamepad objects
  46714. this._updateGamepadObjects();
  46715. for (var i in this.babylonGamepads) {
  46716. this.babylonGamepads[i].update();
  46717. }
  46718. if (this.isMonitoring) {
  46719. if (window.requestAnimationFrame) {
  46720. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46721. }
  46722. else if (window.mozRequestAnimationFrame) {
  46723. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46724. }
  46725. else if (window.webkitRequestAnimationFrame) {
  46726. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46727. }
  46728. }
  46729. };
  46730. // This function is called only on Chrome, which does not yet support
  46731. // connection/disconnection events, but requires you to monitor
  46732. // an array for changes.
  46733. Gamepads.prototype._updateGamepadObjects = function () {
  46734. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  46735. for (var i = 0; i < gamepads.length; i++) {
  46736. if (gamepads[i]) {
  46737. if (!(gamepads[i].index in this.babylonGamepads)) {
  46738. var newGamepad = this._addNewGamepad(gamepads[i]);
  46739. if (this._callbackGamepadConnected) {
  46740. this._callbackGamepadConnected(newGamepad);
  46741. }
  46742. }
  46743. else {
  46744. this.babylonGamepads[i].browserGamepad = gamepads[i];
  46745. }
  46746. }
  46747. }
  46748. };
  46749. return Gamepads;
  46750. })();
  46751. BABYLON.Gamepads = Gamepads;
  46752. var StickValues = (function () {
  46753. function StickValues(x, y) {
  46754. this.x = x;
  46755. this.y = y;
  46756. }
  46757. return StickValues;
  46758. })();
  46759. BABYLON.StickValues = StickValues;
  46760. var Gamepad = (function () {
  46761. function Gamepad(id, index, browserGamepad) {
  46762. this.id = id;
  46763. this.index = index;
  46764. this.browserGamepad = browserGamepad;
  46765. if (this.browserGamepad.axes.length >= 2) {
  46766. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  46767. }
  46768. if (this.browserGamepad.axes.length >= 4) {
  46769. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  46770. }
  46771. }
  46772. Gamepad.prototype.onleftstickchanged = function (callback) {
  46773. this._onleftstickchanged = callback;
  46774. };
  46775. Gamepad.prototype.onrightstickchanged = function (callback) {
  46776. this._onrightstickchanged = callback;
  46777. };
  46778. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46779. get: function () {
  46780. return this._leftStick;
  46781. },
  46782. set: function (newValues) {
  46783. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46784. this._onleftstickchanged(newValues);
  46785. }
  46786. this._leftStick = newValues;
  46787. },
  46788. enumerable: true,
  46789. configurable: true
  46790. });
  46791. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46792. get: function () {
  46793. return this._rightStick;
  46794. },
  46795. set: function (newValues) {
  46796. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46797. this._onrightstickchanged(newValues);
  46798. }
  46799. this._rightStick = newValues;
  46800. },
  46801. enumerable: true,
  46802. configurable: true
  46803. });
  46804. Gamepad.prototype.update = function () {
  46805. if (this._leftStick) {
  46806. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  46807. }
  46808. if (this._rightStick) {
  46809. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  46810. }
  46811. };
  46812. return Gamepad;
  46813. })();
  46814. BABYLON.Gamepad = Gamepad;
  46815. var GenericPad = (function (_super) {
  46816. __extends(GenericPad, _super);
  46817. function GenericPad(id, index, gamepad) {
  46818. _super.call(this, id, index, gamepad);
  46819. this.id = id;
  46820. this.index = index;
  46821. this.gamepad = gamepad;
  46822. this._buttons = new Array(gamepad.buttons.length);
  46823. }
  46824. GenericPad.prototype.onbuttondown = function (callback) {
  46825. this._onbuttondown = callback;
  46826. };
  46827. GenericPad.prototype.onbuttonup = function (callback) {
  46828. this._onbuttonup = callback;
  46829. };
  46830. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46831. if (newValue !== currentValue) {
  46832. if (this._onbuttondown && newValue === 1) {
  46833. this._onbuttondown(buttonIndex);
  46834. }
  46835. if (this._onbuttonup && newValue === 0) {
  46836. this._onbuttonup(buttonIndex);
  46837. }
  46838. }
  46839. return newValue;
  46840. };
  46841. GenericPad.prototype.update = function () {
  46842. _super.prototype.update.call(this);
  46843. for (var index = 0; index < this._buttons.length; index++) {
  46844. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46845. }
  46846. };
  46847. return GenericPad;
  46848. })(Gamepad);
  46849. BABYLON.GenericPad = GenericPad;
  46850. (function (Xbox360Button) {
  46851. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46852. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46853. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46854. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46855. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46856. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46857. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46858. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46859. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46860. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46861. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46862. var Xbox360Button = BABYLON.Xbox360Button;
  46863. (function (Xbox360Dpad) {
  46864. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46865. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46866. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46867. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46868. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46869. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  46870. var Xbox360Pad = (function (_super) {
  46871. __extends(Xbox360Pad, _super);
  46872. function Xbox360Pad() {
  46873. _super.apply(this, arguments);
  46874. this._leftTrigger = 0;
  46875. this._rightTrigger = 0;
  46876. this._buttonA = 0;
  46877. this._buttonB = 0;
  46878. this._buttonX = 0;
  46879. this._buttonY = 0;
  46880. this._buttonBack = 0;
  46881. this._buttonStart = 0;
  46882. this._buttonLB = 0;
  46883. this._buttonRB = 0;
  46884. this._buttonLeftStick = 0;
  46885. this._buttonRightStick = 0;
  46886. this._dPadUp = 0;
  46887. this._dPadDown = 0;
  46888. this._dPadLeft = 0;
  46889. this._dPadRight = 0;
  46890. }
  46891. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46892. this._onlefttriggerchanged = callback;
  46893. };
  46894. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46895. this._onrighttriggerchanged = callback;
  46896. };
  46897. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46898. get: function () {
  46899. return this._leftTrigger;
  46900. },
  46901. set: function (newValue) {
  46902. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46903. this._onlefttriggerchanged(newValue);
  46904. }
  46905. this._leftTrigger = newValue;
  46906. },
  46907. enumerable: true,
  46908. configurable: true
  46909. });
  46910. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46911. get: function () {
  46912. return this._rightTrigger;
  46913. },
  46914. set: function (newValue) {
  46915. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46916. this._onrighttriggerchanged(newValue);
  46917. }
  46918. this._rightTrigger = newValue;
  46919. },
  46920. enumerable: true,
  46921. configurable: true
  46922. });
  46923. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46924. this._onbuttondown = callback;
  46925. };
  46926. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46927. this._onbuttonup = callback;
  46928. };
  46929. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46930. this._ondpaddown = callback;
  46931. };
  46932. Xbox360Pad.prototype.ondpadup = function (callback) {
  46933. this._ondpadup = callback;
  46934. };
  46935. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46936. if (newValue !== currentValue) {
  46937. if (this._onbuttondown && newValue === 1) {
  46938. this._onbuttondown(buttonType);
  46939. }
  46940. if (this._onbuttonup && newValue === 0) {
  46941. this._onbuttonup(buttonType);
  46942. }
  46943. }
  46944. return newValue;
  46945. };
  46946. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46947. if (newValue !== currentValue) {
  46948. if (this._ondpaddown && newValue === 1) {
  46949. this._ondpaddown(buttonType);
  46950. }
  46951. if (this._ondpadup && newValue === 0) {
  46952. this._ondpadup(buttonType);
  46953. }
  46954. }
  46955. return newValue;
  46956. };
  46957. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46958. get: function () {
  46959. return this._buttonA;
  46960. },
  46961. set: function (value) {
  46962. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46963. },
  46964. enumerable: true,
  46965. configurable: true
  46966. });
  46967. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46968. get: function () {
  46969. return this._buttonB;
  46970. },
  46971. set: function (value) {
  46972. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46973. },
  46974. enumerable: true,
  46975. configurable: true
  46976. });
  46977. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46978. get: function () {
  46979. return this._buttonX;
  46980. },
  46981. set: function (value) {
  46982. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46983. },
  46984. enumerable: true,
  46985. configurable: true
  46986. });
  46987. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46988. get: function () {
  46989. return this._buttonY;
  46990. },
  46991. set: function (value) {
  46992. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46993. },
  46994. enumerable: true,
  46995. configurable: true
  46996. });
  46997. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46998. get: function () {
  46999. return this._buttonStart;
  47000. },
  47001. set: function (value) {
  47002. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47003. },
  47004. enumerable: true,
  47005. configurable: true
  47006. });
  47007. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47008. get: function () {
  47009. return this._buttonBack;
  47010. },
  47011. set: function (value) {
  47012. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47013. },
  47014. enumerable: true,
  47015. configurable: true
  47016. });
  47017. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47018. get: function () {
  47019. return this._buttonLB;
  47020. },
  47021. set: function (value) {
  47022. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47023. },
  47024. enumerable: true,
  47025. configurable: true
  47026. });
  47027. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47028. get: function () {
  47029. return this._buttonRB;
  47030. },
  47031. set: function (value) {
  47032. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47033. },
  47034. enumerable: true,
  47035. configurable: true
  47036. });
  47037. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47038. get: function () {
  47039. return this._buttonLeftStick;
  47040. },
  47041. set: function (value) {
  47042. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47043. },
  47044. enumerable: true,
  47045. configurable: true
  47046. });
  47047. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47048. get: function () {
  47049. return this._buttonRightStick;
  47050. },
  47051. set: function (value) {
  47052. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47053. },
  47054. enumerable: true,
  47055. configurable: true
  47056. });
  47057. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47058. get: function () {
  47059. return this._dPadUp;
  47060. },
  47061. set: function (value) {
  47062. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47063. },
  47064. enumerable: true,
  47065. configurable: true
  47066. });
  47067. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47068. get: function () {
  47069. return this._dPadDown;
  47070. },
  47071. set: function (value) {
  47072. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47073. },
  47074. enumerable: true,
  47075. configurable: true
  47076. });
  47077. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47078. get: function () {
  47079. return this._dPadLeft;
  47080. },
  47081. set: function (value) {
  47082. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47083. },
  47084. enumerable: true,
  47085. configurable: true
  47086. });
  47087. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47088. get: function () {
  47089. return this._dPadRight;
  47090. },
  47091. set: function (value) {
  47092. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47093. },
  47094. enumerable: true,
  47095. configurable: true
  47096. });
  47097. Xbox360Pad.prototype.update = function () {
  47098. _super.prototype.update.call(this);
  47099. this.buttonA = this.browserGamepad.buttons[0].value;
  47100. this.buttonB = this.browserGamepad.buttons[1].value;
  47101. this.buttonX = this.browserGamepad.buttons[2].value;
  47102. this.buttonY = this.browserGamepad.buttons[3].value;
  47103. this.buttonLB = this.browserGamepad.buttons[4].value;
  47104. this.buttonRB = this.browserGamepad.buttons[5].value;
  47105. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47106. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47107. this.buttonBack = this.browserGamepad.buttons[8].value;
  47108. this.buttonStart = this.browserGamepad.buttons[9].value;
  47109. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47110. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47111. this.dPadUp = this.browserGamepad.buttons[12].value;
  47112. this.dPadDown = this.browserGamepad.buttons[13].value;
  47113. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47114. this.dPadRight = this.browserGamepad.buttons[15].value;
  47115. };
  47116. return Xbox360Pad;
  47117. })(Gamepad);
  47118. BABYLON.Xbox360Pad = Xbox360Pad;
  47119. })(BABYLON || (BABYLON = {}));
  47120. var BABYLON;
  47121. (function (BABYLON) {
  47122. // We're mainly based on the logic defined into the FreeCamera code
  47123. var GamepadCamera = (function (_super) {
  47124. __extends(GamepadCamera, _super);
  47125. //-- end properties for backward compatibility for inputs
  47126. function GamepadCamera(name, position, scene) {
  47127. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  47128. _super.call(this, name, position, scene);
  47129. }
  47130. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  47131. //-- Begin properties for backward compatibility for inputs
  47132. get: function () {
  47133. var gamepad = this.inputs.attached["gamepad"];
  47134. if (gamepad)
  47135. return gamepad.gamepadAngularSensibility;
  47136. },
  47137. set: function (value) {
  47138. var gamepad = this.inputs.attached["gamepad"];
  47139. if (gamepad)
  47140. gamepad.gamepadAngularSensibility = value;
  47141. },
  47142. enumerable: true,
  47143. configurable: true
  47144. });
  47145. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  47146. get: function () {
  47147. var gamepad = this.inputs.attached["gamepad"];
  47148. if (gamepad)
  47149. return gamepad.gamepadMoveSensibility;
  47150. },
  47151. set: function (value) {
  47152. var gamepad = this.inputs.attached["gamepad"];
  47153. if (gamepad)
  47154. gamepad.gamepadMoveSensibility = value;
  47155. },
  47156. enumerable: true,
  47157. configurable: true
  47158. });
  47159. GamepadCamera.prototype.getTypeName = function () {
  47160. return "GamepadCamera";
  47161. };
  47162. return GamepadCamera;
  47163. })(BABYLON.UniversalCamera);
  47164. BABYLON.GamepadCamera = GamepadCamera;
  47165. })(BABYLON || (BABYLON = {}));
  47166. var BABYLON;
  47167. (function (BABYLON) {
  47168. var Analyser = (function () {
  47169. function Analyser(scene) {
  47170. this.SMOOTHING = 0.75;
  47171. this.FFT_SIZE = 512;
  47172. this.BARGRAPHAMPLITUDE = 256;
  47173. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47174. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47175. this._scene = scene;
  47176. this._audioEngine = BABYLON.Engine.audioEngine;
  47177. if (this._audioEngine.canUseWebAudio) {
  47178. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47179. this._webAudioAnalyser.minDecibels = -140;
  47180. this._webAudioAnalyser.maxDecibels = 0;
  47181. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47182. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47183. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47184. }
  47185. }
  47186. Analyser.prototype.getFrequencyBinCount = function () {
  47187. if (this._audioEngine.canUseWebAudio) {
  47188. return this._webAudioAnalyser.frequencyBinCount;
  47189. }
  47190. else {
  47191. return 0;
  47192. }
  47193. };
  47194. Analyser.prototype.getByteFrequencyData = function () {
  47195. if (this._audioEngine.canUseWebAudio) {
  47196. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47197. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47198. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47199. }
  47200. return this._byteFreqs;
  47201. };
  47202. Analyser.prototype.getByteTimeDomainData = function () {
  47203. if (this._audioEngine.canUseWebAudio) {
  47204. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47205. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47206. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47207. }
  47208. return this._byteTime;
  47209. };
  47210. Analyser.prototype.getFloatFrequencyData = function () {
  47211. if (this._audioEngine.canUseWebAudio) {
  47212. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47213. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47214. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47215. }
  47216. return this._floatFreqs;
  47217. };
  47218. Analyser.prototype.drawDebugCanvas = function () {
  47219. var _this = this;
  47220. if (this._audioEngine.canUseWebAudio) {
  47221. if (!this._debugCanvas) {
  47222. this._debugCanvas = document.createElement("canvas");
  47223. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47224. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47225. this._debugCanvas.style.position = "absolute";
  47226. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47227. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47228. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47229. document.body.appendChild(this._debugCanvas);
  47230. this._registerFunc = function () {
  47231. _this.drawDebugCanvas();
  47232. };
  47233. this._scene.registerBeforeRender(this._registerFunc);
  47234. }
  47235. if (this._registerFunc) {
  47236. var workingArray = this.getByteFrequencyData();
  47237. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47238. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47239. // Draw the frequency domain chart.
  47240. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47241. var value = workingArray[i];
  47242. var percent = value / this.BARGRAPHAMPLITUDE;
  47243. var height = this.DEBUGCANVASSIZE.height * percent;
  47244. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47245. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47246. var hue = i / this.getFrequencyBinCount() * 360;
  47247. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47248. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47249. }
  47250. }
  47251. }
  47252. };
  47253. Analyser.prototype.stopDebugCanvas = function () {
  47254. if (this._debugCanvas) {
  47255. this._scene.unregisterBeforeRender(this._registerFunc);
  47256. this._registerFunc = null;
  47257. document.body.removeChild(this._debugCanvas);
  47258. this._debugCanvas = null;
  47259. this._debugCanvasContext = null;
  47260. }
  47261. };
  47262. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47263. if (this._audioEngine.canUseWebAudio) {
  47264. inputAudioNode.connect(this._webAudioAnalyser);
  47265. this._webAudioAnalyser.connect(outputAudioNode);
  47266. }
  47267. };
  47268. Analyser.prototype.dispose = function () {
  47269. if (this._audioEngine.canUseWebAudio) {
  47270. this._webAudioAnalyser.disconnect();
  47271. }
  47272. };
  47273. return Analyser;
  47274. })();
  47275. BABYLON.Analyser = Analyser;
  47276. })(BABYLON || (BABYLON = {}));
  47277. var BABYLON;
  47278. (function (BABYLON) {
  47279. var DepthRenderer = (function () {
  47280. function DepthRenderer(scene, type) {
  47281. var _this = this;
  47282. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47283. this._viewMatrix = BABYLON.Matrix.Zero();
  47284. this._projectionMatrix = BABYLON.Matrix.Zero();
  47285. this._transformMatrix = BABYLON.Matrix.Zero();
  47286. this._worldViewProjection = BABYLON.Matrix.Zero();
  47287. this._scene = scene;
  47288. var engine = scene.getEngine();
  47289. // Render target
  47290. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47291. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47292. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47293. this._depthMap.refreshRate = 1;
  47294. this._depthMap.renderParticles = false;
  47295. this._depthMap.renderList = null;
  47296. // set default depth value to 1.0 (far away)
  47297. this._depthMap.onClearObservable.add(function (engine) {
  47298. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  47299. });
  47300. // Custom render function
  47301. var renderSubMesh = function (subMesh) {
  47302. var mesh = subMesh.getRenderingMesh();
  47303. var scene = _this._scene;
  47304. var engine = scene.getEngine();
  47305. // Culling
  47306. engine.setState(subMesh.getMaterial().backFaceCulling);
  47307. // Managing instances
  47308. var batch = mesh._getInstancesRenderList(subMesh._id);
  47309. if (batch.mustReturn) {
  47310. return;
  47311. }
  47312. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47313. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47314. engine.enableEffect(_this._effect);
  47315. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47316. var material = subMesh.getMaterial();
  47317. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47318. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47319. // Alpha test
  47320. if (material && material.needAlphaTesting()) {
  47321. var alphaTexture = material.getAlphaTestTexture();
  47322. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47323. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47324. }
  47325. // Bones
  47326. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47327. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47328. }
  47329. // Draw
  47330. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47331. }
  47332. };
  47333. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47334. var index;
  47335. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47336. renderSubMesh(opaqueSubMeshes.data[index]);
  47337. }
  47338. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47339. renderSubMesh(alphaTestSubMeshes.data[index]);
  47340. }
  47341. };
  47342. }
  47343. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47344. var material = subMesh.getMaterial();
  47345. if (material.disableDepthWrite) {
  47346. return false;
  47347. }
  47348. var defines = [];
  47349. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47350. var mesh = subMesh.getMesh();
  47351. var scene = mesh.getScene();
  47352. // Alpha test
  47353. if (material && material.needAlphaTesting()) {
  47354. defines.push("#define ALPHATEST");
  47355. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47356. attribs.push(BABYLON.VertexBuffer.UVKind);
  47357. defines.push("#define UV1");
  47358. }
  47359. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47360. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47361. defines.push("#define UV2");
  47362. }
  47363. }
  47364. // Bones
  47365. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47368. if (mesh.numBoneInfluencers > 4) {
  47369. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47370. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47371. }
  47372. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47373. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47374. }
  47375. else {
  47376. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47377. }
  47378. // Instances
  47379. if (useInstances) {
  47380. defines.push("#define INSTANCES");
  47381. attribs.push("world0");
  47382. attribs.push("world1");
  47383. attribs.push("world2");
  47384. attribs.push("world3");
  47385. }
  47386. // Get correct effect
  47387. var join = defines.join("\n");
  47388. if (this._cachedDefines !== join) {
  47389. this._cachedDefines = join;
  47390. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47391. }
  47392. return this._effect.isReady();
  47393. };
  47394. DepthRenderer.prototype.getDepthMap = function () {
  47395. return this._depthMap;
  47396. };
  47397. // Methods
  47398. DepthRenderer.prototype.dispose = function () {
  47399. this._depthMap.dispose();
  47400. };
  47401. return DepthRenderer;
  47402. })();
  47403. BABYLON.DepthRenderer = DepthRenderer;
  47404. })(BABYLON || (BABYLON = {}));
  47405. var BABYLON;
  47406. (function (BABYLON) {
  47407. var SSAORenderingPipeline = (function (_super) {
  47408. __extends(SSAORenderingPipeline, _super);
  47409. /**
  47410. * @constructor
  47411. * @param {string} name - The rendering pipeline name
  47412. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47413. * @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 }
  47414. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47415. */
  47416. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47417. var _this = this;
  47418. _super.call(this, scene.getEngine(), name);
  47419. // Members
  47420. /**
  47421. * The PassPostProcess id in the pipeline that contains the original scene color
  47422. * @type {string}
  47423. */
  47424. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47425. /**
  47426. * The SSAO PostProcess id in the pipeline
  47427. * @type {string}
  47428. */
  47429. this.SSAORenderEffect = "SSAORenderEffect";
  47430. /**
  47431. * The horizontal blur PostProcess id in the pipeline
  47432. * @type {string}
  47433. */
  47434. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47435. /**
  47436. * The vertical blur PostProcess id in the pipeline
  47437. * @type {string}
  47438. */
  47439. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47440. /**
  47441. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47442. * @type {string}
  47443. */
  47444. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47445. /**
  47446. * The output strength of the SSAO post-process. Default value is 1.0.
  47447. * @type {number}
  47448. */
  47449. this.totalStrength = 1.0;
  47450. /**
  47451. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47452. * @type {number}
  47453. */
  47454. this.radius = 0.0001;
  47455. /**
  47456. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47457. * Must not be equal to fallOff and superior to fallOff.
  47458. * Default value is 0.975
  47459. * @type {number}
  47460. */
  47461. this.area = 0.0075;
  47462. /**
  47463. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47464. * Must not be equal to area and inferior to area.
  47465. * Default value is 0.0
  47466. * @type {number}
  47467. */
  47468. this.fallOff = 0.000001;
  47469. /**
  47470. * The base color of the SSAO post-process
  47471. * The final result is "base + ssao" between [0, 1]
  47472. * @type {number}
  47473. */
  47474. this.base = 0.5;
  47475. this._firstUpdate = true;
  47476. this._scene = scene;
  47477. // Set up assets
  47478. this._createRandomTexture();
  47479. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47480. var ssaoRatio = ratio.ssaoRatio || ratio;
  47481. var combineRatio = ratio.combineRatio || ratio;
  47482. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47483. this._createSSAOPostProcess(ssaoRatio);
  47484. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47485. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47486. this._createSSAOCombinePostProcess(combineRatio);
  47487. // Set up pipeline
  47488. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47489. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47491. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47493. // Finish
  47494. scene.postProcessRenderPipelineManager.addPipeline(this);
  47495. if (cameras)
  47496. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47497. }
  47498. // Public Methods
  47499. /**
  47500. * Returns the horizontal blur PostProcess
  47501. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47502. */
  47503. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47504. return this._blurHPostProcess;
  47505. };
  47506. /**
  47507. * Returns the vertical blur PostProcess
  47508. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47509. */
  47510. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47511. return this._blurVPostProcess;
  47512. };
  47513. /**
  47514. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47515. */
  47516. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47517. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47518. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47519. this._originalColorPostProcess = undefined;
  47520. this._ssaoPostProcess = undefined;
  47521. this._blurHPostProcess = undefined;
  47522. this._blurVPostProcess = undefined;
  47523. this._ssaoCombinePostProcess = undefined;
  47524. this._randomTexture.dispose();
  47525. if (disableDepthRender)
  47526. this._scene.disableDepthRenderer();
  47527. };
  47528. // Private Methods
  47529. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47530. var _this = this;
  47531. var numSamples = 16;
  47532. var sampleSphere = [
  47533. 0.5381, 0.1856, -0.4319,
  47534. 0.1379, 0.2486, 0.4430,
  47535. 0.3371, 0.5679, -0.0057,
  47536. -0.6999, -0.0451, -0.0019,
  47537. 0.0689, -0.1598, -0.8547,
  47538. 0.0560, 0.0069, -0.1843,
  47539. -0.0146, 0.1402, 0.0762,
  47540. 0.0100, -0.1924, -0.0344,
  47541. -0.3577, -0.5301, -0.4358,
  47542. -0.3169, 0.1063, 0.0158,
  47543. 0.0103, -0.5869, 0.0046,
  47544. -0.0897, -0.4940, 0.3287,
  47545. 0.7119, -0.0154, -0.0918,
  47546. -0.0533, 0.0596, -0.5411,
  47547. 0.0352, -0.0631, 0.5460,
  47548. -0.4776, 0.2847, -0.0271
  47549. ];
  47550. var samplesFactor = 1.0 / numSamples;
  47551. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47552. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47553. "area", "fallOff", "base"
  47554. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  47555. this._ssaoPostProcess.onApply = function (effect) {
  47556. if (_this._firstUpdate) {
  47557. effect.setArray3("sampleSphere", sampleSphere);
  47558. effect.setFloat("samplesFactor", samplesFactor);
  47559. effect.setFloat("randTextureTiles", 4.0);
  47560. _this._firstUpdate = false;
  47561. }
  47562. effect.setFloat("totalStrength", _this.totalStrength);
  47563. effect.setFloat("radius", _this.radius);
  47564. effect.setFloat("area", _this.area);
  47565. effect.setFloat("fallOff", _this.fallOff);
  47566. effect.setFloat("base", _this.base);
  47567. effect.setTexture("textureSampler", _this._depthTexture);
  47568. effect.setTexture("randomSampler", _this._randomTexture);
  47569. };
  47570. };
  47571. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47572. var _this = this;
  47573. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47574. this._ssaoCombinePostProcess.onApply = function (effect) {
  47575. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47576. };
  47577. };
  47578. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47579. var size = 512;
  47580. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47581. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47582. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47583. var context = this._randomTexture.getContext();
  47584. var rand = function (min, max) {
  47585. return Math.random() * (max - min) + min;
  47586. };
  47587. var randVector = BABYLON.Vector3.Zero();
  47588. for (var x = 0; x < size; x++) {
  47589. for (var y = 0; y < size; y++) {
  47590. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47591. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47592. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47593. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47594. context.fillRect(x, y, 1, 1);
  47595. }
  47596. }
  47597. this._randomTexture.update(false);
  47598. };
  47599. return SSAORenderingPipeline;
  47600. })(BABYLON.PostProcessRenderPipeline);
  47601. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47602. })(BABYLON || (BABYLON = {}));
  47603. var BABYLON;
  47604. (function (BABYLON) {
  47605. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47606. var VolumetricLightScatteringPostProcess = (function (_super) {
  47607. __extends(VolumetricLightScatteringPostProcess, _super);
  47608. /**
  47609. * @constructor
  47610. * @param {string} name - The post-process name
  47611. * @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)
  47612. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47613. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47614. * @param {number} samples - The post-process quality, default 100
  47615. * @param {number} samplingMode - The post-process filtering mode
  47616. * @param {BABYLON.Engine} engine - The babylon engine
  47617. * @param {boolean} reusable - If the post-process is reusable
  47618. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47619. */
  47620. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47621. var _this = this;
  47622. if (samples === void 0) { samples = 100; }
  47623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47624. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  47625. this._screenCoordinates = BABYLON.Vector2.Zero();
  47626. /**
  47627. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47628. * @type {Vector3}
  47629. */
  47630. this.customMeshPosition = BABYLON.Vector3.Zero();
  47631. /**
  47632. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47633. * @type {boolean}
  47634. */
  47635. this.useCustomMeshPosition = false;
  47636. /**
  47637. * If the post-process should inverse the light scattering direction
  47638. * @type {boolean}
  47639. */
  47640. this.invert = true;
  47641. /**
  47642. * Array containing the excluded meshes not rendered in the internal pass
  47643. */
  47644. this.excludedMeshes = new Array();
  47645. /**
  47646. * Controls the overall intensity of the post-process
  47647. * @type {number}
  47648. */
  47649. this.exposure = 0.3;
  47650. /**
  47651. * Dissipates each sample's contribution in range [0, 1]
  47652. * @type {number}
  47653. */
  47654. this.decay = 0.96815;
  47655. /**
  47656. * Controls the overall intensity of each sample
  47657. * @type {number}
  47658. */
  47659. this.weight = 0.58767;
  47660. /**
  47661. * Controls the density of each sample
  47662. * @type {number}
  47663. */
  47664. this.density = 0.926;
  47665. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47666. var engine = scene.getEngine();
  47667. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47668. // Configure mesh
  47669. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47670. // Configure
  47671. this._createPass(scene, ratio.passRatio || ratio);
  47672. this.onActivate = function (camera) {
  47673. if (!_this.isSupported) {
  47674. _this.dispose(camera);
  47675. }
  47676. _this.onActivate = null;
  47677. };
  47678. this.onApplyObservable.add(function (effect) {
  47679. _this._updateMeshScreenCoordinates(scene);
  47680. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47681. effect.setFloat("exposure", _this.exposure);
  47682. effect.setFloat("decay", _this.decay);
  47683. effect.setFloat("weight", _this.weight);
  47684. effect.setFloat("density", _this.density);
  47685. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47686. });
  47687. }
  47688. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47689. get: function () {
  47690. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47691. return false;
  47692. },
  47693. set: function (useDiffuseColor) {
  47694. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47695. },
  47696. enumerable: true,
  47697. configurable: true
  47698. });
  47699. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47700. var mesh = subMesh.getMesh();
  47701. // Render this.mesh as default
  47702. if (mesh === this.mesh) {
  47703. return mesh.material.isReady(mesh);
  47704. }
  47705. var defines = [];
  47706. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47707. var material = subMesh.getMaterial();
  47708. var needUV = false;
  47709. // Alpha test
  47710. if (material) {
  47711. if (material.needAlphaTesting()) {
  47712. defines.push("#define ALPHATEST");
  47713. }
  47714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47715. attribs.push(BABYLON.VertexBuffer.UVKind);
  47716. defines.push("#define UV1");
  47717. }
  47718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47719. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47720. defines.push("#define UV2");
  47721. }
  47722. }
  47723. // Bones
  47724. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47727. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47728. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47729. }
  47730. else {
  47731. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47732. }
  47733. // Instances
  47734. if (useInstances) {
  47735. defines.push("#define INSTANCES");
  47736. attribs.push("world0");
  47737. attribs.push("world1");
  47738. attribs.push("world2");
  47739. attribs.push("world3");
  47740. }
  47741. // Get correct effect
  47742. var join = defines.join("\n");
  47743. if (this._cachedDefines !== join) {
  47744. this._cachedDefines = join;
  47745. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47746. }
  47747. return this._volumetricLightScatteringPass.isReady();
  47748. };
  47749. /**
  47750. * Sets the new light position for light scattering effect
  47751. * @param {BABYLON.Vector3} The new custom light position
  47752. */
  47753. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47754. this.customMeshPosition = position;
  47755. };
  47756. /**
  47757. * Returns the light position for light scattering effect
  47758. * @return {BABYLON.Vector3} The custom light position
  47759. */
  47760. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47761. return this.customMeshPosition;
  47762. };
  47763. /**
  47764. * Disposes the internal assets and detaches the post-process from the camera
  47765. */
  47766. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47767. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47768. if (rttIndex !== -1) {
  47769. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47770. }
  47771. this._volumetricLightScatteringRTT.dispose();
  47772. _super.prototype.dispose.call(this, camera);
  47773. };
  47774. /**
  47775. * Returns the render target texture used by the post-process
  47776. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47777. */
  47778. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47779. return this._volumetricLightScatteringRTT;
  47780. };
  47781. // Private methods
  47782. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47783. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47784. return true;
  47785. }
  47786. return false;
  47787. };
  47788. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47789. var _this = this;
  47790. var engine = scene.getEngine();
  47791. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47792. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47793. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47794. this._volumetricLightScatteringRTT.renderList = null;
  47795. this._volumetricLightScatteringRTT.renderParticles = false;
  47796. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47797. // Custom render function for submeshes
  47798. var renderSubMesh = function (subMesh) {
  47799. var mesh = subMesh.getRenderingMesh();
  47800. if (_this._meshExcluded(mesh)) {
  47801. return;
  47802. }
  47803. var scene = mesh.getScene();
  47804. var engine = scene.getEngine();
  47805. // Culling
  47806. engine.setState(subMesh.getMaterial().backFaceCulling);
  47807. // Managing instances
  47808. var batch = mesh._getInstancesRenderList(subMesh._id);
  47809. if (batch.mustReturn) {
  47810. return;
  47811. }
  47812. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47813. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47814. var effect = _this._volumetricLightScatteringPass;
  47815. if (mesh === _this.mesh) {
  47816. effect = subMesh.getMaterial().getEffect();
  47817. }
  47818. engine.enableEffect(effect);
  47819. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47820. if (mesh === _this.mesh) {
  47821. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47822. }
  47823. else {
  47824. var material = subMesh.getMaterial();
  47825. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47826. // Alpha test
  47827. if (material && material.needAlphaTesting()) {
  47828. var alphaTexture = material.getAlphaTestTexture();
  47829. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47830. if (alphaTexture) {
  47831. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47832. }
  47833. }
  47834. // Bones
  47835. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47836. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47837. }
  47838. }
  47839. // Draw
  47840. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47841. }
  47842. };
  47843. // Render target texture callbacks
  47844. var savedSceneClearColor;
  47845. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47846. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47847. savedSceneClearColor = scene.clearColor;
  47848. scene.clearColor = sceneClearColor;
  47849. });
  47850. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47851. scene.clearColor = savedSceneClearColor;
  47852. });
  47853. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47854. var engine = scene.getEngine();
  47855. var index;
  47856. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47857. renderSubMesh(opaqueSubMeshes.data[index]);
  47858. }
  47859. engine.setAlphaTesting(true);
  47860. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47861. renderSubMesh(alphaTestSubMeshes.data[index]);
  47862. }
  47863. engine.setAlphaTesting(false);
  47864. if (transparentSubMeshes.length) {
  47865. // Sort sub meshes
  47866. for (index = 0; index < transparentSubMeshes.length; index++) {
  47867. var submesh = transparentSubMeshes.data[index];
  47868. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47869. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47870. }
  47871. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47872. sortedArray.sort(function (a, b) {
  47873. // Alpha index first
  47874. if (a._alphaIndex > b._alphaIndex) {
  47875. return 1;
  47876. }
  47877. if (a._alphaIndex < b._alphaIndex) {
  47878. return -1;
  47879. }
  47880. // Then distance to camera
  47881. if (a._distanceToCamera < b._distanceToCamera) {
  47882. return 1;
  47883. }
  47884. if (a._distanceToCamera > b._distanceToCamera) {
  47885. return -1;
  47886. }
  47887. return 0;
  47888. });
  47889. // Render sub meshes
  47890. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47891. for (index = 0; index < sortedArray.length; index++) {
  47892. renderSubMesh(sortedArray[index]);
  47893. }
  47894. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47895. }
  47896. };
  47897. };
  47898. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47899. var transform = scene.getTransformMatrix();
  47900. var meshPosition;
  47901. if (this.useCustomMeshPosition) {
  47902. meshPosition = this.customMeshPosition;
  47903. }
  47904. else if (this.attachedNode) {
  47905. meshPosition = this.attachedNode.position;
  47906. }
  47907. else {
  47908. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47909. }
  47910. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47911. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47912. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47913. if (this.invert)
  47914. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47915. };
  47916. // Static methods
  47917. /**
  47918. * Creates a default mesh for the Volumeric Light Scattering post-process
  47919. * @param {string} The mesh name
  47920. * @param {BABYLON.Scene} The scene where to create the mesh
  47921. * @return {BABYLON.Mesh} the default mesh
  47922. */
  47923. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47924. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47925. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47926. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47927. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47928. mesh.material = material;
  47929. return mesh;
  47930. };
  47931. __decorate([
  47932. BABYLON.serializeAsVector3()
  47933. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47934. __decorate([
  47935. BABYLON.serialize()
  47936. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47937. __decorate([
  47938. BABYLON.serialize()
  47939. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47940. __decorate([
  47941. BABYLON.serializeAsMeshReference()
  47942. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47943. __decorate([
  47944. BABYLON.serialize()
  47945. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47946. __decorate([
  47947. BABYLON.serialize()
  47948. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47949. __decorate([
  47950. BABYLON.serialize()
  47951. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47952. __decorate([
  47953. BABYLON.serialize()
  47954. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47955. __decorate([
  47956. BABYLON.serialize()
  47957. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47958. return VolumetricLightScatteringPostProcess;
  47959. })(BABYLON.PostProcess);
  47960. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47961. })(BABYLON || (BABYLON = {}));
  47962. // BABYLON.JS Chromatic Aberration GLSL Shader
  47963. // Author: Olivier Guyot
  47964. // Separates very slightly R, G and B colors on the edges of the screen
  47965. // Inspired by Francois Tarlier & Martins Upitis
  47966. var BABYLON;
  47967. (function (BABYLON) {
  47968. var LensRenderingPipeline = (function (_super) {
  47969. __extends(LensRenderingPipeline, _super);
  47970. /**
  47971. * @constructor
  47972. *
  47973. * Effect parameters are as follow:
  47974. * {
  47975. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47976. * edge_blur: number; // from 0 to x (1 for realism)
  47977. * distortion: number; // from 0 to x (1 for realism)
  47978. * grain_amount: number; // from 0 to 1
  47979. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47980. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47981. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47982. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47983. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47984. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47985. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47986. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47987. * }
  47988. * Note: if an effect parameter is unset, effect is disabled
  47989. *
  47990. * @param {string} name - The rendering pipeline name
  47991. * @param {object} parameters - An object containing all parameters (see above)
  47992. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47993. * @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)
  47994. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47995. */
  47996. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47997. var _this = this;
  47998. if (ratio === void 0) { ratio = 1.0; }
  47999. _super.call(this, scene.getEngine(), name);
  48000. // Lens effects can be of the following:
  48001. // - chromatic aberration (slight shift of RGB colors)
  48002. // - blur on the edge of the lens
  48003. // - lens distortion
  48004. // - depth-of-field blur & highlights enhancing
  48005. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  48006. // - grain effect (noise or custom texture)
  48007. // Two additional texture samplers are needed:
  48008. // - depth map (for depth-of-field)
  48009. // - grain texture
  48010. /**
  48011. * The chromatic aberration PostProcess id in the pipeline
  48012. * @type {string}
  48013. */
  48014. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  48015. /**
  48016. * The highlights enhancing PostProcess id in the pipeline
  48017. * @type {string}
  48018. */
  48019. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  48020. /**
  48021. * The depth-of-field PostProcess id in the pipeline
  48022. * @type {string}
  48023. */
  48024. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  48025. this._scene = scene;
  48026. // Fetch texture samplers
  48027. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48028. if (parameters.grain_texture) {
  48029. this._grainTexture = parameters.grain_texture;
  48030. }
  48031. else {
  48032. this._createGrainTexture();
  48033. }
  48034. // save parameters
  48035. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  48036. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  48037. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  48038. this._distortion = parameters.distortion ? parameters.distortion : 0;
  48039. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  48040. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  48041. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  48042. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  48043. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  48044. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  48045. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  48046. // Create effects
  48047. this._createChromaticAberrationPostProcess(ratio);
  48048. this._createHighlightsPostProcess(ratio);
  48049. this._createDepthOfFieldPostProcess(ratio / 4);
  48050. // Set up pipeline
  48051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  48052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  48053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  48054. if (this._highlightsGain === -1) {
  48055. this._disableEffect(this.HighlightsEnhancingEffect, null);
  48056. }
  48057. // Finish
  48058. scene.postProcessRenderPipelineManager.addPipeline(this);
  48059. if (cameras) {
  48060. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48061. }
  48062. }
  48063. // public methods (self explanatory)
  48064. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  48065. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  48066. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  48067. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  48068. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  48069. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  48070. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  48071. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  48072. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  48073. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  48074. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  48075. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  48076. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  48077. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  48078. };
  48079. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  48080. this._highlightsPostProcess.updateEffect();
  48081. };
  48082. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  48083. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  48084. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  48085. this._highlightsGain = amount;
  48086. };
  48087. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  48088. if (this._highlightsGain === -1) {
  48089. this._highlightsGain = 1.0;
  48090. }
  48091. this._highlightsThreshold = amount;
  48092. };
  48093. LensRenderingPipeline.prototype.disableHighlights = function () {
  48094. this._highlightsGain = -1;
  48095. };
  48096. /**
  48097. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  48098. */
  48099. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48100. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48101. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48102. this._chromaticAberrationPostProcess = undefined;
  48103. this._highlightsPostProcess = undefined;
  48104. this._depthOfFieldPostProcess = undefined;
  48105. this._grainTexture.dispose();
  48106. if (disableDepthRender)
  48107. this._scene.disableDepthRenderer();
  48108. };
  48109. // colors shifting and distortion
  48110. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  48111. var _this = this;
  48112. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  48113. [], // samplers
  48114. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48115. this._chromaticAberrationPostProcess.onApply = function (effect) {
  48116. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  48117. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48118. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48119. };
  48120. };
  48121. // highlights enhancing
  48122. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  48123. var _this = this;
  48124. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  48125. [], // samplers
  48126. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  48127. this._highlightsPostProcess.onApply = function (effect) {
  48128. effect.setFloat('gain', _this._highlightsGain);
  48129. effect.setFloat('threshold', _this._highlightsThreshold);
  48130. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  48131. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48132. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48133. };
  48134. };
  48135. // colors shifting and distortion
  48136. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  48137. var _this = this;
  48138. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  48139. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  48140. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  48141. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48142. this._depthOfFieldPostProcess.onApply = function (effect) {
  48143. effect.setTexture("depthSampler", _this._depthTexture);
  48144. effect.setTexture("grainSampler", _this._grainTexture);
  48145. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  48146. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  48147. effect.setFloat('grain_amount', _this._grainAmount);
  48148. effect.setBool('blur_noise', _this._blurNoise);
  48149. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48150. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48151. effect.setFloat('distortion', _this._distortion);
  48152. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48153. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48154. effect.setFloat('aperture', _this._dofAperture);
  48155. effect.setFloat('darken', _this._dofDarken);
  48156. effect.setFloat('edge_blur', _this._edgeBlur);
  48157. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48158. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48159. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48160. };
  48161. };
  48162. // creates a black and white random noise texture, 512x512
  48163. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48164. var size = 512;
  48165. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48166. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48167. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48168. var context = this._grainTexture.getContext();
  48169. var rand = function (min, max) {
  48170. return Math.random() * (max - min) + min;
  48171. };
  48172. var value;
  48173. for (var x = 0; x < size; x++) {
  48174. for (var y = 0; y < size; y++) {
  48175. value = Math.floor(rand(0.42, 0.58) * 255);
  48176. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48177. context.fillRect(x, y, 1, 1);
  48178. }
  48179. }
  48180. this._grainTexture.update(false);
  48181. };
  48182. return LensRenderingPipeline;
  48183. })(BABYLON.PostProcessRenderPipeline);
  48184. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48185. })(BABYLON || (BABYLON = {}));
  48186. //
  48187. // This post-process allows the modification of rendered colors by using
  48188. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48189. //
  48190. // The object needs to be provided an url to a texture containing the color
  48191. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48192. // Use an image editing software to tweak the LUT to match your needs.
  48193. //
  48194. // For an example of a color LUT, see here:
  48195. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48196. // For explanations on color grading, see here:
  48197. // http://udn.epicgames.com/Three/ColorGrading.html
  48198. //
  48199. var BABYLON;
  48200. (function (BABYLON) {
  48201. var ColorCorrectionPostProcess = (function (_super) {
  48202. __extends(ColorCorrectionPostProcess, _super);
  48203. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48204. var _this = this;
  48205. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  48206. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48207. this._colorTableTexture.anisotropicFilteringLevel = 1;
  48208. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48209. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48210. this.onApply = function (effect) {
  48211. effect.setTexture("colorTable", _this._colorTableTexture);
  48212. };
  48213. }
  48214. return ColorCorrectionPostProcess;
  48215. })(BABYLON.PostProcess);
  48216. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48217. })(BABYLON || (BABYLON = {}));
  48218. var BABYLON;
  48219. (function (BABYLON) {
  48220. var AnaglyphFreeCamera = (function (_super) {
  48221. __extends(AnaglyphFreeCamera, _super);
  48222. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48223. _super.call(this, name, position, scene);
  48224. this.interaxialDistance = interaxialDistance;
  48225. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48226. }
  48227. AnaglyphFreeCamera.prototype.getTypeName = function () {
  48228. return "AnaglyphFreeCamera";
  48229. };
  48230. return AnaglyphFreeCamera;
  48231. })(BABYLON.FreeCamera);
  48232. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48233. var AnaglyphArcRotateCamera = (function (_super) {
  48234. __extends(AnaglyphArcRotateCamera, _super);
  48235. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48236. _super.call(this, name, alpha, beta, radius, target, scene);
  48237. this.interaxialDistance = interaxialDistance;
  48238. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48239. }
  48240. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  48241. return "AnaglyphArcRotateCamera";
  48242. };
  48243. return AnaglyphArcRotateCamera;
  48244. })(BABYLON.ArcRotateCamera);
  48245. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48246. var AnaglyphGamepadCamera = (function (_super) {
  48247. __extends(AnaglyphGamepadCamera, _super);
  48248. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48249. _super.call(this, name, position, scene);
  48250. this.interaxialDistance = interaxialDistance;
  48251. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48252. }
  48253. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  48254. return "AnaglyphGamepadCamera";
  48255. };
  48256. return AnaglyphGamepadCamera;
  48257. })(BABYLON.GamepadCamera);
  48258. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48259. var AnaglyphUniversalCamera = (function (_super) {
  48260. __extends(AnaglyphUniversalCamera, _super);
  48261. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48262. _super.call(this, name, position, scene);
  48263. this.interaxialDistance = interaxialDistance;
  48264. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48265. }
  48266. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  48267. return "AnaglyphUniversalCamera";
  48268. };
  48269. return AnaglyphUniversalCamera;
  48270. })(BABYLON.UniversalCamera);
  48271. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48272. var StereoscopicFreeCamera = (function (_super) {
  48273. __extends(StereoscopicFreeCamera, _super);
  48274. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48275. _super.call(this, name, position, scene);
  48276. this.interaxialDistance = interaxialDistance;
  48277. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48278. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48279. }
  48280. StereoscopicFreeCamera.prototype.getTypeName = function () {
  48281. return "StereoscopicFreeCamera";
  48282. };
  48283. return StereoscopicFreeCamera;
  48284. })(BABYLON.FreeCamera);
  48285. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48286. var StereoscopicArcRotateCamera = (function (_super) {
  48287. __extends(StereoscopicArcRotateCamera, _super);
  48288. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48289. _super.call(this, name, alpha, beta, radius, target, scene);
  48290. this.interaxialDistance = interaxialDistance;
  48291. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48292. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48293. }
  48294. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  48295. return "StereoscopicArcRotateCamera";
  48296. };
  48297. return StereoscopicArcRotateCamera;
  48298. })(BABYLON.ArcRotateCamera);
  48299. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48300. var StereoscopicGamepadCamera = (function (_super) {
  48301. __extends(StereoscopicGamepadCamera, _super);
  48302. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48303. _super.call(this, name, position, scene);
  48304. this.interaxialDistance = interaxialDistance;
  48305. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48306. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48307. }
  48308. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  48309. return "StereoscopicGamepadCamera";
  48310. };
  48311. return StereoscopicGamepadCamera;
  48312. })(BABYLON.GamepadCamera);
  48313. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48314. var StereoscopicUniversalCamera = (function (_super) {
  48315. __extends(StereoscopicUniversalCamera, _super);
  48316. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48317. _super.call(this, name, position, scene);
  48318. this.interaxialDistance = interaxialDistance;
  48319. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48320. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48321. }
  48322. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  48323. return "StereoscopicUniversalCamera";
  48324. };
  48325. return StereoscopicUniversalCamera;
  48326. })(BABYLON.UniversalCamera);
  48327. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48328. })(BABYLON || (BABYLON = {}));
  48329. var BABYLON;
  48330. (function (BABYLON) {
  48331. var HDRRenderingPipeline = (function (_super) {
  48332. __extends(HDRRenderingPipeline, _super);
  48333. /**
  48334. * @constructor
  48335. * @param {string} name - The rendering pipeline name
  48336. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48337. * @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)
  48338. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48339. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48340. */
  48341. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48342. var _this = this;
  48343. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48344. _super.call(this, scene.getEngine(), name);
  48345. /**
  48346. * Public members
  48347. */
  48348. // Gaussian Blur
  48349. /**
  48350. * Gaussian blur coefficient
  48351. * @type {number}
  48352. */
  48353. this.gaussCoeff = 0.3;
  48354. /**
  48355. * Gaussian blur mean
  48356. * @type {number}
  48357. */
  48358. this.gaussMean = 1.0;
  48359. /**
  48360. * Gaussian blur standard deviation
  48361. * @type {number}
  48362. */
  48363. this.gaussStandDev = 0.8;
  48364. /**
  48365. * Gaussian blur multiplier. Multiplies the blur effect
  48366. * @type {number}
  48367. */
  48368. this.gaussMultiplier = 4.0;
  48369. // HDR
  48370. /**
  48371. * Exposure, controls the overall intensity of the pipeline
  48372. * @type {number}
  48373. */
  48374. this.exposure = 1.0;
  48375. /**
  48376. * Minimum luminance that the post-process can output. Luminance is >= 0
  48377. * @type {number}
  48378. */
  48379. this.minimumLuminance = 1.0;
  48380. /**
  48381. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48382. * @type {number}
  48383. */
  48384. this.maximumLuminance = 1e20;
  48385. /**
  48386. * Increase rate for luminance: eye adaptation speed to dark
  48387. * @type {number}
  48388. */
  48389. this.luminanceIncreaserate = 0.5;
  48390. /**
  48391. * Decrease rate for luminance: eye adaptation speed to bright
  48392. * @type {number}
  48393. */
  48394. this.luminanceDecreaseRate = 0.5;
  48395. // Bright pass
  48396. /**
  48397. * Minimum luminance needed to compute HDR
  48398. * @type {number}
  48399. */
  48400. this.brightThreshold = 0.8;
  48401. this._needUpdate = true;
  48402. this._scene = scene;
  48403. // Bright pass
  48404. this._createBrightPassPostProcess(scene, ratio);
  48405. // Down sample X4
  48406. this._createDownSampleX4PostProcess(scene, ratio);
  48407. // Create gaussian blur post-processes
  48408. this._createGaussianBlurPostProcess(scene, ratio);
  48409. // Texture adder
  48410. this._createTextureAdderPostProcess(scene, ratio);
  48411. // Luminance generator
  48412. this._createLuminanceGeneratorPostProcess(scene);
  48413. // HDR
  48414. this._createHDRPostProcess(scene, ratio);
  48415. // Pass postprocess
  48416. if (originalPostProcess === null) {
  48417. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48418. }
  48419. else {
  48420. this._originalPostProcess = originalPostProcess;
  48421. }
  48422. // Configure pipeline
  48423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48425. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48426. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48427. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48429. var addDownSamplerPostProcess = function (id) {
  48430. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48431. };
  48432. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48433. addDownSamplerPostProcess(i);
  48434. }
  48435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48436. // Finish
  48437. scene.postProcessRenderPipelineManager.addPipeline(this);
  48438. if (cameras !== null) {
  48439. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48440. }
  48441. this.update();
  48442. }
  48443. /**
  48444. * Tells the pipeline to update its post-processes
  48445. */
  48446. HDRRenderingPipeline.prototype.update = function () {
  48447. this._needUpdate = true;
  48448. };
  48449. /**
  48450. * Returns the current calculated luminance
  48451. */
  48452. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48453. return this._hdrCurrentLuminance;
  48454. };
  48455. /**
  48456. * Returns the currently drawn luminance
  48457. */
  48458. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48459. return this._hdrOutputLuminance;
  48460. };
  48461. /**
  48462. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48463. */
  48464. HDRRenderingPipeline.prototype.dispose = function () {
  48465. this._originalPostProcess = undefined;
  48466. this._brightPassPostProcess = undefined;
  48467. this._downSampleX4PostProcess = undefined;
  48468. this._guassianBlurHPostProcess = undefined;
  48469. this._guassianBlurVPostProcess = undefined;
  48470. this._textureAdderPostProcess = undefined;
  48471. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48472. this._downSamplePostProcesses[i] = undefined;
  48473. }
  48474. this._hdrPostProcess = undefined;
  48475. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48476. };
  48477. /**
  48478. * Creates the HDR post-process and computes the luminance adaptation
  48479. */
  48480. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48481. var _this = this;
  48482. var hdrLastLuminance = 0.0;
  48483. this._hdrOutputLuminance = -1.0;
  48484. this._hdrCurrentLuminance = 1.0;
  48485. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48486. this._hdrPostProcess.onApply = function (effect) {
  48487. if (_this._hdrOutputLuminance < 0.0) {
  48488. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48489. }
  48490. else {
  48491. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48492. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48493. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48494. }
  48495. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48496. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48497. }
  48498. else {
  48499. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48500. }
  48501. }
  48502. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48503. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48504. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48505. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48506. effect.setFloat("exposure", _this.exposure);
  48507. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48508. _this._needUpdate = false;
  48509. };
  48510. };
  48511. /**
  48512. * Texture Adder post-process
  48513. */
  48514. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48515. var _this = this;
  48516. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  48517. this._textureAdderPostProcess.onApply = function (effect) {
  48518. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48519. };
  48520. };
  48521. /**
  48522. * Down sample X4 post-process
  48523. */
  48524. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48525. var _this = this;
  48526. var downSampleX4Offsets = new Array(32);
  48527. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  48528. this._downSampleX4PostProcess.onApply = function (effect) {
  48529. if (_this._needUpdate) {
  48530. var id = 0;
  48531. for (var i = -2; i < 2; i++) {
  48532. for (var j = -2; j < 2; j++) {
  48533. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  48534. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  48535. id += 2;
  48536. }
  48537. }
  48538. }
  48539. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48540. };
  48541. };
  48542. /**
  48543. * Bright pass post-process
  48544. */
  48545. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48546. var _this = this;
  48547. var brightOffsets = new Array(8);
  48548. var brightPassCallback = function (effect) {
  48549. if (_this._needUpdate) {
  48550. var sU = (1.0 / _this._brightPassPostProcess.width);
  48551. var sV = (1.0 / _this._brightPassPostProcess.height);
  48552. brightOffsets[0] = -0.5 * sU;
  48553. brightOffsets[1] = 0.5 * sV;
  48554. brightOffsets[2] = 0.5 * sU;
  48555. brightOffsets[3] = 0.5 * sV;
  48556. brightOffsets[4] = -0.5 * sU;
  48557. brightOffsets[5] = -0.5 * sV;
  48558. brightOffsets[6] = 0.5 * sU;
  48559. brightOffsets[7] = -0.5 * sV;
  48560. }
  48561. effect.setArray2("dsOffsets", brightOffsets);
  48562. effect.setFloat("brightThreshold", _this.brightThreshold);
  48563. };
  48564. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  48565. this._brightPassPostProcess.onApply = brightPassCallback;
  48566. };
  48567. /**
  48568. * Luminance generator. Creates the luminance post-process and down sample post-processes
  48569. */
  48570. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  48571. var _this = this;
  48572. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  48573. var luminanceOffsets = new Array(8);
  48574. var downSampleOffsets = new Array(18);
  48575. var halfDestPixelSize;
  48576. this._downSamplePostProcesses = new Array(lumSteps);
  48577. // Utils for luminance
  48578. var luminanceUpdateSourceOffsets = function (width, height) {
  48579. var sU = (1.0 / width);
  48580. var sV = (1.0 / height);
  48581. luminanceOffsets[0] = -0.5 * sU;
  48582. luminanceOffsets[1] = 0.5 * sV;
  48583. luminanceOffsets[2] = 0.5 * sU;
  48584. luminanceOffsets[3] = 0.5 * sV;
  48585. luminanceOffsets[4] = -0.5 * sU;
  48586. luminanceOffsets[5] = -0.5 * sV;
  48587. luminanceOffsets[6] = 0.5 * sU;
  48588. luminanceOffsets[7] = -0.5 * sV;
  48589. };
  48590. var luminanceUpdateDestOffsets = function (width, height) {
  48591. var id = 0;
  48592. for (var x = -1; x < 2; x++) {
  48593. for (var y = -1; y < 2; y++) {
  48594. downSampleOffsets[id] = (x) / width;
  48595. downSampleOffsets[id + 1] = (y) / height;
  48596. id += 2;
  48597. }
  48598. }
  48599. };
  48600. // Luminance callback
  48601. var luminanceCallback = function (effect) {
  48602. if (_this._needUpdate) {
  48603. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  48604. }
  48605. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48606. effect.setArray2("lumOffsets", luminanceOffsets);
  48607. };
  48608. // Down sample callbacks
  48609. var downSampleCallback = function (indice) {
  48610. var i = indice;
  48611. return function (effect) {
  48612. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48613. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48614. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  48615. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  48616. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  48617. effect.setArray2("dsOffsets", downSampleOffsets);
  48618. };
  48619. };
  48620. var downSampleAfterRenderCallback = function (effect) {
  48621. // Unpack result
  48622. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48623. 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);
  48624. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48625. };
  48626. // Create luminance post-process
  48627. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  48628. 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);
  48629. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  48630. // Create down sample post-processes
  48631. for (var i = lumSteps - 2; i >= 0; i--) {
  48632. var length = Math.pow(3, i);
  48633. ratio = { width: length, height: length };
  48634. var defines = "#define DOWN_SAMPLE\n";
  48635. if (i === 0) {
  48636. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  48637. }
  48638. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48639. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  48640. if (i === 0) {
  48641. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  48642. }
  48643. }
  48644. };
  48645. /**
  48646. * Gaussian blur post-processes. Horizontal and Vertical
  48647. */
  48648. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  48649. var _this = this;
  48650. var blurOffsetsW = new Array(9);
  48651. var blurOffsetsH = new Array(9);
  48652. var blurWeights = new Array(9);
  48653. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  48654. // Utils for gaussian blur
  48655. var calculateBlurOffsets = function (height) {
  48656. var lastOutputDimensions = {
  48657. width: scene.getEngine().getRenderWidth(),
  48658. height: scene.getEngine().getRenderHeight()
  48659. };
  48660. for (var i = 0; i < 9; i++) {
  48661. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48662. if (height) {
  48663. blurOffsetsH[i] = value;
  48664. }
  48665. else {
  48666. blurOffsetsW[i] = value;
  48667. }
  48668. }
  48669. };
  48670. var calculateWeights = function () {
  48671. var x = 0.0;
  48672. for (var i = 0; i < 9; i++) {
  48673. x = (i - 4.0) / 4.0;
  48674. 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));
  48675. }
  48676. };
  48677. // Callback
  48678. var gaussianBlurCallback = function (height) {
  48679. return function (effect) {
  48680. if (_this._needUpdate) {
  48681. calculateWeights();
  48682. calculateBlurOffsets(height);
  48683. }
  48684. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  48685. effect.setArray("blurWeights", blurWeights);
  48686. effect.setFloat("multiplier", _this.gaussMultiplier);
  48687. };
  48688. };
  48689. // Create horizontal gaussian blur post-processes
  48690. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  48691. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  48692. // Create vertical gaussian blur post-process
  48693. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  48694. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  48695. };
  48696. // Luminance generator
  48697. HDRRenderingPipeline.LUM_STEPS = 6;
  48698. return HDRRenderingPipeline;
  48699. })(BABYLON.PostProcessRenderPipeline);
  48700. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  48701. })(BABYLON || (BABYLON = {}));
  48702. var BABYLON;
  48703. (function (BABYLON) {
  48704. var FaceAdjacencies = (function () {
  48705. function FaceAdjacencies() {
  48706. this.edges = new Array();
  48707. this.edgesConnectedCount = 0;
  48708. }
  48709. return FaceAdjacencies;
  48710. })();
  48711. var EdgesRenderer = (function () {
  48712. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48713. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48714. if (epsilon === void 0) { epsilon = 0.95; }
  48715. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48716. this.edgesWidthScalerForOrthographic = 1000.0;
  48717. this.edgesWidthScalerForPerspective = 50.0;
  48718. this._linesPositions = new Array();
  48719. this._linesNormals = new Array();
  48720. this._linesIndices = new Array();
  48721. this._buffers = new Array();
  48722. this._checkVerticesInsteadOfIndices = false;
  48723. this._source = source;
  48724. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48725. this._epsilon = epsilon;
  48726. this._prepareRessources();
  48727. this._generateEdgesLines();
  48728. }
  48729. EdgesRenderer.prototype._prepareRessources = function () {
  48730. if (this._lineShader) {
  48731. return;
  48732. }
  48733. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48734. attributes: ["position", "normal"],
  48735. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48736. });
  48737. this._lineShader.disableDepthWrite = true;
  48738. this._lineShader.backFaceCulling = false;
  48739. };
  48740. EdgesRenderer.prototype.dispose = function () {
  48741. this._vb0.dispose();
  48742. this._vb1.dispose();
  48743. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48744. this._lineShader.dispose();
  48745. };
  48746. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48747. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48748. return 0;
  48749. }
  48750. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48751. return 1;
  48752. }
  48753. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48754. return 2;
  48755. }
  48756. return -1;
  48757. };
  48758. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48759. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48760. return 0;
  48761. }
  48762. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48763. return 1;
  48764. }
  48765. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48766. return 2;
  48767. }
  48768. return -1;
  48769. };
  48770. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48771. var needToCreateLine;
  48772. if (edge === undefined) {
  48773. needToCreateLine = true;
  48774. }
  48775. else {
  48776. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48777. needToCreateLine = dotProduct < this._epsilon;
  48778. }
  48779. if (needToCreateLine) {
  48780. var offset = this._linesPositions.length / 3;
  48781. var normal = p0.subtract(p1);
  48782. normal.normalize();
  48783. // Positions
  48784. this._linesPositions.push(p0.x);
  48785. this._linesPositions.push(p0.y);
  48786. this._linesPositions.push(p0.z);
  48787. this._linesPositions.push(p0.x);
  48788. this._linesPositions.push(p0.y);
  48789. this._linesPositions.push(p0.z);
  48790. this._linesPositions.push(p1.x);
  48791. this._linesPositions.push(p1.y);
  48792. this._linesPositions.push(p1.z);
  48793. this._linesPositions.push(p1.x);
  48794. this._linesPositions.push(p1.y);
  48795. this._linesPositions.push(p1.z);
  48796. // Normals
  48797. this._linesNormals.push(p1.x);
  48798. this._linesNormals.push(p1.y);
  48799. this._linesNormals.push(p1.z);
  48800. this._linesNormals.push(-1);
  48801. this._linesNormals.push(p1.x);
  48802. this._linesNormals.push(p1.y);
  48803. this._linesNormals.push(p1.z);
  48804. this._linesNormals.push(1);
  48805. this._linesNormals.push(p0.x);
  48806. this._linesNormals.push(p0.y);
  48807. this._linesNormals.push(p0.z);
  48808. this._linesNormals.push(-1);
  48809. this._linesNormals.push(p0.x);
  48810. this._linesNormals.push(p0.y);
  48811. this._linesNormals.push(p0.z);
  48812. this._linesNormals.push(1);
  48813. // Indices
  48814. this._linesIndices.push(offset);
  48815. this._linesIndices.push(offset + 1);
  48816. this._linesIndices.push(offset + 2);
  48817. this._linesIndices.push(offset);
  48818. this._linesIndices.push(offset + 2);
  48819. this._linesIndices.push(offset + 3);
  48820. }
  48821. };
  48822. EdgesRenderer.prototype._generateEdgesLines = function () {
  48823. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48824. var indices = this._source.getIndices();
  48825. // First let's find adjacencies
  48826. var adjacencies = new Array();
  48827. var faceNormals = new Array();
  48828. var index;
  48829. var faceAdjacencies;
  48830. // Prepare faces
  48831. for (index = 0; index < indices.length; index += 3) {
  48832. faceAdjacencies = new FaceAdjacencies();
  48833. var p0Index = indices[index];
  48834. var p1Index = indices[index + 1];
  48835. var p2Index = indices[index + 2];
  48836. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  48837. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  48838. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  48839. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  48840. faceNormal.normalize();
  48841. faceNormals.push(faceNormal);
  48842. adjacencies.push(faceAdjacencies);
  48843. }
  48844. // Scan
  48845. for (index = 0; index < adjacencies.length; index++) {
  48846. faceAdjacencies = adjacencies[index];
  48847. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  48848. var otherFaceAdjacencies = adjacencies[otherIndex];
  48849. if (faceAdjacencies.edgesConnectedCount === 3) {
  48850. break;
  48851. }
  48852. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  48853. continue;
  48854. }
  48855. var otherP0 = indices[otherIndex * 3];
  48856. var otherP1 = indices[otherIndex * 3 + 1];
  48857. var otherP2 = indices[otherIndex * 3 + 2];
  48858. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  48859. var otherEdgeIndex;
  48860. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  48861. continue;
  48862. }
  48863. switch (edgeIndex) {
  48864. case 0:
  48865. if (this._checkVerticesInsteadOfIndices) {
  48866. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48867. }
  48868. else {
  48869. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  48870. }
  48871. break;
  48872. case 1:
  48873. if (this._checkVerticesInsteadOfIndices) {
  48874. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48875. }
  48876. else {
  48877. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  48878. }
  48879. break;
  48880. case 2:
  48881. if (this._checkVerticesInsteadOfIndices) {
  48882. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48883. }
  48884. else {
  48885. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  48886. }
  48887. break;
  48888. }
  48889. if (otherEdgeIndex === -1) {
  48890. continue;
  48891. }
  48892. faceAdjacencies.edges[edgeIndex] = otherIndex;
  48893. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  48894. faceAdjacencies.edgesConnectedCount++;
  48895. otherFaceAdjacencies.edgesConnectedCount++;
  48896. if (faceAdjacencies.edgesConnectedCount === 3) {
  48897. break;
  48898. }
  48899. }
  48900. }
  48901. }
  48902. // Create lines
  48903. for (index = 0; index < adjacencies.length; index++) {
  48904. // 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
  48905. var current = adjacencies[index];
  48906. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  48907. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  48908. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  48909. }
  48910. // Merge into a single mesh
  48911. var engine = this._source.getScene().getEngine();
  48912. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  48913. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  48914. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  48915. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  48916. this._ib = engine.createIndexBuffer(this._linesIndices);
  48917. this._indicesCount = this._linesIndices.length;
  48918. };
  48919. EdgesRenderer.prototype.render = function () {
  48920. if (!this._lineShader.isReady()) {
  48921. return;
  48922. }
  48923. var scene = this._source.getScene();
  48924. var engine = scene.getEngine();
  48925. this._lineShader._preBind();
  48926. // VBOs
  48927. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  48928. scene.resetCachedMaterial();
  48929. this._lineShader.setColor4("color", this._source.edgesColor);
  48930. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  48931. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  48932. }
  48933. else {
  48934. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  48935. }
  48936. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  48937. this._lineShader.bind(this._source.getWorldMatrix());
  48938. // Draw order
  48939. engine.draw(true, 0, this._indicesCount);
  48940. this._lineShader.unbind();
  48941. engine.setDepthWrite(true);
  48942. };
  48943. return EdgesRenderer;
  48944. })();
  48945. BABYLON.EdgesRenderer = EdgesRenderer;
  48946. })(BABYLON || (BABYLON = {}));
  48947. var BABYLON;
  48948. (function (BABYLON) {
  48949. (function (TonemappingOperator) {
  48950. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48951. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48952. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48953. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48954. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48955. var TonemappingOperator = BABYLON.TonemappingOperator;
  48956. ;
  48957. var TonemapPostProcess = (function (_super) {
  48958. __extends(TonemapPostProcess, _super);
  48959. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48960. var _this = this;
  48961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48962. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48963. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  48964. this._operator = _operator;
  48965. this.exposureAdjustment = exposureAdjustment;
  48966. var defines = "#define ";
  48967. if (this._operator === TonemappingOperator.Hable)
  48968. defines += "HABLE_TONEMAPPING";
  48969. else if (this._operator === TonemappingOperator.Reinhard)
  48970. defines += "REINHARD_TONEMAPPING";
  48971. else if (this._operator === TonemappingOperator.HejiDawson)
  48972. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48973. else if (this._operator === TonemappingOperator.Photographic)
  48974. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48975. //sadly a second call to create the effect.
  48976. this.updateEffect(defines);
  48977. this.onApply = function (effect) {
  48978. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48979. };
  48980. }
  48981. return TonemapPostProcess;
  48982. })(BABYLON.PostProcess);
  48983. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48984. })(BABYLON || (BABYLON = {}));
  48985. var BABYLON;
  48986. (function (BABYLON) {
  48987. var ReflectionProbe = (function () {
  48988. function ReflectionProbe(name, size, scene, generateMipMaps) {
  48989. var _this = this;
  48990. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48991. this.name = name;
  48992. this._viewMatrix = BABYLON.Matrix.Identity();
  48993. this._target = BABYLON.Vector3.Zero();
  48994. this._add = BABYLON.Vector3.Zero();
  48995. this.invertYAxis = false;
  48996. this.position = BABYLON.Vector3.Zero();
  48997. this._scene = scene;
  48998. this._scene.reflectionProbes.push(this);
  48999. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  49000. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  49001. switch (faceIndex) {
  49002. case 0:
  49003. _this._add.copyFromFloats(1, 0, 0);
  49004. break;
  49005. case 1:
  49006. _this._add.copyFromFloats(-1, 0, 0);
  49007. break;
  49008. case 2:
  49009. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  49010. break;
  49011. case 3:
  49012. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  49013. break;
  49014. case 4:
  49015. _this._add.copyFromFloats(0, 0, 1);
  49016. break;
  49017. case 5:
  49018. _this._add.copyFromFloats(0, 0, -1);
  49019. break;
  49020. }
  49021. if (_this._attachedMesh) {
  49022. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  49023. }
  49024. _this.position.addToRef(_this._add, _this._target);
  49025. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  49026. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  49027. });
  49028. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  49029. scene.updateTransformMatrix(true);
  49030. });
  49031. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  49032. }
  49033. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  49034. get: function () {
  49035. return this._renderTargetTexture.refreshRate;
  49036. },
  49037. set: function (value) {
  49038. this._renderTargetTexture.refreshRate = value;
  49039. },
  49040. enumerable: true,
  49041. configurable: true
  49042. });
  49043. ReflectionProbe.prototype.getScene = function () {
  49044. return this._scene;
  49045. };
  49046. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  49047. get: function () {
  49048. return this._renderTargetTexture;
  49049. },
  49050. enumerable: true,
  49051. configurable: true
  49052. });
  49053. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  49054. get: function () {
  49055. return this._renderTargetTexture.renderList;
  49056. },
  49057. enumerable: true,
  49058. configurable: true
  49059. });
  49060. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  49061. this._attachedMesh = mesh;
  49062. };
  49063. ReflectionProbe.prototype.dispose = function () {
  49064. var index = this._scene.reflectionProbes.indexOf(this);
  49065. if (index !== -1) {
  49066. // Remove from the scene if found
  49067. this._scene.reflectionProbes.splice(index, 1);
  49068. }
  49069. if (this._renderTargetTexture) {
  49070. this._renderTargetTexture.dispose();
  49071. this._renderTargetTexture = null;
  49072. }
  49073. };
  49074. return ReflectionProbe;
  49075. })();
  49076. BABYLON.ReflectionProbe = ReflectionProbe;
  49077. })(BABYLON || (BABYLON = {}));
  49078. var BABYLON;
  49079. (function (BABYLON) {
  49080. var SolidParticle = (function () {
  49081. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  49082. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  49083. this.position = BABYLON.Vector3.Zero(); // position
  49084. this.rotation = BABYLON.Vector3.Zero(); // rotation
  49085. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  49086. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  49087. this.velocity = BABYLON.Vector3.Zero(); // velocity
  49088. this.alive = true; // alive
  49089. this.isVisible = true; // visibility
  49090. this.idx = particleIndex;
  49091. this._pos = positionIndex;
  49092. this._model = model;
  49093. this.shapeId = shapeId;
  49094. this.idxInShape = idxInShape;
  49095. }
  49096. Object.defineProperty(SolidParticle.prototype, "scale", {
  49097. //legacy support, changed scale to scaling
  49098. get: function () {
  49099. return this.scaling;
  49100. },
  49101. set: function (scale) {
  49102. this.scaling = scale;
  49103. },
  49104. enumerable: true,
  49105. configurable: true
  49106. });
  49107. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49108. //legacy support, changed quaternion to rotationQuaternion
  49109. get: function () {
  49110. return this.rotationQuaternion;
  49111. },
  49112. set: function (q) {
  49113. this.rotationQuaternion = q;
  49114. },
  49115. enumerable: true,
  49116. configurable: true
  49117. });
  49118. return SolidParticle;
  49119. })();
  49120. BABYLON.SolidParticle = SolidParticle;
  49121. var ModelShape = (function () {
  49122. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49123. this.shapeID = id;
  49124. this._shape = shape;
  49125. this._shapeUV = shapeUV;
  49126. this._positionFunction = posFunction;
  49127. this._vertexFunction = vtxFunction;
  49128. }
  49129. return ModelShape;
  49130. })();
  49131. BABYLON.ModelShape = ModelShape;
  49132. })(BABYLON || (BABYLON = {}));
  49133. var BABYLON;
  49134. (function (BABYLON) {
  49135. /**
  49136. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49137. */
  49138. var SolidParticleSystem = (function () {
  49139. /**
  49140. * Creates a SPS (Solid Particle System) object.
  49141. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49142. * `scene` (Scene) is the scene in which the SPS is added.
  49143. * `updatableè (default true) : if the SPS must be updatable or immutable.
  49144. * `isPickable` (default false) : if the solid particles must be pickable.
  49145. */
  49146. function SolidParticleSystem(name, scene, options) {
  49147. // public members
  49148. /**
  49149. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49150. * Example : var p = SPS.particles[i];
  49151. */
  49152. this.particles = new Array();
  49153. /**
  49154. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49155. */
  49156. this.nbParticles = 0;
  49157. /**
  49158. * If the particles must ever face the camera (default false). Useful for planar particles.
  49159. */
  49160. this.billboard = false;
  49161. /**
  49162. * This a counter ofr your own usage. It's not set by any SPS functions.
  49163. */
  49164. this.counter = 0;
  49165. /**
  49166. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49167. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49168. */
  49169. this.vars = {};
  49170. this._positions = new Array();
  49171. this._indices = new Array();
  49172. this._normals = new Array();
  49173. this._colors = new Array();
  49174. this._uvs = new Array();
  49175. this._index = 0; // indices index
  49176. this._updatable = true;
  49177. this._pickable = false;
  49178. this._isVisibilityBoxLocked = false;
  49179. this._alwaysVisible = false;
  49180. this._shapeCounter = 0;
  49181. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  49182. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49183. this._computeParticleColor = true;
  49184. this._computeParticleTexture = true;
  49185. this._computeParticleRotation = true;
  49186. this._computeParticleVertex = false;
  49187. this._computeBoundingBox = false;
  49188. this._cam_axisZ = BABYLON.Vector3.Zero();
  49189. this._cam_axisY = BABYLON.Vector3.Zero();
  49190. this._cam_axisX = BABYLON.Vector3.Zero();
  49191. this._axisX = BABYLON.Axis.X;
  49192. this._axisY = BABYLON.Axis.Y;
  49193. this._axisZ = BABYLON.Axis.Z;
  49194. this._fakeCamPos = BABYLON.Vector3.Zero();
  49195. this._rotMatrix = new BABYLON.Matrix();
  49196. this._invertMatrix = new BABYLON.Matrix();
  49197. this._rotated = BABYLON.Vector3.Zero();
  49198. this._quaternion = new BABYLON.Quaternion();
  49199. this._vertex = BABYLON.Vector3.Zero();
  49200. this._normal = BABYLON.Vector3.Zero();
  49201. this._yaw = 0.0;
  49202. this._pitch = 0.0;
  49203. this._roll = 0.0;
  49204. this._halfroll = 0.0;
  49205. this._halfpitch = 0.0;
  49206. this._halfyaw = 0.0;
  49207. this._sinRoll = 0.0;
  49208. this._cosRoll = 0.0;
  49209. this._sinPitch = 0.0;
  49210. this._cosPitch = 0.0;
  49211. this._sinYaw = 0.0;
  49212. this._cosYaw = 0.0;
  49213. this._w = 0.0;
  49214. this._minimum = BABYLON.Tmp.Vector3[0];
  49215. this._maximum = BABYLON.Tmp.Vector3[1];
  49216. this.name = name;
  49217. this._scene = scene;
  49218. this._camera = scene.activeCamera;
  49219. this._pickable = options ? options.isPickable : false;
  49220. if (options && options.updatable) {
  49221. this._updatable = options.updatable;
  49222. }
  49223. else {
  49224. this._updatable = true;
  49225. }
  49226. if (this._pickable) {
  49227. this.pickedParticles = [];
  49228. }
  49229. }
  49230. /**
  49231. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49232. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49233. */
  49234. SolidParticleSystem.prototype.buildMesh = function () {
  49235. if (this.nbParticles === 0) {
  49236. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49237. this.addShape(triangle, 1);
  49238. triangle.dispose();
  49239. }
  49240. this._positions32 = new Float32Array(this._positions);
  49241. this._uvs32 = new Float32Array(this._uvs);
  49242. this._colors32 = new Float32Array(this._colors);
  49243. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49244. this._normals32 = new Float32Array(this._normals);
  49245. this._fixedNormal32 = new Float32Array(this._normals);
  49246. var vertexData = new BABYLON.VertexData();
  49247. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49248. vertexData.indices = this._indices;
  49249. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49250. if (this._uvs32) {
  49251. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49252. ;
  49253. }
  49254. if (this._colors32) {
  49255. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49256. }
  49257. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49258. vertexData.applyToMesh(mesh, this._updatable);
  49259. this.mesh = mesh;
  49260. this.mesh.isPickable = this._pickable;
  49261. // free memory
  49262. this._positions = null;
  49263. this._normals = null;
  49264. this._uvs = null;
  49265. this._colors = null;
  49266. if (!this._updatable) {
  49267. this.particles.length = 0;
  49268. }
  49269. return mesh;
  49270. };
  49271. /**
  49272. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49273. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49274. * Thus the particles generated from `digest()` have their property `position` set yet.
  49275. * `mesh` (`Mesh`) is the mesh to be digested
  49276. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49277. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49278. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49279. */
  49280. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49281. var size = (options && options.facetNb) || 1;
  49282. var number = (options && options.number);
  49283. var delta = (options && options.delta) || 0;
  49284. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49285. var meshInd = mesh.getIndices();
  49286. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49287. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49288. var f = 0; // facet counter
  49289. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49290. // compute size from number
  49291. if (number) {
  49292. number = (number > totalFacets) ? totalFacets : number;
  49293. size = Math.round(totalFacets / number);
  49294. delta = 0;
  49295. }
  49296. else {
  49297. size = (size > totalFacets) ? totalFacets : size;
  49298. }
  49299. var facetPos = []; // submesh positions
  49300. var facetInd = []; // submesh indices
  49301. var facetUV = []; // submesh UV
  49302. var facetCol = []; // submesh colors
  49303. var barycenter = BABYLON.Tmp.Vector3[0];
  49304. var rand;
  49305. var sizeO = size;
  49306. while (f < totalFacets) {
  49307. size = sizeO + Math.floor((1 + delta) * Math.random());
  49308. if (f > totalFacets - size) {
  49309. size = totalFacets - f;
  49310. }
  49311. // reset temp arrays
  49312. facetPos.length = 0;
  49313. facetInd.length = 0;
  49314. facetUV.length = 0;
  49315. facetCol.length = 0;
  49316. // iterate over "size" facets
  49317. var fi = 0;
  49318. for (var j = f * 3; j < (f + size) * 3; j++) {
  49319. facetInd.push(fi);
  49320. var i = meshInd[j];
  49321. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49322. if (meshUV) {
  49323. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49324. }
  49325. if (meshCol) {
  49326. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49327. }
  49328. fi++;
  49329. }
  49330. // create a model shape for each single particle
  49331. var idx = this.nbParticles;
  49332. var shape = this._posToShape(facetPos);
  49333. var shapeUV = this._uvsToShapeUV(facetUV);
  49334. // compute the barycenter of the shape
  49335. var v;
  49336. for (v = 0; v < shape.length; v++) {
  49337. barycenter.addInPlace(shape[v]);
  49338. }
  49339. barycenter.scaleInPlace(1 / shape.length);
  49340. // shift the shape from its barycenter to the origin
  49341. for (v = 0; v < shape.length; v++) {
  49342. shape[v].subtractInPlace(barycenter);
  49343. }
  49344. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49345. // add the particle in the SPS
  49346. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  49347. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  49348. // initialize the particle position
  49349. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49350. this._index += shape.length;
  49351. idx++;
  49352. this.nbParticles++;
  49353. this._shapeCounter++;
  49354. f += size;
  49355. }
  49356. return this;
  49357. };
  49358. //reset copy
  49359. SolidParticleSystem.prototype._resetCopy = function () {
  49360. this._copy.position.x = 0;
  49361. this._copy.position.y = 0;
  49362. this._copy.position.z = 0;
  49363. this._copy.rotation.x = 0;
  49364. this._copy.rotation.y = 0;
  49365. this._copy.rotation.z = 0;
  49366. this._copy.rotationQuaternion = null;
  49367. this._copy.scaling.x = 1;
  49368. this._copy.scaling.y = 1;
  49369. this._copy.scaling.z = 1;
  49370. this._copy.uvs.x = 0;
  49371. this._copy.uvs.y = 0;
  49372. this._copy.uvs.z = 1;
  49373. this._copy.uvs.w = 1;
  49374. this._copy.color = null;
  49375. };
  49376. // _meshBuilder : inserts the shape model in the global SPS mesh
  49377. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  49378. var i;
  49379. var u = 0;
  49380. var c = 0;
  49381. this._resetCopy();
  49382. if (options && options.positionFunction) {
  49383. options.positionFunction(this._copy, idx, idxInShape);
  49384. }
  49385. if (this._copy.rotationQuaternion) {
  49386. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49387. }
  49388. else {
  49389. this._yaw = this._copy.rotation.y;
  49390. this._pitch = this._copy.rotation.x;
  49391. this._roll = this._copy.rotation.z;
  49392. this._quaternionRotationYPR();
  49393. }
  49394. this._quaternionToRotationMatrix();
  49395. for (i = 0; i < shape.length; i++) {
  49396. this._vertex.x = shape[i].x;
  49397. this._vertex.y = shape[i].y;
  49398. this._vertex.z = shape[i].z;
  49399. if (options && options.vertexFunction) {
  49400. options.vertexFunction(this._copy, this._vertex, i);
  49401. }
  49402. this._vertex.x *= this._copy.scaling.x;
  49403. this._vertex.y *= this._copy.scaling.y;
  49404. this._vertex.z *= this._copy.scaling.z;
  49405. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49406. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49407. if (meshUV) {
  49408. 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);
  49409. u += 2;
  49410. }
  49411. if (this._copy.color) {
  49412. this._color = this._copy.color;
  49413. }
  49414. else if (meshCol && meshCol[c]) {
  49415. this._color.r = meshCol[c];
  49416. this._color.g = meshCol[c + 1];
  49417. this._color.b = meshCol[c + 2];
  49418. this._color.a = meshCol[c + 3];
  49419. }
  49420. else {
  49421. this._color.r = 1;
  49422. this._color.g = 1;
  49423. this._color.b = 1;
  49424. this._color.a = 1;
  49425. }
  49426. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49427. c += 4;
  49428. }
  49429. for (i = 0; i < meshInd.length; i++) {
  49430. indices.push(p + meshInd[i]);
  49431. }
  49432. if (this._pickable) {
  49433. var nbfaces = meshInd.length / 3;
  49434. for (i = 0; i < nbfaces; i++) {
  49435. this.pickedParticles.push({ idx: idx, faceId: i });
  49436. }
  49437. }
  49438. };
  49439. // returns a shape array from positions array
  49440. SolidParticleSystem.prototype._posToShape = function (positions) {
  49441. var shape = [];
  49442. for (var i = 0; i < positions.length; i += 3) {
  49443. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49444. }
  49445. return shape;
  49446. };
  49447. // returns a shapeUV array from a Vector4 uvs
  49448. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49449. var shapeUV = [];
  49450. if (uvs) {
  49451. for (var i = 0; i < uvs.length; i++)
  49452. shapeUV.push(uvs[i]);
  49453. }
  49454. return shapeUV;
  49455. };
  49456. // adds a new particle object in the particles array
  49457. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  49458. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  49459. };
  49460. /**
  49461. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49462. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49463. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  49464. * `nb` (positive integer) the number of particles to be created from this model
  49465. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  49466. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  49467. */
  49468. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49469. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49470. var meshInd = mesh.getIndices();
  49471. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49472. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49473. var shape = this._posToShape(meshPos);
  49474. var shapeUV = this._uvsToShapeUV(meshUV);
  49475. var posfunc = options ? options.positionFunction : null;
  49476. var vtxfunc = options ? options.vertexFunction : null;
  49477. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  49478. // particles
  49479. var idx = this.nbParticles;
  49480. for (var i = 0; i < nb; i++) {
  49481. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  49482. if (this._updatable) {
  49483. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  49484. }
  49485. this._index += shape.length;
  49486. idx++;
  49487. }
  49488. this.nbParticles += nb;
  49489. this._shapeCounter++;
  49490. return this._shapeCounter - 1;
  49491. };
  49492. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49493. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49494. this._resetCopy();
  49495. if (particle._model._positionFunction) {
  49496. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49497. }
  49498. if (this._copy.rotationQuaternion) {
  49499. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49500. }
  49501. else {
  49502. this._yaw = this._copy.rotation.y;
  49503. this._pitch = this._copy.rotation.x;
  49504. this._roll = this._copy.rotation.z;
  49505. this._quaternionRotationYPR();
  49506. }
  49507. this._quaternionToRotationMatrix();
  49508. this._shape = particle._model._shape;
  49509. for (var pt = 0; pt < this._shape.length; pt++) {
  49510. this._vertex.x = this._shape[pt].x;
  49511. this._vertex.y = this._shape[pt].y;
  49512. this._vertex.z = this._shape[pt].z;
  49513. if (particle._model._vertexFunction) {
  49514. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49515. }
  49516. this._vertex.x *= this._copy.scaling.x;
  49517. this._vertex.y *= this._copy.scaling.y;
  49518. this._vertex.z *= this._copy.scaling.z;
  49519. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49520. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49521. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49522. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49523. }
  49524. particle.position.x = 0;
  49525. particle.position.y = 0;
  49526. particle.position.z = 0;
  49527. particle.rotation.x = 0;
  49528. particle.rotation.y = 0;
  49529. particle.rotation.z = 0;
  49530. particle.rotationQuaternion = null;
  49531. particle.scaling.x = 1;
  49532. particle.scaling.y = 1;
  49533. particle.scaling.z = 1;
  49534. };
  49535. /**
  49536. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49537. */
  49538. SolidParticleSystem.prototype.rebuildMesh = function () {
  49539. for (var p = 0; p < this.particles.length; p++) {
  49540. this._rebuildParticle(this.particles[p]);
  49541. }
  49542. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49543. };
  49544. /**
  49545. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49546. * This method calls `updateParticle()` for each particle of the SPS.
  49547. * For an animated SPS, it is usually called within the render loop.
  49548. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  49549. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  49550. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  49551. */
  49552. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49553. if (start === void 0) { start = 0; }
  49554. if (end === void 0) { end = this.nbParticles - 1; }
  49555. if (update === void 0) { update = true; }
  49556. if (!this._updatable) {
  49557. return;
  49558. }
  49559. // custom beforeUpdate
  49560. this.beforeUpdateParticles(start, end, update);
  49561. this._cam_axisX.x = 1;
  49562. this._cam_axisX.y = 0;
  49563. this._cam_axisX.z = 0;
  49564. this._cam_axisY.x = 0;
  49565. this._cam_axisY.y = 1;
  49566. this._cam_axisY.z = 0;
  49567. this._cam_axisZ.x = 0;
  49568. this._cam_axisZ.y = 0;
  49569. this._cam_axisZ.z = 1;
  49570. // if the particles will always face the camera
  49571. if (this.billboard) {
  49572. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  49573. this._yaw = this.mesh.rotation.y;
  49574. this._pitch = this.mesh.rotation.x;
  49575. this._roll = this.mesh.rotation.z;
  49576. this._quaternionRotationYPR();
  49577. this._quaternionToRotationMatrix();
  49578. this._rotMatrix.invertToRef(this._invertMatrix);
  49579. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  49580. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  49581. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  49582. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  49583. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  49584. this._cam_axisY.normalize();
  49585. this._cam_axisX.normalize();
  49586. this._cam_axisZ.normalize();
  49587. }
  49588. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49589. var idx = 0;
  49590. var index = 0;
  49591. var colidx = 0;
  49592. var colorIndex = 0;
  49593. var uvidx = 0;
  49594. var uvIndex = 0;
  49595. var pt = 0;
  49596. if (this._computeBoundingBox) {
  49597. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49598. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49599. }
  49600. // particle loop
  49601. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  49602. for (var p = start; p <= end; p++) {
  49603. this._particle = this.particles[p];
  49604. this._shape = this._particle._model._shape;
  49605. this._shapeUV = this._particle._model._shapeUV;
  49606. // call to custom user function to update the particle properties
  49607. this.updateParticle(this._particle);
  49608. if (this._particle.isVisible) {
  49609. // particle rotation matrix
  49610. if (this.billboard) {
  49611. this._particle.rotation.x = 0.0;
  49612. this._particle.rotation.y = 0.0;
  49613. }
  49614. if (this._computeParticleRotation) {
  49615. if (this._particle.rotationQuaternion) {
  49616. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49617. }
  49618. else {
  49619. this._yaw = this._particle.rotation.y;
  49620. this._pitch = this._particle.rotation.x;
  49621. this._roll = this._particle.rotation.z;
  49622. this._quaternionRotationYPR();
  49623. }
  49624. this._quaternionToRotationMatrix();
  49625. }
  49626. // particle vertex loop
  49627. for (pt = 0; pt < this._shape.length; pt++) {
  49628. idx = index + pt * 3;
  49629. colidx = colorIndex + pt * 4;
  49630. uvidx = uvIndex + pt * 2;
  49631. this._vertex.x = this._shape[pt].x;
  49632. this._vertex.y = this._shape[pt].y;
  49633. this._vertex.z = this._shape[pt].z;
  49634. if (this._computeParticleVertex) {
  49635. this.updateParticleVertex(this._particle, this._vertex, pt);
  49636. }
  49637. // positions
  49638. this._vertex.x *= this._particle.scaling.x;
  49639. this._vertex.y *= this._particle.scaling.y;
  49640. this._vertex.z *= this._particle.scaling.z;
  49641. 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];
  49642. 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;
  49643. 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;
  49644. 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;
  49645. 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;
  49646. 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;
  49647. 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;
  49648. if (this._computeBoundingBox) {
  49649. if (this._positions32[idx] < this._minimum.x) {
  49650. this._minimum.x = this._positions32[idx];
  49651. }
  49652. if (this._positions32[idx] > this._maximum.x) {
  49653. this._maximum.x = this._positions32[idx];
  49654. }
  49655. if (this._positions32[idx + 1] < this._minimum.y) {
  49656. this._minimum.y = this._positions32[idx + 1];
  49657. }
  49658. if (this._positions32[idx + 1] > this._maximum.y) {
  49659. this._maximum.y = this._positions32[idx + 1];
  49660. }
  49661. if (this._positions32[idx + 2] < this._minimum.z) {
  49662. this._minimum.z = this._positions32[idx + 2];
  49663. }
  49664. if (this._positions32[idx + 2] > this._maximum.z) {
  49665. this._maximum.z = this._positions32[idx + 2];
  49666. }
  49667. }
  49668. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49669. if (!this._computeParticleVertex && !this.billboard) {
  49670. this._normal.x = this._fixedNormal32[idx];
  49671. this._normal.y = this._fixedNormal32[idx + 1];
  49672. this._normal.z = this._fixedNormal32[idx + 2];
  49673. 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];
  49674. 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;
  49675. 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;
  49676. 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;
  49677. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49678. 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;
  49679. 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;
  49680. }
  49681. if (this._computeParticleColor) {
  49682. this._colors32[colidx] = this._particle.color.r;
  49683. this._colors32[colidx + 1] = this._particle.color.g;
  49684. this._colors32[colidx + 2] = this._particle.color.b;
  49685. this._colors32[colidx + 3] = this._particle.color.a;
  49686. }
  49687. if (this._computeParticleTexture) {
  49688. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49689. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49690. }
  49691. }
  49692. }
  49693. else {
  49694. for (pt = 0; pt < this._shape.length; pt++) {
  49695. idx = index + pt * 3;
  49696. colidx = colorIndex + pt * 4;
  49697. uvidx = uvIndex + pt * 2;
  49698. this._positions32[idx] = this._camera.position.x;
  49699. this._positions32[idx + 1] = this._camera.position.y;
  49700. this._positions32[idx + 2] = this._camera.position.z;
  49701. this._normals32[idx] = 0.0;
  49702. this._normals32[idx + 1] = 0.0;
  49703. this._normals32[idx + 2] = 0.0;
  49704. if (this._computeParticleColor) {
  49705. this._colors32[colidx] = this._particle.color.r;
  49706. this._colors32[colidx + 1] = this._particle.color.g;
  49707. this._colors32[colidx + 2] = this._particle.color.b;
  49708. this._colors32[colidx + 3] = this._particle.color.a;
  49709. }
  49710. if (this._computeParticleTexture) {
  49711. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49712. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49713. }
  49714. }
  49715. }
  49716. // increment indexes for the next particle
  49717. index = idx + 3;
  49718. colorIndex = colidx + 4;
  49719. uvIndex = uvidx + 2;
  49720. }
  49721. // if the VBO must be updated
  49722. if (update) {
  49723. if (this._computeParticleColor) {
  49724. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49725. }
  49726. if (this._computeParticleTexture) {
  49727. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49728. }
  49729. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49730. if (!this.mesh.areNormalsFrozen) {
  49731. if (this._computeParticleVertex || this.billboard) {
  49732. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49733. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  49734. for (var i = 0; i < this._normals32.length; i++) {
  49735. this._fixedNormal32[i] = this._normals32[i];
  49736. }
  49737. }
  49738. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49739. }
  49740. }
  49741. if (this._computeBoundingBox) {
  49742. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49743. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49744. }
  49745. this.afterUpdateParticles(start, end, update);
  49746. };
  49747. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49748. this._halfroll = this._roll * 0.5;
  49749. this._halfpitch = this._pitch * 0.5;
  49750. this._halfyaw = this._yaw * 0.5;
  49751. this._sinRoll = Math.sin(this._halfroll);
  49752. this._cosRoll = Math.cos(this._halfroll);
  49753. this._sinPitch = Math.sin(this._halfpitch);
  49754. this._cosPitch = Math.cos(this._halfpitch);
  49755. this._sinYaw = Math.sin(this._halfyaw);
  49756. this._cosYaw = Math.cos(this._halfyaw);
  49757. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  49758. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  49759. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  49760. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  49761. };
  49762. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49763. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49764. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49765. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49766. this._rotMatrix.m[3] = 0;
  49767. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49768. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49769. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49770. this._rotMatrix.m[7] = 0;
  49771. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49772. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49773. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49774. this._rotMatrix.m[11] = 0;
  49775. this._rotMatrix.m[12] = 0;
  49776. this._rotMatrix.m[13] = 0;
  49777. this._rotMatrix.m[14] = 0;
  49778. this._rotMatrix.m[15] = 1.0;
  49779. };
  49780. /**
  49781. * Disposes the SPS
  49782. */
  49783. SolidParticleSystem.prototype.dispose = function () {
  49784. this.mesh.dispose();
  49785. this.vars = null;
  49786. // drop references to internal big arrays for the GC
  49787. this._positions = null;
  49788. this._indices = null;
  49789. this._normals = null;
  49790. this._uvs = null;
  49791. this._colors = null;
  49792. this._positions32 = null;
  49793. this._normals32 = null;
  49794. this._fixedNormal32 = null;
  49795. this._uvs32 = null;
  49796. this._colors32 = null;
  49797. this.pickedParticles = null;
  49798. };
  49799. /**
  49800. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49801. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49802. */
  49803. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49804. if (!this._isVisibilityBoxLocked) {
  49805. this.mesh.refreshBoundingInfo();
  49806. }
  49807. };
  49808. /**
  49809. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49810. * @param size the size (float) of the visibility box
  49811. * note : this doesn't lock the SPS mesh bounding box.
  49812. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49813. */
  49814. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49815. var vis = size / 2;
  49816. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49817. };
  49818. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49819. // getter and setter
  49820. get: function () {
  49821. return this._alwaysVisible;
  49822. },
  49823. /**
  49824. * Sets the SPS as always visible or not
  49825. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49826. */
  49827. set: function (val) {
  49828. this._alwaysVisible = val;
  49829. this.mesh.alwaysSelectAsActiveMesh = val;
  49830. },
  49831. enumerable: true,
  49832. configurable: true
  49833. });
  49834. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49835. get: function () {
  49836. return this._isVisibilityBoxLocked;
  49837. },
  49838. /**
  49839. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49840. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49841. */
  49842. set: function (val) {
  49843. this._isVisibilityBoxLocked = val;
  49844. this.mesh.getBoundingInfo().isLocked = val;
  49845. },
  49846. enumerable: true,
  49847. configurable: true
  49848. });
  49849. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49850. // getters
  49851. get: function () {
  49852. return this._computeParticleRotation;
  49853. },
  49854. // Optimizer setters
  49855. /**
  49856. * Tells to `setParticles()` to compute the particle rotations or not.
  49857. * Default value : true. The SPS is faster when it's set to false.
  49858. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49859. */
  49860. set: function (val) {
  49861. this._computeParticleRotation = val;
  49862. },
  49863. enumerable: true,
  49864. configurable: true
  49865. });
  49866. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49867. get: function () {
  49868. return this._computeParticleColor;
  49869. },
  49870. /**
  49871. * Tells to `setParticles()` to compute the particle colors or not.
  49872. * Default value : true. The SPS is faster when it's set to false.
  49873. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49874. */
  49875. set: function (val) {
  49876. this._computeParticleColor = val;
  49877. },
  49878. enumerable: true,
  49879. configurable: true
  49880. });
  49881. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49882. get: function () {
  49883. return this._computeParticleTexture;
  49884. },
  49885. /**
  49886. * Tells to `setParticles()` to compute the particle textures or not.
  49887. * Default value : true. The SPS is faster when it's set to false.
  49888. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49889. */
  49890. set: function (val) {
  49891. this._computeParticleTexture = val;
  49892. },
  49893. enumerable: true,
  49894. configurable: true
  49895. });
  49896. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49897. get: function () {
  49898. return this._computeParticleVertex;
  49899. },
  49900. /**
  49901. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49902. * Default value : false. The SPS is faster when it's set to false.
  49903. * Note : the particle custom vertex positions aren't stored values.
  49904. */
  49905. set: function (val) {
  49906. this._computeParticleVertex = val;
  49907. },
  49908. enumerable: true,
  49909. configurable: true
  49910. });
  49911. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49912. get: function () {
  49913. return this._computeBoundingBox;
  49914. },
  49915. /**
  49916. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49917. */
  49918. set: function (val) {
  49919. this._computeBoundingBox = val;
  49920. },
  49921. enumerable: true,
  49922. configurable: true
  49923. });
  49924. // =======================================================================
  49925. // Particle behavior logic
  49926. // these following methods may be overwritten by the user to fit his needs
  49927. /**
  49928. * This function does nothing. It may be overwritten to set all the particle first values.
  49929. * The SPS doesn't call this function, you may have to call it by your own.
  49930. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49931. */
  49932. SolidParticleSystem.prototype.initParticles = function () {
  49933. };
  49934. /**
  49935. * This function does nothing. It may be overwritten to recycle a particle.
  49936. * The SPS doesn't call this function, you may have to call it by your own.
  49937. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49938. */
  49939. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49940. return particle;
  49941. };
  49942. /**
  49943. * Updates a particle : this function should be overwritten by the user.
  49944. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49945. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49946. * ex : just set a particle position or velocity and recycle conditions
  49947. */
  49948. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49949. return particle;
  49950. };
  49951. /**
  49952. * Updates a vertex of a particle : it can be overwritten by the user.
  49953. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49954. * @param particle the current particle
  49955. * @param vertex the current index of the current particle
  49956. * @param pt the index of the current vertex in the particle shape
  49957. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49958. * ex : just set a vertex particle position
  49959. */
  49960. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49961. return vertex;
  49962. };
  49963. /**
  49964. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49965. * This does nothing and may be overwritten by the user.
  49966. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49967. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49968. * @param update the boolean update value actually passed to setParticles()
  49969. */
  49970. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49971. };
  49972. /**
  49973. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49974. * This will be passed three parameters.
  49975. * This does nothing and may be overwritten by the user.
  49976. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49977. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49978. * @param update the boolean update value actually passed to setParticles()
  49979. */
  49980. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49981. };
  49982. return SolidParticleSystem;
  49983. })();
  49984. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49985. })(BABYLON || (BABYLON = {}));
  49986. var BABYLON;
  49987. (function (BABYLON) {
  49988. var Internals;
  49989. (function (Internals) {
  49990. var FileFaceOrientation = (function () {
  49991. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49992. this.name = name;
  49993. this.worldAxisForNormal = worldAxisForNormal;
  49994. this.worldAxisForFileX = worldAxisForFileX;
  49995. this.worldAxisForFileY = worldAxisForFileY;
  49996. }
  49997. return FileFaceOrientation;
  49998. })();
  49999. ;
  50000. /**
  50001. * Helper class dealing with the extraction of spherical polynomial dataArray
  50002. * from a cube map.
  50003. */
  50004. var CubeMapToSphericalPolynomialTools = (function () {
  50005. function CubeMapToSphericalPolynomialTools() {
  50006. }
  50007. /**
  50008. * Converts a cubemap to the according Spherical Polynomial data.
  50009. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50010. *
  50011. * @param cubeInfo The Cube map to extract the information from.
  50012. * @return The Spherical Polynomial data.
  50013. */
  50014. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50015. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50016. var totalSolidAngle = 0.0;
  50017. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50018. var du = 2.0 / cubeInfo.size;
  50019. var dv = du;
  50020. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50021. var minUV = du * 0.5 - 1.0;
  50022. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50023. var fileFace = this.FileFaces[faceIndex];
  50024. var dataArray = cubeInfo[fileFace.name];
  50025. var v = minUV;
  50026. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50027. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50028. // Because SP is still linear, so summation is fine in that basis.
  50029. for (var y = 0; y < cubeInfo.size; y++) {
  50030. var u = minUV;
  50031. for (var x = 0; x < cubeInfo.size; x++) {
  50032. // World direction (not normalised)
  50033. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50034. worldDirection.normalize();
  50035. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50036. if (1) {
  50037. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50038. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50039. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50040. var color = new BABYLON.Color3(r, g, b);
  50041. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50042. }
  50043. else {
  50044. if (faceIndex == 0) {
  50045. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50046. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50047. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50048. }
  50049. else if (faceIndex == 1) {
  50050. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50051. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50052. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50053. }
  50054. else if (faceIndex == 2) {
  50055. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50056. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50057. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50058. }
  50059. else if (faceIndex == 3) {
  50060. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50061. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50062. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50063. }
  50064. else if (faceIndex == 4) {
  50065. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50066. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50067. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50068. }
  50069. else if (faceIndex == 5) {
  50070. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50071. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50072. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50073. }
  50074. 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]);
  50075. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50076. }
  50077. totalSolidAngle += deltaSolidAngle;
  50078. u += du;
  50079. }
  50080. v += dv;
  50081. }
  50082. }
  50083. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50084. var correction = correctSolidAngle / totalSolidAngle;
  50085. sphericalHarmonics.scale(correction);
  50086. // Additionally scale by pi -- audit needed
  50087. sphericalHarmonics.scale(1.0 / Math.PI);
  50088. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50089. };
  50090. CubeMapToSphericalPolynomialTools.FileFaces = [
  50091. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50092. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50093. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50094. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50095. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50096. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50097. ];
  50098. return CubeMapToSphericalPolynomialTools;
  50099. })();
  50100. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50101. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50102. })(BABYLON || (BABYLON = {}));
  50103. var BABYLON;
  50104. (function (BABYLON) {
  50105. var Internals;
  50106. (function (Internals) {
  50107. /**
  50108. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50109. */
  50110. var PanoramaToCubeMapTools = (function () {
  50111. function PanoramaToCubeMapTools() {
  50112. }
  50113. /**
  50114. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50115. *
  50116. * @param float32Array The source data.
  50117. * @param inputWidth The width of the input panorama.
  50118. * @param inputhHeight The height of the input panorama.
  50119. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50120. * @return The cubemap data
  50121. */
  50122. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50123. if (!float32Array) {
  50124. throw "ConvertPanoramaToCubemap: input cannot be null";
  50125. }
  50126. if (float32Array.length != inputWidth * inputHeight * 3) {
  50127. throw "ConvertPanoramaToCubemap: input size is wrong";
  50128. }
  50129. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50130. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50131. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50132. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50133. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50134. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50135. return {
  50136. front: textureFront,
  50137. back: textureBack,
  50138. left: textureLeft,
  50139. right: textureRight,
  50140. up: textureUp,
  50141. down: textureDown,
  50142. size: size
  50143. };
  50144. };
  50145. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50146. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50147. var textureArray = new Float32Array(buffer);
  50148. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50149. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50150. var dy = 1 / texSize;
  50151. var fy = 0;
  50152. for (var y = 0; y < texSize; y++) {
  50153. var xv1 = faceData[0];
  50154. var xv2 = faceData[2];
  50155. for (var x = 0; x < texSize; x++) {
  50156. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50157. v.normalize();
  50158. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50159. // 3 channels per pixels
  50160. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50161. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50162. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50163. xv1 = xv1.add(rotDX1);
  50164. xv2 = xv2.add(rotDX2);
  50165. }
  50166. fy += dy;
  50167. }
  50168. return textureArray;
  50169. };
  50170. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50171. var theta = Math.atan2(vDir.z, vDir.x);
  50172. var phi = Math.acos(vDir.y);
  50173. while (theta < -Math.PI)
  50174. theta += 2 * Math.PI;
  50175. while (theta > Math.PI)
  50176. theta -= 2 * Math.PI;
  50177. var dx = theta / Math.PI;
  50178. var dy = phi / Math.PI;
  50179. // recenter.
  50180. dx = dx * 0.5 + 0.5;
  50181. var px = Math.round(dx * inputWidth);
  50182. if (px < 0)
  50183. px = 0;
  50184. else if (px >= inputWidth)
  50185. px = inputWidth - 1;
  50186. var py = Math.round(dy * inputHeight);
  50187. if (py < 0)
  50188. py = 0;
  50189. else if (py >= inputHeight)
  50190. py = inputHeight - 1;
  50191. var inputY = (inputHeight - py - 1);
  50192. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50193. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50194. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50195. return {
  50196. r: r,
  50197. g: g,
  50198. b: b
  50199. };
  50200. };
  50201. PanoramaToCubeMapTools.FACE_FRONT = [
  50202. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50203. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50204. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50205. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50206. ];
  50207. PanoramaToCubeMapTools.FACE_BACK = [
  50208. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50209. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50210. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50211. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50212. ];
  50213. PanoramaToCubeMapTools.FACE_RIGHT = [
  50214. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50215. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50216. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50217. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50218. ];
  50219. PanoramaToCubeMapTools.FACE_LEFT = [
  50220. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50221. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50222. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50223. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50224. ];
  50225. PanoramaToCubeMapTools.FACE_DOWN = [
  50226. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50227. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50228. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50229. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50230. ];
  50231. PanoramaToCubeMapTools.FACE_UP = [
  50232. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50233. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50234. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50235. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50236. ];
  50237. return PanoramaToCubeMapTools;
  50238. })();
  50239. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50240. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50241. })(BABYLON || (BABYLON = {}));
  50242. var BABYLON;
  50243. (function (BABYLON) {
  50244. var Internals;
  50245. (function (Internals) {
  50246. ;
  50247. /**
  50248. * This groups tools to convert HDR texture to native colors array.
  50249. */
  50250. var HDRTools = (function () {
  50251. function HDRTools() {
  50252. }
  50253. HDRTools.Ldexp = function (mantissa, exponent) {
  50254. if (exponent > 1023) {
  50255. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50256. }
  50257. if (exponent < -1074) {
  50258. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50259. }
  50260. return mantissa * Math.pow(2, exponent);
  50261. };
  50262. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50263. if (exponent > 0) {
  50264. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50265. float32array[index + 0] = red * exponent;
  50266. float32array[index + 1] = green * exponent;
  50267. float32array[index + 2] = blue * exponent;
  50268. }
  50269. else {
  50270. float32array[index + 0] = 0;
  50271. float32array[index + 1] = 0;
  50272. float32array[index + 2] = 0;
  50273. }
  50274. };
  50275. HDRTools.readStringLine = function (uint8array, startIndex) {
  50276. var line = "";
  50277. var character = "";
  50278. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50279. character = String.fromCharCode(uint8array[i]);
  50280. if (character == "\n") {
  50281. break;
  50282. }
  50283. line += character;
  50284. }
  50285. return line;
  50286. };
  50287. /**
  50288. * Reads header information from an RGBE texture stored in a native array.
  50289. * More information on this format are available here:
  50290. * https://en.wikipedia.org/wiki/RGBE_image_format
  50291. *
  50292. * @param uint8array The binary file stored in native array.
  50293. * @return The header information.
  50294. */
  50295. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50296. var height = 0;
  50297. var width = 0;
  50298. var line = this.readStringLine(uint8array, 0);
  50299. if (line[0] != '#' || line[1] != '?') {
  50300. throw "Bad HDR Format.";
  50301. }
  50302. var endOfHeader = false;
  50303. var findFormat = false;
  50304. var lineIndex = 0;
  50305. do {
  50306. lineIndex += (line.length + 1);
  50307. line = this.readStringLine(uint8array, lineIndex);
  50308. if (line == "FORMAT=32-bit_rle_rgbe") {
  50309. findFormat = true;
  50310. }
  50311. else if (line.length == 0) {
  50312. endOfHeader = true;
  50313. }
  50314. } while (!endOfHeader);
  50315. if (!findFormat) {
  50316. throw "HDR Bad header format, unsupported FORMAT";
  50317. }
  50318. lineIndex += (line.length + 1);
  50319. line = this.readStringLine(uint8array, lineIndex);
  50320. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50321. var match = sizeRegexp.exec(line);
  50322. // TODO. Support +Y and -X if needed.
  50323. if (match.length < 3) {
  50324. throw "HDR Bad header format, no size";
  50325. }
  50326. width = parseInt(match[2]);
  50327. height = parseInt(match[1]);
  50328. if (width < 8 || width > 0x7fff) {
  50329. throw "HDR Bad header format, unsupported size";
  50330. }
  50331. lineIndex += (line.length + 1);
  50332. return {
  50333. height: height,
  50334. width: width,
  50335. dataPosition: lineIndex
  50336. };
  50337. };
  50338. /**
  50339. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50340. * This RGBE texture needs to store the information as a panorama.
  50341. *
  50342. * More information on this format are available here:
  50343. * https://en.wikipedia.org/wiki/RGBE_image_format
  50344. *
  50345. * @param buffer The binary file stored in an array buffer.
  50346. * @param size The expected size of the extracted cubemap.
  50347. * @return The Cube Map information.
  50348. */
  50349. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50350. var uint8array = new Uint8Array(buffer);
  50351. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50352. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50353. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50354. return cubeMapData;
  50355. };
  50356. /**
  50357. * Returns the pixels data extracted from an RGBE texture.
  50358. * This pixels will be stored left to right up to down in the R G B order in one array.
  50359. *
  50360. * More information on this format are available here:
  50361. * https://en.wikipedia.org/wiki/RGBE_image_format
  50362. *
  50363. * @param uint8array The binary file stored in an array buffer.
  50364. * @param hdrInfo The header information of the file.
  50365. * @return The pixels data in RGB right to left up to down order.
  50366. */
  50367. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50368. // Keep for multi format supports.
  50369. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50370. };
  50371. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50372. var num_scanlines = hdrInfo.height;
  50373. var scanline_width = hdrInfo.width;
  50374. var a, b, c, d, count;
  50375. var dataIndex = hdrInfo.dataPosition;
  50376. var index = 0, endIndex = 0, i = 0;
  50377. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50378. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50379. // 3 channels of 4 bytes per pixel in float.
  50380. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50381. var resultArray = new Float32Array(resultBuffer);
  50382. // read in each successive scanline
  50383. while (num_scanlines > 0) {
  50384. a = uint8array[dataIndex++];
  50385. b = uint8array[dataIndex++];
  50386. c = uint8array[dataIndex++];
  50387. d = uint8array[dataIndex++];
  50388. if (a != 2 || b != 2 || (c & 0x80)) {
  50389. // this file is not run length encoded
  50390. throw "HDR Bad header format, not RLE";
  50391. }
  50392. if (((c << 8) | d) != scanline_width) {
  50393. throw "HDR Bad header format, wrong scan line width";
  50394. }
  50395. index = 0;
  50396. // read each of the four channels for the scanline into the buffer
  50397. for (i = 0; i < 4; i++) {
  50398. endIndex = (i + 1) * scanline_width;
  50399. while (index < endIndex) {
  50400. a = uint8array[dataIndex++];
  50401. b = uint8array[dataIndex++];
  50402. if (a > 128) {
  50403. // a run of the same value
  50404. count = a - 128;
  50405. if ((count == 0) || (count > endIndex - index)) {
  50406. throw "HDR Bad Format, bad scanline data (run)";
  50407. }
  50408. while (count-- > 0) {
  50409. scanLineArray[index++] = b;
  50410. }
  50411. }
  50412. else {
  50413. // a non-run
  50414. count = a;
  50415. if ((count == 0) || (count > endIndex - index)) {
  50416. throw "HDR Bad Format, bad scanline data (non-run)";
  50417. }
  50418. scanLineArray[index++] = b;
  50419. if (--count > 0) {
  50420. for (var j = 0; j < count; j++) {
  50421. scanLineArray[index++] = uint8array[dataIndex++];
  50422. }
  50423. }
  50424. }
  50425. }
  50426. }
  50427. // now convert data from buffer into floats
  50428. for (i = 0; i < scanline_width; i++) {
  50429. a = scanLineArray[i];
  50430. b = scanLineArray[i + scanline_width];
  50431. c = scanLineArray[i + 2 * scanline_width];
  50432. d = scanLineArray[i + 3 * scanline_width];
  50433. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50434. }
  50435. num_scanlines--;
  50436. }
  50437. return resultArray;
  50438. };
  50439. return HDRTools;
  50440. })();
  50441. Internals.HDRTools = HDRTools;
  50442. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50443. })(BABYLON || (BABYLON = {}));
  50444. //_______________________________________________________________
  50445. // Extracted from CubeMapGen:
  50446. // https://code.google.com/archive/p/cubemapgen/
  50447. //
  50448. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50449. //_______________________________________________________________
  50450. var BABYLON;
  50451. (function (BABYLON) {
  50452. var Internals;
  50453. (function (Internals) {
  50454. /**
  50455. * The bounding box information used during the conversion process.
  50456. */
  50457. var CMGBoundinBox = (function () {
  50458. function CMGBoundinBox() {
  50459. this.min = new BABYLON.Vector3(0, 0, 0);
  50460. this.max = new BABYLON.Vector3(0, 0, 0);
  50461. this.clear();
  50462. }
  50463. CMGBoundinBox.prototype.clear = function () {
  50464. this.min.x = CMGBoundinBox.MAX;
  50465. this.min.y = CMGBoundinBox.MAX;
  50466. this.min.z = CMGBoundinBox.MAX;
  50467. this.max.x = CMGBoundinBox.MIN;
  50468. this.max.y = CMGBoundinBox.MIN;
  50469. this.max.z = CMGBoundinBox.MIN;
  50470. };
  50471. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50472. this.min.x = Math.min(this.min.x, x);
  50473. this.min.y = Math.min(this.min.y, y);
  50474. this.min.z = Math.min(this.min.z, z);
  50475. this.max.x = Math.max(this.max.x, x);
  50476. this.max.y = Math.max(this.max.y, y);
  50477. this.max.z = Math.max(this.max.z, z);
  50478. };
  50479. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50480. this.min.x = Math.max(this.min.x, x);
  50481. this.min.y = Math.max(this.min.y, y);
  50482. this.min.z = Math.max(this.min.z, z);
  50483. };
  50484. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50485. this.max.x = Math.min(this.max.x, x);
  50486. this.max.y = Math.min(this.max.y, y);
  50487. this.max.z = Math.min(this.max.z, z);
  50488. };
  50489. CMGBoundinBox.prototype.empty = function () {
  50490. if ((this.min.x > this.max.y) ||
  50491. (this.min.y > this.max.y) ||
  50492. (this.min.z > this.max.y)) {
  50493. return true;
  50494. }
  50495. else {
  50496. return false;
  50497. }
  50498. };
  50499. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50500. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50501. return CMGBoundinBox;
  50502. })();
  50503. /**
  50504. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50505. * required by the glossinees of a material.
  50506. *
  50507. * This only supports the cosine drop power as well as Warp fixup generation method.
  50508. *
  50509. * This is using the process from CubeMapGen described here:
  50510. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50511. */
  50512. var PMREMGenerator = (function () {
  50513. /**
  50514. * Constructor of the generator.
  50515. *
  50516. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50517. * @param inputSize The size of the cubemap faces
  50518. * @param outputSize The size of the output cubemap faces
  50519. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50520. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50521. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50522. * @param specularPower The max specular level of the desired cubemap
  50523. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50524. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50525. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50526. */
  50527. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50528. this.input = input;
  50529. this.inputSize = inputSize;
  50530. this.outputSize = outputSize;
  50531. this.maxNumMipLevels = maxNumMipLevels;
  50532. this.numChannels = numChannels;
  50533. this.isFloat = isFloat;
  50534. this.specularPower = specularPower;
  50535. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50536. this.excludeBase = excludeBase;
  50537. this.fixup = fixup;
  50538. this._outputSurface = [];
  50539. this._numMipLevels = 0;
  50540. }
  50541. /**
  50542. * Launches the filter process and return the result.
  50543. *
  50544. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50545. */
  50546. PMREMGenerator.prototype.filterCubeMap = function () {
  50547. // Init cubemap processor
  50548. this.init();
  50549. // Filters the cubemap
  50550. this.filterCubeMapMipChain();
  50551. // Returns the filtered mips.
  50552. return this._outputSurface;
  50553. };
  50554. PMREMGenerator.prototype.init = function () {
  50555. var i;
  50556. var j;
  50557. var mipLevelSize;
  50558. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50559. if (this.maxNumMipLevels == 0) {
  50560. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50561. }
  50562. //first miplevel size
  50563. mipLevelSize = this.outputSize;
  50564. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50565. for (j = 0; j < this.maxNumMipLevels; j++) {
  50566. this._outputSurface.length++;
  50567. this._outputSurface[j] = [];
  50568. //Iterate over faces for output images
  50569. for (i = 0; i < 6; i++) {
  50570. this._outputSurface[j].length++;
  50571. // Initializes a new array for the output.
  50572. if (this.isFloat) {
  50573. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50574. }
  50575. else {
  50576. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50577. }
  50578. }
  50579. //next mip level is half size
  50580. mipLevelSize >>= 1;
  50581. this._numMipLevels++;
  50582. //terminate if mip chain becomes too small
  50583. if (mipLevelSize == 0) {
  50584. this.maxNumMipLevels = j;
  50585. return;
  50586. }
  50587. }
  50588. };
  50589. //--------------------------------------------------------------------------------------
  50590. //Cube map filtering and mip chain generation.
  50591. // the cube map filtereing is specified using a number of parameters:
  50592. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50593. // indicates the region of the hemisphere to filter over for each tap.
  50594. //
  50595. // Note that the top mip level is also a filtered version of the original input images
  50596. // as well in order to create mip chains for diffuse environment illumination.
  50597. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50598. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50599. //
  50600. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50601. // is a_InitialMipAngle
  50602. //
  50603. // The angle for the subsequent levels of the mip chain are specified by their parents
  50604. // filtering angle and a per-level scale and bias
  50605. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50606. //
  50607. //--------------------------------------------------------------------------------------
  50608. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50609. // First, take count of the lighting model to modify SpecularPower
  50610. // 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;
  50611. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50612. //Cone angle start (for generating subsequent mip levels)
  50613. var currentSpecularPower = this.specularPower;
  50614. //Build filter lookup tables based on the source miplevel size
  50615. this.precomputeFilterLookupTables(this.inputSize);
  50616. // Note that we need to filter the first level before generating mipmap
  50617. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50618. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50619. // TODO : Write a function to copy and scale the base mipmap in output
  50620. // I am just lazy here and just put a high specular power value, and do some if.
  50621. if (this.excludeBase && (levelIndex == 0)) {
  50622. // 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).
  50623. currentSpecularPower = 100000.0;
  50624. }
  50625. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50626. var srcCubeImage = this.input;
  50627. var dstCubeImage = this._outputSurface[levelIndex];
  50628. var dstSize = this.outputSize >> levelIndex;
  50629. // Compute required angle.
  50630. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50631. // filter cube surfaces
  50632. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50633. // fix seams
  50634. if (this.fixup) {
  50635. this.fixupCubeEdges(dstCubeImage, dstSize);
  50636. }
  50637. // Decrease the specular power to generate the mipmap chain
  50638. // TODO : Use another method for Exclude (see first comment at start of the function
  50639. if (this.excludeBase && (levelIndex == 0)) {
  50640. currentSpecularPower = this.specularPower;
  50641. }
  50642. currentSpecularPower *= this.cosinePowerDropPerMip;
  50643. }
  50644. };
  50645. //--------------------------------------------------------------------------------------
  50646. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50647. // It allow to optimize the texel to access base on the specular power.
  50648. //--------------------------------------------------------------------------------------
  50649. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50650. // We want to find the alpha such that:
  50651. // cos(alpha)^cosinePower = epsilon
  50652. // That's: acos(epsilon^(1/cosinePower))
  50653. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50654. var angle = 180.0;
  50655. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50656. angle *= 180.0 / Math.PI; // Convert to degree
  50657. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50658. return angle;
  50659. };
  50660. //--------------------------------------------------------------------------------------
  50661. //Builds the following lookup tables prior to filtering:
  50662. // -normalizer cube map
  50663. // -tap weight lookup table
  50664. //
  50665. //--------------------------------------------------------------------------------------
  50666. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50667. var srcTexelAngle;
  50668. var iCubeFace;
  50669. //clear pre-existing normalizer cube map
  50670. this._normCubeMap = [];
  50671. //Normalized vectors per cubeface and per-texel solid angle
  50672. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50673. };
  50674. //--------------------------------------------------------------------------------------
  50675. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50676. //
  50677. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50678. //
  50679. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50680. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50681. // below
  50682. //--------------------------------------------------------------------------------------
  50683. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50684. var iCubeFace;
  50685. var u;
  50686. var v;
  50687. //iterate over cube faces
  50688. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50689. //First three channels for norm cube, and last channel for solid angle
  50690. this._normCubeMap.push(new Float32Array(size * size * 4));
  50691. //fast texture walk, build normalizer cube map
  50692. var facesData = this.input[iCubeFace];
  50693. for (v = 0; v < size; v++) {
  50694. for (u = 0; u < size; u++) {
  50695. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50696. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50697. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50698. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50699. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50700. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50701. }
  50702. }
  50703. }
  50704. };
  50705. //--------------------------------------------------------------------------------------
  50706. // Convert cubemap face texel coordinates and face idx to 3D vector
  50707. // note the U and V coords are integer coords and range from 0 to size-1
  50708. // this routine can be used to generate a normalizer cube map
  50709. //--------------------------------------------------------------------------------------
  50710. // SL BEGIN
  50711. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50712. var nvcU;
  50713. var nvcV;
  50714. var tempVec;
  50715. // Change from original AMD code
  50716. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50717. // + 0.5f is for texel center addressing
  50718. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50719. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50720. // warp fixup
  50721. if (fixup && size > 1) {
  50722. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50723. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50724. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50725. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50726. }
  50727. // Get current vector
  50728. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50729. // U contribution
  50730. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50731. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50732. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50733. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50734. // V contribution and Sum
  50735. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50736. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50737. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50738. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50739. //add face axis
  50740. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50741. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50742. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50743. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50744. //normalize vector
  50745. PMREMGenerator._vectorTemp.normalize();
  50746. return PMREMGenerator._vectorTemp;
  50747. };
  50748. //--------------------------------------------------------------------------------------
  50749. // Convert 3D vector to cubemap face texel coordinates and face idx
  50750. // note the U and V coords are integer coords and range from 0 to size-1
  50751. // this routine can be used to generate a normalizer cube map
  50752. //
  50753. // returns face IDX and texel coords
  50754. //--------------------------------------------------------------------------------------
  50755. // SL BEGIN
  50756. /*
  50757. Mapping Texture Coordinates to Cube Map Faces
  50758. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50759. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50760. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50761. map arrangement in Pixar's RenderMan package.
  50762. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50763. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50764. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50765. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50766. the major axis direction). The target column in the table below explains how the major axis direction
  50767. maps to the 2D image of a particular cube map target.
  50768. major axis
  50769. direction target sc tc ma
  50770. ---------- --------------------------------- --- --- ---
  50771. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50772. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50773. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50774. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50775. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50776. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50777. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50778. an updated (s,t) is calculated as follows
  50779. s = ( sc/|ma| + 1 ) / 2
  50780. t = ( tc/|ma| + 1 ) / 2
  50781. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50782. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50783. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50784. */
  50785. // Note this method return U and V in range from 0 to size-1
  50786. // SL END
  50787. // Store the information in vector3 for convenience (faceindex, u, v)
  50788. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50789. var maxCoord;
  50790. var faceIdx;
  50791. //absolute value 3
  50792. var absX = Math.abs(x);
  50793. var absY = Math.abs(y);
  50794. var absZ = Math.abs(z);
  50795. if (absX >= absY && absX >= absZ) {
  50796. maxCoord = absX;
  50797. if (x >= 0) {
  50798. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50799. }
  50800. else {
  50801. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50802. }
  50803. }
  50804. else if (absY >= absX && absY >= absZ) {
  50805. maxCoord = absY;
  50806. if (y >= 0) {
  50807. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50808. }
  50809. else {
  50810. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50811. }
  50812. }
  50813. else {
  50814. maxCoord = absZ;
  50815. if (z >= 0) {
  50816. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50817. }
  50818. else {
  50819. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50820. }
  50821. }
  50822. //divide through by max coord so face vector lies on cube face
  50823. var scale = 1 / maxCoord;
  50824. x *= scale;
  50825. y *= scale;
  50826. z *= scale;
  50827. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50828. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50829. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50830. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50831. // Modify original AMD code to return value from 0 to Size - 1
  50832. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50833. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50834. PMREMGenerator._vectorTemp.x = faceIdx;
  50835. PMREMGenerator._vectorTemp.y = u;
  50836. PMREMGenerator._vectorTemp.z = v;
  50837. return PMREMGenerator._vectorTemp;
  50838. };
  50839. //--------------------------------------------------------------------------------------
  50840. //Original code from Ignacio CastaÒo
  50841. // This formula is from Manne ÷hrstrˆm's thesis.
  50842. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50843. // cube face and return the area of the projection of that portion on the
  50844. // surface of the sphere.
  50845. //--------------------------------------------------------------------------------------
  50846. PMREMGenerator.prototype.areaElement = function (x, y) {
  50847. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50848. };
  50849. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50850. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50851. // (+ 0.5f is for texel center addressing)
  50852. u = (2.0 * (u + 0.5) / size) - 1.0;
  50853. v = (2.0 * (v + 0.5) / size) - 1.0;
  50854. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50855. var invResolution = 1.0 / size;
  50856. // U and V are the -1..1 texture coordinate on the current face.
  50857. // Get projected area for this texel
  50858. var x0 = u - invResolution;
  50859. var y0 = v - invResolution;
  50860. var x1 = u + invResolution;
  50861. var y1 = v + invResolution;
  50862. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50863. return solidAngle;
  50864. };
  50865. //--------------------------------------------------------------------------------------
  50866. //The key to the speed of these filtering routines is to quickly define a per-face
  50867. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50868. // Later these pixels are selectively processed based on their dot products to see if
  50869. // they reside within the filtering cone.
  50870. //
  50871. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50872. // of the number of texels needed to be covered in width and height order to filter the
  50873. // region. the bounding box for the center taps face is defined first, and if the
  50874. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50875. // defined next
  50876. //--------------------------------------------------------------------------------------
  50877. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50878. // note that pixels within these regions may be rejected
  50879. // based on the anlge
  50880. var iCubeFace;
  50881. var u;
  50882. var v;
  50883. // bounding box per face to specify region to process
  50884. var filterExtents = [];
  50885. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50886. filterExtents.push(new CMGBoundinBox());
  50887. }
  50888. // min angle a src texel can cover (in degrees)
  50889. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50890. // angle about center tap to define filter cone
  50891. // filter angle is 1/2 the cone angle
  50892. var filterAngle = filterConeAngle / 2.0;
  50893. //ensure filter angle is larger than a texel
  50894. if (filterAngle < srcTexelAngle) {
  50895. filterAngle = srcTexelAngle;
  50896. }
  50897. //ensure filter cone is always smaller than the hemisphere
  50898. if (filterAngle > 90.0) {
  50899. filterAngle = 90.0;
  50900. }
  50901. // the maximum number of texels in 1D the filter cone angle will cover
  50902. // used to determine bounding box size for filter extents
  50903. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50904. // ensure conservative region always covers at least one texel
  50905. if (filterSize < 1) {
  50906. filterSize = 1;
  50907. }
  50908. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50909. // reside within the cone angle
  50910. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50911. // process required faces
  50912. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50913. //iterate over dst cube map face texel
  50914. for (v = 0; v < dstSize; v++) {
  50915. for (u = 0; u < dstSize; u++) {
  50916. //get center tap direction
  50917. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50918. //clear old per-face filter extents
  50919. this.clearFilterExtents(filterExtents);
  50920. //define per-face filter extents
  50921. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50922. //perform filtering of src faces using filter extents
  50923. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50924. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50925. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50926. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50927. }
  50928. }
  50929. }
  50930. };
  50931. //--------------------------------------------------------------------------------------
  50932. //Clear filter extents for the 6 cube map faces
  50933. //--------------------------------------------------------------------------------------
  50934. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50935. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50936. filterExtents[iCubeFaces].clear();
  50937. }
  50938. };
  50939. //--------------------------------------------------------------------------------------
  50940. //Define per-face bounding box filter extents
  50941. //
  50942. // These define conservative texel regions in each of the faces the filter can possibly
  50943. // process. When the pixels in the regions are actually processed, the dot product
  50944. // between the tap vector and the center tap vector is used to determine the weight of
  50945. // the tap and whether or not the tap is within the cone.
  50946. //
  50947. //--------------------------------------------------------------------------------------
  50948. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50949. //neighboring face and bleed over amount, and width of BBOX for
  50950. // left, right, top, and bottom edges of this face
  50951. var bleedOverAmount = [0, 0, 0, 0];
  50952. var bleedOverBBoxMin = [0, 0, 0, 0];
  50953. var bleedOverBBoxMax = [0, 0, 0, 0];
  50954. var neighborFace;
  50955. var neighborEdge;
  50956. var oppositeFaceIdx;
  50957. //get face idx, and u, v info from center tap dir
  50958. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50959. var faceIdx = result.x;
  50960. var u = result.y;
  50961. var v = result.z;
  50962. //define bbox size within face
  50963. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50964. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50965. filterExtents[faceIdx].clampMin(0, 0, 0);
  50966. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50967. //u and v extent in face corresponding to center tap
  50968. var minU = filterExtents[faceIdx].min.x;
  50969. var minV = filterExtents[faceIdx].min.y;
  50970. var maxU = filterExtents[faceIdx].max.x;
  50971. var maxV = filterExtents[faceIdx].max.y;
  50972. //bleed over amounts for face across u=0 edge (left)
  50973. bleedOverAmount[0] = (bboxSize - u);
  50974. bleedOverBBoxMin[0] = minV;
  50975. bleedOverBBoxMax[0] = maxV;
  50976. //bleed over amounts for face across u=1 edge (right)
  50977. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50978. bleedOverBBoxMin[1] = minV;
  50979. bleedOverBBoxMax[1] = maxV;
  50980. //bleed over to face across v=0 edge (up)
  50981. bleedOverAmount[2] = (bboxSize - v);
  50982. bleedOverBBoxMin[2] = minU;
  50983. bleedOverBBoxMax[2] = maxU;
  50984. //bleed over to face across v=1 edge (down)
  50985. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50986. bleedOverBBoxMin[3] = minU;
  50987. bleedOverBBoxMax[3] = maxU;
  50988. //compute bleed over regions in neighboring faces
  50989. for (var i = 0; i < 4; i++) {
  50990. if (bleedOverAmount[i] > 0) {
  50991. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50992. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50993. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50994. // be flipped: the cases are
  50995. // if a left edge mates with a left or bottom edge on the neighbor
  50996. // if a top edge mates with a top or right edge on the neighbor
  50997. // if a right edge mates with a right or top edge on the neighbor
  50998. // if a bottom edge mates with a bottom or left edge on the neighbor
  50999. //Seeing as the edges are enumerated as follows
  51000. // left =0
  51001. // right =1
  51002. // top =2
  51003. // bottom =3
  51004. //
  51005. // so if the edge enums are the same, or the sum of the enums == 3,
  51006. // the bbox needs to be flipped
  51007. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51008. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51009. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51010. }
  51011. //The way the bounding box is extended onto the neighboring face
  51012. // depends on which edge of neighboring face abuts with this one
  51013. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51014. case PMREMGenerator.CP_EDGE_LEFT:
  51015. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51016. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51017. break;
  51018. case PMREMGenerator.CP_EDGE_RIGHT:
  51019. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51020. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51021. break;
  51022. case PMREMGenerator.CP_EDGE_TOP:
  51023. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51024. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51025. break;
  51026. case PMREMGenerator.CP_EDGE_BOTTOM:
  51027. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51028. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51029. break;
  51030. }
  51031. //clamp filter extents in non-center tap faces to remain within surface
  51032. filterExtents[neighborFace].clampMin(0, 0, 0);
  51033. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51034. }
  51035. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51036. // from the center tap face, then process the opposite face entirely for now.
  51037. //Note that the cases in which this happens, what usually happens is that
  51038. // more than one edge bleeds onto the opposite face, and the bounding box
  51039. // encompasses the entire cube map face.
  51040. if (bleedOverAmount[i] > srcSize) {
  51041. //determine opposite face
  51042. switch (faceIdx) {
  51043. case PMREMGenerator.CP_FACE_X_POS:
  51044. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51045. break;
  51046. case PMREMGenerator.CP_FACE_X_NEG:
  51047. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51048. break;
  51049. case PMREMGenerator.CP_FACE_Y_POS:
  51050. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51051. break;
  51052. case PMREMGenerator.CP_FACE_Y_NEG:
  51053. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51054. break;
  51055. case PMREMGenerator.CP_FACE_Z_POS:
  51056. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51057. break;
  51058. case PMREMGenerator.CP_FACE_Z_NEG:
  51059. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51060. break;
  51061. default:
  51062. break;
  51063. }
  51064. //just encompass entire face for now
  51065. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51066. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51067. }
  51068. }
  51069. };
  51070. //--------------------------------------------------------------------------------------
  51071. //ProcessFilterExtents
  51072. // Process bounding box in each cube face
  51073. //
  51074. //--------------------------------------------------------------------------------------
  51075. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51076. //accumulators are 64-bit floats in order to have the precision needed
  51077. // over a summation of a large number of pixels
  51078. var dstAccum = [0, 0, 0, 0];
  51079. var weightAccum = 0;
  51080. var k = 0;
  51081. var nSrcChannels = this.numChannels;
  51082. // norm cube map and srcCubeMap have same face width
  51083. var faceWidth = srcSize;
  51084. //amount to add to pointer to move to next scanline in images
  51085. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51086. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51087. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51088. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51089. // iterate over cubefaces
  51090. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51091. //if bbox is non empty
  51092. if (!filterExtents[iFaceIdx].empty()) {
  51093. var uStart = filterExtents[iFaceIdx].min.x;
  51094. var vStart = filterExtents[iFaceIdx].min.y;
  51095. var uEnd = filterExtents[iFaceIdx].max.x;
  51096. var vEnd = filterExtents[iFaceIdx].max.y;
  51097. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51098. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51099. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51100. for (var v = vStart; v <= vEnd; v++) {
  51101. var normCubeRowWalk = 0;
  51102. var srcCubeRowWalk = 0;
  51103. for (var u = uStart; u <= uEnd; u++) {
  51104. //pointer to direction in cube map associated with texel
  51105. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51106. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51107. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51108. //check dot product to see if texel is within cone
  51109. var tapDotProd = texelVectX * centerTapDir.x +
  51110. texelVectY * centerTapDir.y +
  51111. texelVectZ * centerTapDir.z;
  51112. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51113. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51114. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51115. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51116. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51117. // so just adding one to specularpower do the trick.
  51118. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51119. //iterate over channels
  51120. for (k = 0; k < nSrcChannels; k++) {
  51121. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51122. srcCubeRowWalk++;
  51123. }
  51124. weightAccum += weight; //accumulate weight
  51125. }
  51126. else {
  51127. //step across source pixel
  51128. srcCubeRowWalk += nSrcChannels;
  51129. }
  51130. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51131. }
  51132. startIndexNormCubeMap += normCubePitch;
  51133. startIndexSrcCubeMap += srcCubePitch;
  51134. }
  51135. }
  51136. }
  51137. //divide through by weights if weight is non zero
  51138. if (weightAccum != 0.0) {
  51139. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51140. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51141. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51142. if (this.numChannels > 3) {
  51143. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51144. }
  51145. }
  51146. else {
  51147. // otherwise sample nearest
  51148. // get face idx and u, v texel coordinate in face
  51149. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51150. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51151. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51152. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51153. if (this.numChannels > 3) {
  51154. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51155. }
  51156. }
  51157. return PMREMGenerator._vectorTemp;
  51158. };
  51159. //--------------------------------------------------------------------------------------
  51160. // Fixup cube edges
  51161. //
  51162. // average texels on cube map faces across the edges
  51163. // WARP/BENT Method Only.
  51164. //--------------------------------------------------------------------------------------
  51165. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51166. var k;
  51167. var j;
  51168. var i;
  51169. var iFace;
  51170. var iCorner = 0;
  51171. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51172. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51173. // note that if functionality to filter across the three texels for each corner, then
  51174. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51175. var cornerPtr = [
  51176. [[], [], []],
  51177. [[], [], []],
  51178. [[], [], []],
  51179. [[], [], []],
  51180. [[], [], []],
  51181. [[], [], []],
  51182. [[], [], []],
  51183. [[], [], []]
  51184. ];
  51185. //if there is no fixup, or fixup width = 0, do nothing
  51186. if (cubeMapSize < 1) {
  51187. return;
  51188. }
  51189. //special case 1x1 cubemap, average face colors
  51190. if (cubeMapSize == 1) {
  51191. //iterate over channels
  51192. for (k = 0; k < this.numChannels; k++) {
  51193. var accum = 0.0;
  51194. //iterate over faces to accumulate face colors
  51195. for (iFace = 0; iFace < 6; iFace++) {
  51196. accum += cubeMap[iFace][k];
  51197. }
  51198. //compute average over 6 face colors
  51199. accum /= 6.0;
  51200. //iterate over faces to distribute face colors
  51201. for (iFace = 0; iFace < 6; iFace++) {
  51202. cubeMap[iFace][k] = accum;
  51203. }
  51204. }
  51205. return;
  51206. }
  51207. //iterate over faces to collect list of corner texel pointers
  51208. for (iFace = 0; iFace < 6; iFace++) {
  51209. //the 4 corner pointers for this face
  51210. faceCornerStartIndicies[0] = [iFace, 0];
  51211. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51212. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51213. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51214. //iterate over face corners to collect cube corner pointers
  51215. for (iCorner = 0; iCorner < 4; iCorner++) {
  51216. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51217. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51218. cornerNumPtrs[corner]++;
  51219. }
  51220. }
  51221. //iterate over corners to average across corner tap values
  51222. for (iCorner = 0; iCorner < 8; iCorner++) {
  51223. for (k = 0; k < this.numChannels; k++) {
  51224. var cornerTapAccum = 0.0;
  51225. //iterate over corner texels and average results
  51226. for (i = 0; i < 3; i++) {
  51227. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51228. }
  51229. //divide by 3 to compute average of corner tap values
  51230. cornerTapAccum *= (1.0 / 3.0);
  51231. //iterate over corner texels and average results
  51232. for (i = 0; i < 3; i++) {
  51233. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51234. }
  51235. }
  51236. }
  51237. //iterate over the twelve edges of the cube to average across edges
  51238. for (i = 0; i < 12; i++) {
  51239. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51240. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51241. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51242. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51243. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51244. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51245. var edgeWalk = 0;
  51246. var neighborEdgeWalk = 0;
  51247. //Determine walking pointers based on edge type
  51248. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51249. switch (edge) {
  51250. case PMREMGenerator.CP_EDGE_LEFT:
  51251. // no change to faceEdgeStartPtr
  51252. edgeWalk = this.numChannels * cubeMapSize;
  51253. break;
  51254. case PMREMGenerator.CP_EDGE_RIGHT:
  51255. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51256. edgeWalk = this.numChannels * cubeMapSize;
  51257. break;
  51258. case PMREMGenerator.CP_EDGE_TOP:
  51259. // no change to faceEdgeStartPtr
  51260. edgeWalk = this.numChannels;
  51261. break;
  51262. case PMREMGenerator.CP_EDGE_BOTTOM:
  51263. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51264. edgeWalk = this.numChannels;
  51265. break;
  51266. }
  51267. //For certain types of edge abutments, the neighbor edge walk needs to
  51268. // be flipped: the cases are
  51269. // if a left edge mates with a left or bottom edge on the neighbor
  51270. // if a top edge mates with a top or right edge on the neighbor
  51271. // if a right edge mates with a right or top edge on the neighbor
  51272. // if a bottom edge mates with a bottom or left edge on the neighbor
  51273. //Seeing as the edges are enumerated as follows
  51274. // left =0
  51275. // right =1
  51276. // top =2
  51277. // bottom =3
  51278. //
  51279. //If the edge enums are the same, or the sum of the enums == 3,
  51280. // the neighbor edge walk needs to be flipped
  51281. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51282. switch (neighborEdge) {
  51283. case PMREMGenerator.CP_EDGE_LEFT:
  51284. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51285. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51286. break;
  51287. case PMREMGenerator.CP_EDGE_RIGHT:
  51288. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51289. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51290. break;
  51291. case PMREMGenerator.CP_EDGE_TOP:
  51292. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51293. neighborEdgeWalk = -this.numChannels;
  51294. break;
  51295. case PMREMGenerator.CP_EDGE_BOTTOM:
  51296. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51297. neighborEdgeWalk = -this.numChannels;
  51298. break;
  51299. }
  51300. }
  51301. else {
  51302. //swapped direction neighbor edge walk
  51303. switch (neighborEdge) {
  51304. case PMREMGenerator.CP_EDGE_LEFT:
  51305. //no change to neighborEdgeStartPtr for this case since it points
  51306. // to the upper left corner already
  51307. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51308. break;
  51309. case PMREMGenerator.CP_EDGE_RIGHT:
  51310. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51311. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51312. break;
  51313. case PMREMGenerator.CP_EDGE_TOP:
  51314. //no change to neighborEdgeStartPtr for this case since it points
  51315. // to the upper left corner already
  51316. neighborEdgeWalk = this.numChannels;
  51317. break;
  51318. case PMREMGenerator.CP_EDGE_BOTTOM:
  51319. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51320. neighborEdgeWalk = this.numChannels;
  51321. break;
  51322. }
  51323. }
  51324. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51325. //nearby neighborhood
  51326. //step ahead one texel on edge
  51327. edgeStartIndex += edgeWalk;
  51328. neighborEdgeStartIndex += neighborEdgeWalk;
  51329. // note that this loop does not process the corner texels, since they have already been
  51330. // averaged across faces across earlier
  51331. for (j = 1; j < (cubeMapSize - 1); j++) {
  51332. //for each set of taps along edge, average them
  51333. // and rewrite the results into the edges
  51334. for (k = 0; k < this.numChannels; k++) {
  51335. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51336. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51337. //compute average of tap intensity values
  51338. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51339. //propagate average of taps to edge taps
  51340. cubeMap[face][edgeStartIndex + k] = avgTap;
  51341. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51342. }
  51343. edgeStartIndex += edgeWalk;
  51344. neighborEdgeStartIndex += neighborEdgeWalk;
  51345. }
  51346. }
  51347. };
  51348. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51349. PMREMGenerator.CP_UDIR = 0;
  51350. PMREMGenerator.CP_VDIR = 1;
  51351. PMREMGenerator.CP_FACEAXIS = 2;
  51352. //used to index cube faces
  51353. PMREMGenerator.CP_FACE_X_POS = 0;
  51354. PMREMGenerator.CP_FACE_X_NEG = 1;
  51355. PMREMGenerator.CP_FACE_Y_POS = 2;
  51356. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51357. PMREMGenerator.CP_FACE_Z_POS = 4;
  51358. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51359. //used to index image edges
  51360. // NOTE.. the actual number corresponding to the edge is important
  51361. // do not change these, or the code will break
  51362. //
  51363. // CP_EDGE_LEFT is u = 0
  51364. // CP_EDGE_RIGHT is u = width-1
  51365. // CP_EDGE_TOP is v = 0
  51366. // CP_EDGE_BOTTOM is v = height-1
  51367. PMREMGenerator.CP_EDGE_LEFT = 0;
  51368. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51369. PMREMGenerator.CP_EDGE_TOP = 2;
  51370. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51371. //corners of CUBE map (P or N specifys if it corresponds to the
  51372. // positive or negative direction each of X, Y, and Z
  51373. PMREMGenerator.CP_CORNER_NNN = 0;
  51374. PMREMGenerator.CP_CORNER_NNP = 1;
  51375. PMREMGenerator.CP_CORNER_NPN = 2;
  51376. PMREMGenerator.CP_CORNER_NPP = 3;
  51377. PMREMGenerator.CP_CORNER_PNN = 4;
  51378. PMREMGenerator.CP_CORNER_PNP = 5;
  51379. PMREMGenerator.CP_CORNER_PPN = 6;
  51380. PMREMGenerator.CP_CORNER_PPP = 7;
  51381. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51382. //3x2 matrices that map cube map indexing vectors in 3d
  51383. // (after face selection and divide through by the
  51384. // _ABSOLUTE VALUE_ of the max coord)
  51385. // into NVC space
  51386. //Note this currently assumes the D3D cube face ordering and orientation
  51387. PMREMGenerator._sgFace2DMapping = [
  51388. //XPOS face
  51389. [[0, 0, -1],
  51390. [0, -1, 0],
  51391. [1, 0, 0]],
  51392. //XNEG face
  51393. [[0, 0, 1],
  51394. [0, -1, 0],
  51395. [-1, 0, 0]],
  51396. //YPOS face
  51397. [[1, 0, 0],
  51398. [0, 0, 1],
  51399. [0, 1, 0]],
  51400. //YNEG face
  51401. [[1, 0, 0],
  51402. [0, 0, -1],
  51403. [0, -1, 0]],
  51404. //ZPOS face
  51405. [[1, 0, 0],
  51406. [0, -1, 0],
  51407. [0, 0, 1]],
  51408. //ZNEG face
  51409. [[-1, 0, 0],
  51410. [0, -1, 0],
  51411. [0, 0, -1]],
  51412. ];
  51413. //------------------------------------------------------------------------------
  51414. // D3D cube map face specification
  51415. // mapping from 3D x,y,z cube map lookup coordinates
  51416. // to 2D within face u,v coordinates
  51417. //
  51418. // --------------------> U direction
  51419. // | (within-face texture space)
  51420. // | _____
  51421. // | | |
  51422. // | | +Y |
  51423. // | _____|_____|_____ _____
  51424. // | | | | | |
  51425. // | | -X | +Z | +X | -Z |
  51426. // | |_____|_____|_____|_____|
  51427. // | | |
  51428. // | | -Y |
  51429. // | |_____|
  51430. // |
  51431. // v V direction
  51432. // (within-face texture space)
  51433. //------------------------------------------------------------------------------
  51434. //Information about neighbors and how texture coorrdinates change across faces
  51435. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51436. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51437. //Note this currently assumes the D3D cube face ordering and orientation
  51438. PMREMGenerator._sgCubeNgh = [
  51439. //XPOS face
  51440. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51441. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51442. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51443. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51444. //XNEG face
  51445. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51446. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51447. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51448. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51449. //YPOS face
  51450. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51451. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51452. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51453. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51454. //YNEG face
  51455. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51456. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51457. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51458. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51459. //ZPOS face
  51460. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51461. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51462. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51463. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51464. //ZNEG face
  51465. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51466. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51467. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51468. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51469. ];
  51470. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51471. // this table is used to average over the edges.
  51472. PMREMGenerator._sgCubeEdgeList = [
  51473. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51474. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51475. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51476. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51477. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51478. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51479. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51480. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51481. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51482. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51483. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51484. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51485. ];
  51486. //Information about which of the 8 cube corners are correspond to the
  51487. // the 4 corners in each cube face
  51488. // the order is upper left, upper right, lower left, lower right
  51489. PMREMGenerator._sgCubeCornerList = [
  51490. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51491. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51492. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51493. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51494. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51495. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51496. ];
  51497. return PMREMGenerator;
  51498. })();
  51499. Internals.PMREMGenerator = PMREMGenerator;
  51500. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51501. })(BABYLON || (BABYLON = {}));
  51502. var BABYLON;
  51503. (function (BABYLON) {
  51504. /**
  51505. * This represents a texture coming from an HDR input.
  51506. *
  51507. * The only supported format is currently panorama picture stored in RGBE format.
  51508. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51509. */
  51510. var HDRCubeTexture = (function (_super) {
  51511. __extends(HDRCubeTexture, _super);
  51512. /**
  51513. * Instantiates an HDRTexture from the following parameters.
  51514. *
  51515. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51516. * @param scene The scene the texture will be used in
  51517. * @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.
  51518. * @param noMipmap Forces to not generate the mipmap if true
  51519. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51520. * @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)
  51521. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51522. */
  51523. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  51524. if (noMipmap === void 0) { noMipmap = false; }
  51525. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51526. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51527. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51528. _super.call(this, scene);
  51529. this._useInGammaSpace = false;
  51530. this._generateHarmonics = true;
  51531. this._isBABYLONPreprocessed = false;
  51532. /**
  51533. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51534. */
  51535. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51536. /**
  51537. * The spherical polynomial data extracted from the texture.
  51538. */
  51539. this.sphericalPolynomial = null;
  51540. /**
  51541. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51542. * This is usefull at run time to apply the good shader.
  51543. */
  51544. this.isPMREM = false;
  51545. if (!url) {
  51546. return;
  51547. }
  51548. this.name = url;
  51549. this.url = url;
  51550. this.hasAlpha = false;
  51551. this.isCube = true;
  51552. this._textureMatrix = BABYLON.Matrix.Identity();
  51553. if (size) {
  51554. this._isBABYLONPreprocessed = false;
  51555. this._noMipmap = noMipmap;
  51556. this._size = size;
  51557. this._useInGammaSpace = useInGammaSpace;
  51558. this._usePMREMGenerator = usePMREMGenerator &&
  51559. scene.getEngine().getCaps().textureLOD &&
  51560. this.getScene().getEngine().getCaps().textureFloat &&
  51561. !this._useInGammaSpace;
  51562. }
  51563. else {
  51564. this._isBABYLONPreprocessed = true;
  51565. this._noMipmap = false;
  51566. this._useInGammaSpace = false;
  51567. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51568. this.getScene().getEngine().getCaps().textureFloat &&
  51569. !this._useInGammaSpace;
  51570. }
  51571. this.isPMREM = this._usePMREMGenerator;
  51572. this._texture = this._getFromCache(url, this._noMipmap);
  51573. if (!this._texture) {
  51574. if (!scene.useDelayedTextureLoading) {
  51575. this.loadTexture();
  51576. }
  51577. else {
  51578. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51579. }
  51580. }
  51581. }
  51582. /**
  51583. * Occurs when the file is a preprocessed .babylon.hdr file.
  51584. */
  51585. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51586. var _this = this;
  51587. var mipLevels = 0;
  51588. var floatArrayView = null;
  51589. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51590. var mips = [];
  51591. var startIndex = 30;
  51592. for (var level = 0; level < mipLevels; level++) {
  51593. mips.push([]);
  51594. // Fill each pixel of the mip level.
  51595. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51596. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51597. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51598. mips[level].push(faceData);
  51599. startIndex += faceSize;
  51600. }
  51601. }
  51602. return mips;
  51603. } : null;
  51604. var callback = function (buffer) {
  51605. // Create Native Array Views
  51606. var intArrayView = new Int32Array(buffer);
  51607. floatArrayView = new Float32Array(buffer);
  51608. // Fill header.
  51609. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51610. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51611. // Update Texture Information.
  51612. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51613. // Fill polynomial information.
  51614. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51615. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51616. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51617. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51618. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51619. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51620. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51621. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51622. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51623. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51624. // Fill pixel data.
  51625. mipLevels = intArrayView[29]; // Number of mip levels.
  51626. var startIndex = 30;
  51627. var data = [];
  51628. var faceSize = Math.pow(_this._size, 2) * 3;
  51629. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51630. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51631. startIndex += faceSize;
  51632. }
  51633. var results = [];
  51634. var byteArray = null;
  51635. // Push each faces.
  51636. for (var k = 0; k < 6; k++) {
  51637. var dataFace = null;
  51638. // If special cases.
  51639. if (!mipmapGenerator) {
  51640. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51641. dataFace = data[j];
  51642. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51643. // 3 channels of 1 bytes per pixel in bytes.
  51644. var byteBuffer = new ArrayBuffer(faceSize);
  51645. byteArray = new Uint8Array(byteBuffer);
  51646. }
  51647. for (var i = 0; i < _this._size * _this._size; i++) {
  51648. // Put in gamma space if requested.
  51649. if (_this._useInGammaSpace) {
  51650. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51651. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51652. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51653. }
  51654. // Convert to int texture for fallback.
  51655. if (byteArray) {
  51656. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51657. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51658. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51659. // May use luminance instead if the result is not accurate.
  51660. var max = Math.max(Math.max(r, g), b);
  51661. if (max > 255) {
  51662. var scale = 255 / max;
  51663. r *= scale;
  51664. g *= scale;
  51665. b *= scale;
  51666. }
  51667. byteArray[(i * 3) + 0] = r;
  51668. byteArray[(i * 3) + 1] = g;
  51669. byteArray[(i * 3) + 2] = b;
  51670. }
  51671. }
  51672. }
  51673. else {
  51674. dataFace = data[k];
  51675. }
  51676. // Fill the array accordingly.
  51677. if (byteArray) {
  51678. results.push(byteArray);
  51679. }
  51680. else {
  51681. results.push(dataFace);
  51682. }
  51683. }
  51684. return results;
  51685. };
  51686. 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);
  51687. };
  51688. /**
  51689. * Occurs when the file is raw .hdr file.
  51690. */
  51691. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51692. var _this = this;
  51693. var callback = function (buffer) {
  51694. // Extract the raw linear data.
  51695. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51696. // Generate harmonics if needed.
  51697. if (_this._generateHarmonics) {
  51698. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51699. }
  51700. var results = [];
  51701. var byteArray = null;
  51702. // Push each faces.
  51703. for (var j = 0; j < 6; j++) {
  51704. // Create uintarray fallback.
  51705. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51706. // 3 channels of 1 bytes per pixel in bytes.
  51707. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51708. byteArray = new Uint8Array(byteBuffer);
  51709. }
  51710. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51711. // If special cases.
  51712. if (_this._useInGammaSpace || byteArray) {
  51713. for (var i = 0; i < _this._size * _this._size; i++) {
  51714. // Put in gamma space if requested.
  51715. if (_this._useInGammaSpace) {
  51716. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51717. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51718. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51719. }
  51720. // Convert to int texture for fallback.
  51721. if (byteArray) {
  51722. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51723. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51724. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51725. // May use luminance instead if the result is not accurate.
  51726. var max = Math.max(Math.max(r, g), b);
  51727. if (max > 255) {
  51728. var scale = 255 / max;
  51729. r *= scale;
  51730. g *= scale;
  51731. b *= scale;
  51732. }
  51733. byteArray[(i * 3) + 0] = r;
  51734. byteArray[(i * 3) + 1] = g;
  51735. byteArray[(i * 3) + 2] = b;
  51736. }
  51737. }
  51738. }
  51739. if (byteArray) {
  51740. results.push(byteArray);
  51741. }
  51742. else {
  51743. results.push(dataFace);
  51744. }
  51745. }
  51746. return results;
  51747. };
  51748. var mipmapGenerator = null;
  51749. if (!this._noMipmap &&
  51750. this._usePMREMGenerator) {
  51751. mipmapGenerator = function (data) {
  51752. // Custom setup of the generator matching with the PBR shader values.
  51753. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51754. return generator.filterCubeMap();
  51755. };
  51756. }
  51757. 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);
  51758. };
  51759. /**
  51760. * Starts the loading process of the texture.
  51761. */
  51762. HDRCubeTexture.prototype.loadTexture = function () {
  51763. if (this._isBABYLONPreprocessed) {
  51764. this.loadBabylonTexture();
  51765. }
  51766. else {
  51767. this.loadHDRTexture();
  51768. }
  51769. };
  51770. HDRCubeTexture.prototype.clone = function () {
  51771. var size = this._isBABYLONPreprocessed ? null : this._size;
  51772. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51773. // Base texture
  51774. newTexture.level = this.level;
  51775. newTexture.wrapU = this.wrapU;
  51776. newTexture.wrapV = this.wrapV;
  51777. newTexture.coordinatesIndex = this.coordinatesIndex;
  51778. newTexture.coordinatesMode = this.coordinatesMode;
  51779. return newTexture;
  51780. };
  51781. // Methods
  51782. HDRCubeTexture.prototype.delayLoad = function () {
  51783. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51784. return;
  51785. }
  51786. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51787. this._texture = this._getFromCache(this.url, this._noMipmap);
  51788. if (!this._texture) {
  51789. this.loadTexture();
  51790. }
  51791. };
  51792. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51793. return this._textureMatrix;
  51794. };
  51795. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51796. var texture = null;
  51797. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51798. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51799. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  51800. texture.name = parsedTexture.name;
  51801. texture.hasAlpha = parsedTexture.hasAlpha;
  51802. texture.level = parsedTexture.level;
  51803. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51804. }
  51805. return texture;
  51806. };
  51807. HDRCubeTexture.prototype.serialize = function () {
  51808. if (!this.name) {
  51809. return null;
  51810. }
  51811. var serializationObject = {};
  51812. serializationObject.name = this.name;
  51813. serializationObject.hasAlpha = this.hasAlpha;
  51814. serializationObject.isCube = true;
  51815. serializationObject.level = this.level;
  51816. serializationObject.size = this._size;
  51817. serializationObject.coordinatesMode = this.coordinatesMode;
  51818. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51819. serializationObject.generateHarmonics = this._generateHarmonics;
  51820. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51821. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51822. return serializationObject;
  51823. };
  51824. /**
  51825. * Saves as a file the data contained in the texture in a binary format.
  51826. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51827. * as the spherical used in the lighting.
  51828. * @param url The HDR file url.
  51829. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51830. * @param onError Method called if any error happens during download.
  51831. * @return The packed binary data.
  51832. */
  51833. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51834. if (onError === void 0) { onError = null; }
  51835. var callback = function (buffer) {
  51836. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51837. // Returns a URL you can use as a href.
  51838. var objUrl = window.URL.createObjectURL(data);
  51839. // Simulates a link to it and click to dowload.
  51840. var a = document.createElement("a");
  51841. document.body.appendChild(a);
  51842. a.style.display = "none";
  51843. a.href = objUrl;
  51844. a.download = "envmap.babylon.hdr";
  51845. a.click();
  51846. };
  51847. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51848. };
  51849. /**
  51850. * Serializes the data contained in the texture in a binary format.
  51851. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51852. * as the spherical used in the lighting.
  51853. * @param url The HDR file url.
  51854. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51855. * @param onError Method called if any error happens during download.
  51856. * @return The packed binary data.
  51857. */
  51858. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51859. if (onError === void 0) { onError = null; }
  51860. // Needs the url tho create the texture.
  51861. if (!url) {
  51862. return null;
  51863. }
  51864. // Check Power of two size.
  51865. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51866. return null;
  51867. }
  51868. var getDataCallback = function (dataBuffer) {
  51869. // Extract the raw linear data.
  51870. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51871. // Generate harmonics if needed.
  51872. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51873. // Generate seamless faces
  51874. var mipGeneratorArray = [];
  51875. // Data are known to be in +X +Y +Z -X -Y -Z
  51876. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51877. mipGeneratorArray.push(cubeData.right); // +X
  51878. mipGeneratorArray.push(cubeData.left); // -X
  51879. mipGeneratorArray.push(cubeData.up); // +Y
  51880. mipGeneratorArray.push(cubeData.down); // -Y
  51881. mipGeneratorArray.push(cubeData.front); // +Z
  51882. mipGeneratorArray.push(cubeData.back); // -Z
  51883. // Custom setup of the generator matching with the PBR shader values.
  51884. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51885. var mippedData = generator.filterCubeMap();
  51886. // Compute required byte length.
  51887. var byteLength = 1 * 4; // Raw Data Version int32.
  51888. byteLength += 4; // CubeMap max mip face size int32.
  51889. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51890. // Add data size.
  51891. byteLength += 4; // Number of mip levels int32.
  51892. for (var level = 0; level < mippedData.length; level++) {
  51893. var mipSize = size >> level;
  51894. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51895. }
  51896. // Prepare binary structure.
  51897. var buffer = new ArrayBuffer(byteLength);
  51898. var intArrayView = new Int32Array(buffer);
  51899. var floatArrayView = new Float32Array(buffer);
  51900. // Fill header.
  51901. intArrayView[0] = 1; // Version 1.
  51902. intArrayView[1] = size; // CubeMap max mip face size.
  51903. // Fill polynomial information.
  51904. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51905. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51906. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51907. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51908. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51909. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51910. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51911. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51912. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51913. // Fill pixel data.
  51914. intArrayView[29] = mippedData.length; // Number of mip levels.
  51915. var startIndex = 30;
  51916. for (var level = 0; level < mippedData.length; level++) {
  51917. // Fill each pixel of the mip level.
  51918. var faceSize = Math.pow(size >> level, 2) * 3;
  51919. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51920. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51921. startIndex += faceSize;
  51922. }
  51923. }
  51924. // Callback.
  51925. callback(buffer);
  51926. };
  51927. // Download and process.
  51928. BABYLON.Tools.LoadFile(url, function (data) {
  51929. getDataCallback(data);
  51930. }, null, null, true, onError);
  51931. };
  51932. HDRCubeTexture._facesMapping = [
  51933. "right",
  51934. "up",
  51935. "front",
  51936. "left",
  51937. "down",
  51938. "back"
  51939. ];
  51940. return HDRCubeTexture;
  51941. })(BABYLON.BaseTexture);
  51942. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51943. })(BABYLON || (BABYLON = {}));
  51944. var BABYLON;
  51945. (function (BABYLON) {
  51946. var Debug;
  51947. (function (Debug) {
  51948. /**
  51949. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  51950. */
  51951. var SkeletonViewer = (function () {
  51952. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  51953. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  51954. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  51955. this.skeleton = skeleton;
  51956. this.mesh = mesh;
  51957. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  51958. this.renderingGroupId = renderingGroupId;
  51959. this.color = BABYLON.Color3.White();
  51960. this._debugLines = [];
  51961. this._isEnabled = false;
  51962. this._scene = scene;
  51963. this.update();
  51964. this._renderFunction = this.update.bind(this);
  51965. }
  51966. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  51967. get: function () {
  51968. return this._isEnabled;
  51969. },
  51970. set: function (value) {
  51971. if (this._isEnabled === value) {
  51972. return;
  51973. }
  51974. this._isEnabled = value;
  51975. if (value) {
  51976. this._scene.registerBeforeRender(this._renderFunction);
  51977. }
  51978. else {
  51979. this._scene.unregisterBeforeRender(this._renderFunction);
  51980. }
  51981. },
  51982. enumerable: true,
  51983. configurable: true
  51984. });
  51985. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  51986. if (x === void 0) { x = 0; }
  51987. if (y === void 0) { y = 0; }
  51988. if (z === void 0) { z = 0; }
  51989. var tmat = BABYLON.Tmp.Matrix[0];
  51990. var parentBone = bone.getParent();
  51991. tmat.copyFrom(bone.getLocalMatrix());
  51992. if (x !== 0 || y !== 0 || z !== 0) {
  51993. var tmat2 = BABYLON.Tmp.Matrix[1];
  51994. BABYLON.Matrix.IdentityToRef(tmat2);
  51995. tmat2.m[12] = x;
  51996. tmat2.m[13] = y;
  51997. tmat2.m[14] = z;
  51998. tmat2.multiplyToRef(tmat, tmat);
  51999. }
  52000. if (parentBone) {
  52001. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  52002. }
  52003. tmat.multiplyToRef(meshMat, tmat);
  52004. position.x = tmat.m[12];
  52005. position.y = tmat.m[13];
  52006. position.z = tmat.m[14];
  52007. };
  52008. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52009. var len = bones.length;
  52010. for (var i = 0; i < len; i++) {
  52011. var bone = bones[i];
  52012. var points = this._debugLines[i];
  52013. if (!points) {
  52014. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52015. this._debugLines[i] = points;
  52016. }
  52017. this._getBonePosition(points[0], bone, meshMat);
  52018. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52019. }
  52020. };
  52021. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52022. var len = bones.length;
  52023. var boneNum = 0;
  52024. for (var i = len - 1; i >= 0; i--) {
  52025. var childBone = bones[i];
  52026. var parentBone = childBone.getParent();
  52027. if (!parentBone) {
  52028. continue;
  52029. }
  52030. var points = this._debugLines[boneNum];
  52031. if (!points) {
  52032. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52033. this._debugLines[boneNum] = points;
  52034. }
  52035. this._getBonePosition(points[0], childBone, meshMat);
  52036. this._getBonePosition(points[1], parentBone, meshMat);
  52037. boneNum++;
  52038. }
  52039. };
  52040. SkeletonViewer.prototype.update = function () {
  52041. if (this.autoUpdateBonesMatrices) {
  52042. this._updateBoneMatrix(this.skeleton.bones[0]);
  52043. }
  52044. if (this.skeleton.bones[0].length === undefined) {
  52045. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52046. }
  52047. else {
  52048. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52049. }
  52050. if (!this._debugMesh) {
  52051. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  52052. this._debugMesh.renderingGroupId = this.renderingGroupId;
  52053. }
  52054. else {
  52055. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  52056. }
  52057. this._debugMesh.color = this.color;
  52058. };
  52059. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  52060. if (bone.getParent()) {
  52061. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  52062. }
  52063. var children = bone.children;
  52064. var len = children.length;
  52065. for (var i = 0; i < len; i++) {
  52066. this._updateBoneMatrix(children[i]);
  52067. }
  52068. };
  52069. SkeletonViewer.prototype.dispose = function () {
  52070. if (this._debugMesh) {
  52071. this.isEnabled = false;
  52072. this._debugMesh.dispose();
  52073. this._debugMesh = null;
  52074. }
  52075. };
  52076. return SkeletonViewer;
  52077. })();
  52078. Debug.SkeletonViewer = SkeletonViewer;
  52079. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52080. })(BABYLON || (BABYLON = {}));
  52081. var BABYLON;
  52082. (function (BABYLON) {
  52083. /**
  52084. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52085. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52086. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  52087. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52088. */
  52089. var ColorCurves = (function () {
  52090. function ColorCurves() {
  52091. this._dirty = true;
  52092. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  52093. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  52094. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52095. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  52096. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52097. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  52098. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  52099. this._globalHue = 30;
  52100. this._globalDensity = 0;
  52101. this._globalSaturation = 0;
  52102. this._globalExposure = 0;
  52103. this._highlightsHue = 30;
  52104. this._highlightsDensity = 0;
  52105. this._highlightsSaturation = 0;
  52106. this._highlightsExposure = 0;
  52107. this._midtonesHue = 30;
  52108. this._midtonesDensity = 0;
  52109. this._midtonesSaturation = 0;
  52110. this._midtonesExposure = 0;
  52111. this._shadowsHue = 30;
  52112. this._shadowsDensity = 0;
  52113. this._shadowsSaturation = 0;
  52114. this._shadowsExposure = 0;
  52115. }
  52116. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  52117. /**
  52118. * Gets the global Hue value.
  52119. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52120. */
  52121. get: function () {
  52122. return this._globalHue;
  52123. },
  52124. /**
  52125. * Sets the global Hue value.
  52126. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52127. */
  52128. set: function (value) {
  52129. this._globalHue = value;
  52130. this._dirty = true;
  52131. },
  52132. enumerable: true,
  52133. configurable: true
  52134. });
  52135. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  52136. /**
  52137. * Gets the global Density value.
  52138. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52139. * Values less than zero provide a filter of opposite hue.
  52140. */
  52141. get: function () {
  52142. return this._globalDensity;
  52143. },
  52144. /**
  52145. * Sets the global Density value.
  52146. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52147. * Values less than zero provide a filter of opposite hue.
  52148. */
  52149. set: function (value) {
  52150. this._globalDensity = value;
  52151. this._dirty = true;
  52152. },
  52153. enumerable: true,
  52154. configurable: true
  52155. });
  52156. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  52157. /**
  52158. * Gets the global Saturation value.
  52159. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52160. */
  52161. get: function () {
  52162. return this._globalSaturation;
  52163. },
  52164. /**
  52165. * Sets the global Saturation value.
  52166. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52167. */
  52168. set: function (value) {
  52169. this._globalSaturation = value;
  52170. this._dirty = true;
  52171. },
  52172. enumerable: true,
  52173. configurable: true
  52174. });
  52175. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  52176. /**
  52177. * Gets the highlights Hue value.
  52178. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52179. */
  52180. get: function () {
  52181. return this._highlightsHue;
  52182. },
  52183. /**
  52184. * Sets the highlights Hue value.
  52185. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52186. */
  52187. set: function (value) {
  52188. this._highlightsHue = value;
  52189. this._dirty = true;
  52190. },
  52191. enumerable: true,
  52192. configurable: true
  52193. });
  52194. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  52195. /**
  52196. * Gets the highlights Density value.
  52197. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52198. * Values less than zero provide a filter of opposite hue.
  52199. */
  52200. get: function () {
  52201. return this._highlightsDensity;
  52202. },
  52203. /**
  52204. * Sets the highlights Density value.
  52205. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52206. * Values less than zero provide a filter of opposite hue.
  52207. */
  52208. set: function (value) {
  52209. this._highlightsDensity = value;
  52210. this._dirty = true;
  52211. },
  52212. enumerable: true,
  52213. configurable: true
  52214. });
  52215. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  52216. /**
  52217. * Gets the highlights Saturation value.
  52218. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52219. */
  52220. get: function () {
  52221. return this._highlightsSaturation;
  52222. },
  52223. /**
  52224. * Sets the highlights Saturation value.
  52225. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52226. */
  52227. set: function (value) {
  52228. this._highlightsSaturation = value;
  52229. this._dirty = true;
  52230. },
  52231. enumerable: true,
  52232. configurable: true
  52233. });
  52234. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  52235. /**
  52236. * Gets the highlights Exposure value.
  52237. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52238. */
  52239. get: function () {
  52240. return this._highlightsExposure;
  52241. },
  52242. /**
  52243. * Sets the highlights Exposure value.
  52244. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52245. */
  52246. set: function (value) {
  52247. this._highlightsExposure = value;
  52248. this._dirty = true;
  52249. },
  52250. enumerable: true,
  52251. configurable: true
  52252. });
  52253. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  52254. /**
  52255. * Gets the midtones Hue value.
  52256. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52257. */
  52258. get: function () {
  52259. return this._midtonesHue;
  52260. },
  52261. /**
  52262. * Sets the midtones Hue value.
  52263. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52264. */
  52265. set: function (value) {
  52266. this._midtonesHue = value;
  52267. this._dirty = true;
  52268. },
  52269. enumerable: true,
  52270. configurable: true
  52271. });
  52272. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52273. /**
  52274. * Gets the midtones Density value.
  52275. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52276. * Values less than zero provide a filter of opposite hue.
  52277. */
  52278. get: function () {
  52279. return this._midtonesDensity;
  52280. },
  52281. /**
  52282. * Sets the midtones Density value.
  52283. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52284. * Values less than zero provide a filter of opposite hue.
  52285. */
  52286. set: function (value) {
  52287. this._midtonesDensity = value;
  52288. this._dirty = true;
  52289. },
  52290. enumerable: true,
  52291. configurable: true
  52292. });
  52293. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52294. /**
  52295. * Gets the midtones Saturation value.
  52296. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52297. */
  52298. get: function () {
  52299. return this._midtonesSaturation;
  52300. },
  52301. /**
  52302. * Sets the midtones Saturation value.
  52303. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52304. */
  52305. set: function (value) {
  52306. this._midtonesSaturation = value;
  52307. this._dirty = true;
  52308. },
  52309. enumerable: true,
  52310. configurable: true
  52311. });
  52312. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52313. /**
  52314. * Gets the midtones Exposure value.
  52315. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52316. */
  52317. get: function () {
  52318. return this._midtonesExposure;
  52319. },
  52320. /**
  52321. * Sets the midtones Exposure value.
  52322. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52323. */
  52324. set: function (value) {
  52325. this._midtonesExposure = value;
  52326. this._dirty = true;
  52327. },
  52328. enumerable: true,
  52329. configurable: true
  52330. });
  52331. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52332. /**
  52333. * Gets the shadows Hue value.
  52334. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52335. */
  52336. get: function () {
  52337. return this._shadowsHue;
  52338. },
  52339. /**
  52340. * Sets the shadows Hue value.
  52341. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52342. */
  52343. set: function (value) {
  52344. this._shadowsHue = value;
  52345. this._dirty = true;
  52346. },
  52347. enumerable: true,
  52348. configurable: true
  52349. });
  52350. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52351. /**
  52352. * Gets the shadows Density value.
  52353. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52354. * Values less than zero provide a filter of opposite hue.
  52355. */
  52356. get: function () {
  52357. return this._shadowsDensity;
  52358. },
  52359. /**
  52360. * Sets the shadows Density value.
  52361. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52362. * Values less than zero provide a filter of opposite hue.
  52363. */
  52364. set: function (value) {
  52365. this._shadowsDensity = value;
  52366. this._dirty = true;
  52367. },
  52368. enumerable: true,
  52369. configurable: true
  52370. });
  52371. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  52372. /**
  52373. * Gets the shadows Saturation value.
  52374. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52375. */
  52376. get: function () {
  52377. return this._shadowsSaturation;
  52378. },
  52379. /**
  52380. * Sets the shadows Saturation value.
  52381. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52382. */
  52383. set: function (value) {
  52384. this._shadowsSaturation = value;
  52385. this._dirty = true;
  52386. },
  52387. enumerable: true,
  52388. configurable: true
  52389. });
  52390. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  52391. /**
  52392. * Gets the shadows Exposure value.
  52393. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52394. */
  52395. get: function () {
  52396. return this._shadowsExposure;
  52397. },
  52398. /**
  52399. * Sets the shadows Exposure value.
  52400. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52401. */
  52402. set: function (value) {
  52403. this._shadowsExposure = value;
  52404. this._dirty = true;
  52405. },
  52406. enumerable: true,
  52407. configurable: true
  52408. });
  52409. /**
  52410. * Binds the color curves to the shader.
  52411. * @param colorCurves The color curve to bind
  52412. * @param effect The effect to bind to
  52413. */
  52414. ColorCurves.Bind = function (colorCurves, effect) {
  52415. if (colorCurves._dirty) {
  52416. colorCurves._dirty = false;
  52417. // Fill in global info.
  52418. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  52419. // Compute highlights info.
  52420. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  52421. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  52422. // Compute midtones info.
  52423. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  52424. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  52425. // Compute shadows info.
  52426. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  52427. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  52428. // Compute deltas (neutral is midtones).
  52429. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  52430. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  52431. }
  52432. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  52433. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  52434. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  52435. };
  52436. /**
  52437. * Prepare the list of uniforms associated with the ColorCurves effects.
  52438. * @param uniformsList The list of uniforms used in the effect
  52439. */
  52440. ColorCurves.PrepareUniforms = function (uniformsList) {
  52441. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  52442. };
  52443. /**
  52444. * Returns color grading data based on a hue, density, saturation and exposure value.
  52445. * @param filterHue The hue of the color filter.
  52446. * @param filterDensity The density of the color filter.
  52447. * @param saturation The saturation.
  52448. * @param exposure The exposure.
  52449. * @param result The result data container.
  52450. */
  52451. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  52452. if (hue == null) {
  52453. return;
  52454. }
  52455. hue = ColorCurves.clamp(hue, 0, 360);
  52456. density = ColorCurves.clamp(density, -100, 100);
  52457. saturation = ColorCurves.clamp(saturation, -100, 100);
  52458. exposure = ColorCurves.clamp(exposure, -100, 100);
  52459. // Remap the slider/config filter density with non-linear mapping and also scale by half
  52460. // so that the maximum filter density is only 50% control. This provides fine control
  52461. // for small values and reasonable range.
  52462. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  52463. density *= 0.5;
  52464. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  52465. if (density < 0) {
  52466. density *= -1;
  52467. hue = (hue + 180) % 360;
  52468. }
  52469. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  52470. result.scaleToRef(2, result);
  52471. result.a = 1 + 0.01 * saturation;
  52472. };
  52473. /**
  52474. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  52475. * @param value The input slider value in range [-100,100].
  52476. * @returns Adjusted value.
  52477. */
  52478. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  52479. value /= 100;
  52480. var x = Math.abs(value);
  52481. x = Math.pow(x, 2);
  52482. if (value < 0) {
  52483. x *= -1;
  52484. }
  52485. x *= 100;
  52486. return x;
  52487. };
  52488. /**
  52489. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  52490. * @param hue The hue (H) input.
  52491. * @param saturation The saturation (S) input.
  52492. * @param brightness The brightness (B) input.
  52493. * @result An RGBA color represented as Vector4.
  52494. */
  52495. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  52496. var h = ColorCurves.clamp(hue, 0, 360);
  52497. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  52498. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  52499. if (s === 0) {
  52500. result.r = v;
  52501. result.g = v;
  52502. result.b = v;
  52503. }
  52504. else {
  52505. // sector 0 to 5
  52506. h /= 60;
  52507. var i = Math.floor(h);
  52508. // fractional part of h
  52509. var f = h - i;
  52510. var p = v * (1 - s);
  52511. var q = v * (1 - s * f);
  52512. var t = v * (1 - s * (1 - f));
  52513. switch (i) {
  52514. case 0:
  52515. result.r = v;
  52516. result.g = t;
  52517. result.b = p;
  52518. break;
  52519. case 1:
  52520. result.r = q;
  52521. result.g = v;
  52522. result.b = p;
  52523. break;
  52524. case 2:
  52525. result.r = p;
  52526. result.g = v;
  52527. result.b = t;
  52528. break;
  52529. case 3:
  52530. result.r = p;
  52531. result.g = q;
  52532. result.b = v;
  52533. break;
  52534. case 4:
  52535. result.r = t;
  52536. result.g = p;
  52537. result.b = v;
  52538. break;
  52539. default:
  52540. result.r = v;
  52541. result.g = p;
  52542. result.b = q;
  52543. break;
  52544. }
  52545. }
  52546. result.a = 1;
  52547. };
  52548. /**
  52549. * Returns a value clamped between min and max
  52550. * @param value The value to clamp
  52551. * @param min The minimum of value
  52552. * @param max The maximum of value
  52553. * @returns The clamped value.
  52554. */
  52555. ColorCurves.clamp = function (value, min, max) {
  52556. return Math.min(Math.max(value, min), max);
  52557. };
  52558. /**
  52559. * Clones the current color curve instance.
  52560. * @return The cloned curves
  52561. */
  52562. ColorCurves.prototype.clone = function () {
  52563. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  52564. };
  52565. /**
  52566. * Serializes the current color curve instance to a json representation.
  52567. * @return a JSON representation
  52568. */
  52569. ColorCurves.prototype.serialize = function () {
  52570. return BABYLON.SerializationHelper.Serialize(this);
  52571. };
  52572. /**
  52573. * Parses the color curve from a json representation.
  52574. * @param source the JSON source to parse
  52575. * @return The parsed curves
  52576. */
  52577. ColorCurves.Parse = function (source) {
  52578. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  52579. };
  52580. __decorate([
  52581. BABYLON.serialize()
  52582. ], ColorCurves.prototype, "_globalHue", void 0);
  52583. __decorate([
  52584. BABYLON.serialize()
  52585. ], ColorCurves.prototype, "_globalDensity", void 0);
  52586. __decorate([
  52587. BABYLON.serialize()
  52588. ], ColorCurves.prototype, "_globalSaturation", void 0);
  52589. __decorate([
  52590. BABYLON.serialize()
  52591. ], ColorCurves.prototype, "_globalExposure", void 0);
  52592. __decorate([
  52593. BABYLON.serialize()
  52594. ], ColorCurves.prototype, "_highlightsHue", void 0);
  52595. __decorate([
  52596. BABYLON.serialize()
  52597. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  52598. __decorate([
  52599. BABYLON.serialize()
  52600. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  52601. __decorate([
  52602. BABYLON.serialize()
  52603. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  52604. __decorate([
  52605. BABYLON.serialize()
  52606. ], ColorCurves.prototype, "_midtonesHue", void 0);
  52607. __decorate([
  52608. BABYLON.serialize()
  52609. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  52610. __decorate([
  52611. BABYLON.serialize()
  52612. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  52613. __decorate([
  52614. BABYLON.serialize()
  52615. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  52616. return ColorCurves;
  52617. })();
  52618. BABYLON.ColorCurves = ColorCurves;
  52619. })(BABYLON || (BABYLON = {}));
  52620. var BABYLON;
  52621. (function (BABYLON) {
  52622. /**
  52623. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52624. * It can help converting any input color in a desired output one. This can then be used to create effects
  52625. * from sepia, black and white to sixties or futuristic rendering...
  52626. *
  52627. * The only supported format is currently 3dl.
  52628. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52629. */
  52630. var ColorGradingTexture = (function (_super) {
  52631. __extends(ColorGradingTexture, _super);
  52632. /**
  52633. * Instantiates a ColorGradingTexture from the following parameters.
  52634. *
  52635. * @param url The location of the color gradind data (currently only supporting 3dl)
  52636. * @param scene The scene the texture will be used in
  52637. */
  52638. function ColorGradingTexture(url, scene) {
  52639. _super.call(this, scene);
  52640. if (!url) {
  52641. return;
  52642. }
  52643. this._textureMatrix = BABYLON.Matrix.Identity();
  52644. this.name = url;
  52645. this.url = url;
  52646. this.hasAlpha = false;
  52647. this.isCube = false;
  52648. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52649. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52650. this.anisotropicFilteringLevel = 1;
  52651. this._texture = this._getFromCache(url, true);
  52652. if (!this._texture) {
  52653. if (!scene.useDelayedTextureLoading) {
  52654. this.loadTexture();
  52655. }
  52656. else {
  52657. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52658. }
  52659. }
  52660. }
  52661. /**
  52662. * Returns the texture matrix used in most of the material.
  52663. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52664. */
  52665. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52666. return this._textureMatrix;
  52667. };
  52668. /**
  52669. * Occurs when the file being loaded is a .3dl LUT file.
  52670. */
  52671. ColorGradingTexture.prototype.load3dlTexture = function () {
  52672. var _this = this;
  52673. var mipLevels = 0;
  52674. var floatArrayView = null;
  52675. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52676. this._texture = texture;
  52677. var callback = function (text) {
  52678. var data;
  52679. var tempData;
  52680. var line;
  52681. var lines = text.split('\n');
  52682. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52683. var maxColor = 0;
  52684. for (var i = 0; i < lines.length; i++) {
  52685. line = lines[i];
  52686. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52687. continue;
  52688. if (line.indexOf('#') === 0)
  52689. continue;
  52690. var words = line.split(" ");
  52691. if (size === 0) {
  52692. // Number of space + one
  52693. size = words.length;
  52694. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52695. tempData = new Float32Array(size * size * size * 4);
  52696. continue;
  52697. }
  52698. if (size != 0) {
  52699. var r = Math.max(parseInt(words[0]), 0);
  52700. var g = Math.max(parseInt(words[1]), 0);
  52701. var b = Math.max(parseInt(words[2]), 0);
  52702. maxColor = Math.max(r, maxColor);
  52703. maxColor = Math.max(g, maxColor);
  52704. maxColor = Math.max(b, maxColor);
  52705. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52706. tempData[pixelStorageIndex + 0] = r;
  52707. tempData[pixelStorageIndex + 1] = g;
  52708. tempData[pixelStorageIndex + 2] = b;
  52709. tempData[pixelStorageIndex + 3] = 0;
  52710. pixelIndexSlice++;
  52711. if (pixelIndexSlice % size == 0) {
  52712. pixelIndexH++;
  52713. pixelIndexSlice = 0;
  52714. if (pixelIndexH % size == 0) {
  52715. pixelIndexW++;
  52716. pixelIndexH = 0;
  52717. }
  52718. }
  52719. }
  52720. }
  52721. for (var i = 0; i < tempData.length; i++) {
  52722. var value = tempData[i];
  52723. data[i] = (value / maxColor * 255);
  52724. }
  52725. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52726. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52727. };
  52728. BABYLON.Tools.LoadFile(this.url, callback);
  52729. return this._texture;
  52730. };
  52731. /**
  52732. * Starts the loading process of the texture.
  52733. */
  52734. ColorGradingTexture.prototype.loadTexture = function () {
  52735. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52736. this.load3dlTexture();
  52737. }
  52738. };
  52739. /**
  52740. * Clones the color gradind texture.
  52741. */
  52742. ColorGradingTexture.prototype.clone = function () {
  52743. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52744. // Base texture
  52745. newTexture.level = this.level;
  52746. return newTexture;
  52747. };
  52748. /**
  52749. * Called during delayed load for textures.
  52750. */
  52751. ColorGradingTexture.prototype.delayLoad = function () {
  52752. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52753. return;
  52754. }
  52755. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52756. this._texture = this._getFromCache(this.url, true);
  52757. if (!this._texture) {
  52758. this.loadTexture();
  52759. }
  52760. };
  52761. /**
  52762. * Parses a color grading texture serialized by Babylon.
  52763. * @param parsedTexture The texture information being parsedTexture
  52764. * @param scene The scene to load the texture in
  52765. * @param rootUrl The root url of the data assets to load
  52766. * @return A color gradind texture
  52767. */
  52768. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52769. var texture = null;
  52770. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52771. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52772. texture.name = parsedTexture.name;
  52773. texture.level = parsedTexture.level;
  52774. }
  52775. return texture;
  52776. };
  52777. /**
  52778. * Serializes the LUT texture to json format.
  52779. */
  52780. ColorGradingTexture.prototype.serialize = function () {
  52781. if (!this.name) {
  52782. return null;
  52783. }
  52784. var serializationObject = {};
  52785. serializationObject.name = this.name;
  52786. serializationObject.level = this.level;
  52787. return serializationObject;
  52788. };
  52789. /**
  52790. * Empty line regex stored for GC.
  52791. */
  52792. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  52793. return ColorGradingTexture;
  52794. })(BABYLON.BaseTexture);
  52795. BABYLON.ColorGradingTexture = ColorGradingTexture;
  52796. })(BABYLON || (BABYLON = {}));
  52797. var BABYLON;
  52798. (function (BABYLON) {
  52799. var PBRMaterialDefines = (function (_super) {
  52800. __extends(PBRMaterialDefines, _super);
  52801. function PBRMaterialDefines() {
  52802. _super.call(this);
  52803. this.ALBEDO = false;
  52804. this.AMBIENT = false;
  52805. this.OPACITY = false;
  52806. this.OPACITYRGB = false;
  52807. this.REFLECTION = false;
  52808. this.EMISSIVE = false;
  52809. this.REFLECTIVITY = false;
  52810. this.BUMP = false;
  52811. this.PARALLAX = false;
  52812. this.PARALLAXOCCLUSION = false;
  52813. this.SPECULAROVERALPHA = false;
  52814. this.CLIPPLANE = false;
  52815. this.ALPHATEST = false;
  52816. this.ALPHAFROMALBEDO = false;
  52817. this.POINTSIZE = false;
  52818. this.FOG = false;
  52819. this.SPECULARTERM = false;
  52820. this.OPACITYFRESNEL = false;
  52821. this.EMISSIVEFRESNEL = false;
  52822. this.FRESNEL = false;
  52823. this.NORMAL = false;
  52824. this.UV1 = false;
  52825. this.UV2 = false;
  52826. this.VERTEXCOLOR = false;
  52827. this.VERTEXALPHA = false;
  52828. this.NUM_BONE_INFLUENCERS = 0;
  52829. this.BonesPerMesh = 0;
  52830. this.INSTANCES = false;
  52831. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  52832. this.MICROSURFACEAUTOMATIC = false;
  52833. this.EMISSIVEASILLUMINATION = false;
  52834. this.LINKEMISSIVEWITHALBEDO = false;
  52835. this.LIGHTMAP = false;
  52836. this.USELIGHTMAPASSHADOWMAP = false;
  52837. this.REFLECTIONMAP_3D = false;
  52838. this.REFLECTIONMAP_SPHERICAL = false;
  52839. this.REFLECTIONMAP_PLANAR = false;
  52840. this.REFLECTIONMAP_CUBIC = false;
  52841. this.REFLECTIONMAP_PROJECTION = false;
  52842. this.REFLECTIONMAP_SKYBOX = false;
  52843. this.REFLECTIONMAP_EXPLICIT = false;
  52844. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  52845. this.INVERTCUBICMAP = false;
  52846. this.LOGARITHMICDEPTH = false;
  52847. this.CAMERATONEMAP = false;
  52848. this.CAMERACONTRAST = false;
  52849. this.CAMERACOLORGRADING = false;
  52850. this.CAMERACOLORCURVES = false;
  52851. this.OVERLOADEDVALUES = false;
  52852. this.OVERLOADEDSHADOWVALUES = false;
  52853. this.USESPHERICALFROMREFLECTIONMAP = false;
  52854. this.REFRACTION = false;
  52855. this.REFRACTIONMAP_3D = false;
  52856. this.LINKREFRACTIONTOTRANSPARENCY = false;
  52857. this.REFRACTIONMAPINLINEARSPACE = false;
  52858. this.LODBASEDMICROSFURACE = false;
  52859. this.USEPHYSICALLIGHTFALLOFF = false;
  52860. this.RADIANCEOVERALPHA = false;
  52861. this.USEPMREMREFLECTION = false;
  52862. this.USEPMREMREFRACTION = false;
  52863. this.OPENGLNORMALMAP = false;
  52864. this.INVERTNORMALMAPX = false;
  52865. this.INVERTNORMALMAPY = false;
  52866. this.rebuild();
  52867. }
  52868. return PBRMaterialDefines;
  52869. })(BABYLON.MaterialDefines);
  52870. /**
  52871. * The Physically based material of BJS.
  52872. *
  52873. * This offers the main features of a standard PBR material.
  52874. * For more information, please refer to the documentation :
  52875. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  52876. */
  52877. var PBRMaterial = (function (_super) {
  52878. __extends(PBRMaterial, _super);
  52879. /**
  52880. * Instantiates a new PBRMaterial instance.
  52881. *
  52882. * @param name The material name
  52883. * @param scene The scene the material will be use in.
  52884. */
  52885. function PBRMaterial(name, scene) {
  52886. var _this = this;
  52887. _super.call(this, name, scene);
  52888. /**
  52889. * Intensity of the direct lights e.g. the four lights available in your scene.
  52890. * This impacts both the direct diffuse and specular highlights.
  52891. */
  52892. this.directIntensity = 1.0;
  52893. /**
  52894. * Intensity of the emissive part of the material.
  52895. * This helps controlling the emissive effect without modifying the emissive color.
  52896. */
  52897. this.emissiveIntensity = 1.0;
  52898. /**
  52899. * Intensity of the environment e.g. how much the environment will light the object
  52900. * either through harmonics for rough material or through the refelction for shiny ones.
  52901. */
  52902. this.environmentIntensity = 1.0;
  52903. /**
  52904. * This is a special control allowing the reduction of the specular highlights coming from the
  52905. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  52906. */
  52907. this.specularIntensity = 1.0;
  52908. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  52909. /**
  52910. * Debug Control allowing disabling the bump map on this material.
  52911. */
  52912. this.disableBumpMap = false;
  52913. /**
  52914. * Debug Control helping enforcing or dropping the darkness of shadows.
  52915. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  52916. */
  52917. this.overloadedShadowIntensity = 1.0;
  52918. /**
  52919. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  52920. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  52921. */
  52922. this.overloadedShadeIntensity = 1.0;
  52923. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  52924. /**
  52925. * The camera exposure used on this material.
  52926. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  52927. * This corresponds to a photographic exposure.
  52928. */
  52929. this.cameraExposure = 1.0;
  52930. /**
  52931. * The camera contrast used on this material.
  52932. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  52933. */
  52934. this.cameraContrast = 1.0;
  52935. /**
  52936. * Color Grading 2D Lookup Texture.
  52937. * This allows special effects like sepia, black and white to sixties rendering style.
  52938. */
  52939. this.cameraColorGradingTexture = null;
  52940. this._cameraColorGradingScaleOffset = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  52941. this._cameraColorGradingInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  52942. /**
  52943. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52944. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52945. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  52946. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52947. */
  52948. this.cameraColorCurves = null;
  52949. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  52950. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  52951. /**
  52952. * Debug Control allowing to overload the ambient color.
  52953. * This as to be use with the overloadedAmbientIntensity parameter.
  52954. */
  52955. this.overloadedAmbient = BABYLON.Color3.White();
  52956. /**
  52957. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  52958. */
  52959. this.overloadedAmbientIntensity = 0.0;
  52960. /**
  52961. * Debug Control allowing to overload the albedo color.
  52962. * This as to be use with the overloadedAlbedoIntensity parameter.
  52963. */
  52964. this.overloadedAlbedo = BABYLON.Color3.White();
  52965. /**
  52966. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  52967. */
  52968. this.overloadedAlbedoIntensity = 0.0;
  52969. /**
  52970. * Debug Control allowing to overload the reflectivity color.
  52971. * This as to be use with the overloadedReflectivityIntensity parameter.
  52972. */
  52973. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  52974. /**
  52975. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  52976. */
  52977. this.overloadedReflectivityIntensity = 0.0;
  52978. /**
  52979. * Debug Control allowing to overload the emissive color.
  52980. * This as to be use with the overloadedEmissiveIntensity parameter.
  52981. */
  52982. this.overloadedEmissive = BABYLON.Color3.White();
  52983. /**
  52984. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  52985. */
  52986. this.overloadedEmissiveIntensity = 0.0;
  52987. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  52988. /**
  52989. * Debug Control allowing to overload the reflection color.
  52990. * This as to be use with the overloadedReflectionIntensity parameter.
  52991. */
  52992. this.overloadedReflection = BABYLON.Color3.White();
  52993. /**
  52994. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  52995. */
  52996. this.overloadedReflectionIntensity = 0.0;
  52997. /**
  52998. * Debug Control allowing to overload the microsurface.
  52999. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53000. */
  53001. this.overloadedMicroSurface = 0.0;
  53002. /**
  53003. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53004. */
  53005. this.overloadedMicroSurfaceIntensity = 0.0;
  53006. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  53007. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53008. /**
  53009. * AKA Diffuse Color in other nomenclature.
  53010. */
  53011. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53012. /**
  53013. * AKA Specular Color in other nomenclature.
  53014. */
  53015. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53016. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53017. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53018. /**
  53019. * AKA Glossiness in other nomenclature.
  53020. */
  53021. this.microSurface = 0.9;
  53022. /**
  53023. * source material index of refraction (IOR)' / 'destination material IOR.
  53024. */
  53025. this.indexOfRefraction = 0.66;
  53026. /**
  53027. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53028. */
  53029. this.invertRefractionY = false;
  53030. /**
  53031. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53032. * Materials half opaque for instance using refraction could benefit from this control.
  53033. */
  53034. this.linkRefractionWithTransparency = false;
  53035. /**
  53036. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53037. */
  53038. this.linkEmissiveWithAlbedo = false;
  53039. this.useLightmapAsShadowmap = false;
  53040. /**
  53041. * In this mode, the emissive informtaion will always be added to the lighting once.
  53042. * A light for instance can be thought as emissive.
  53043. */
  53044. this.useEmissiveAsIllumination = false;
  53045. /**
  53046. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53047. */
  53048. this.useAlphaFromAlbedoTexture = false;
  53049. /**
  53050. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53051. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53052. */
  53053. this.useSpecularOverAlpha = true;
  53054. /**
  53055. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53056. */
  53057. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53058. /**
  53059. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53060. * The material will try to infer what glossiness each pixel should be.
  53061. */
  53062. this.useAutoMicroSurfaceFromReflectivityMap = false;
  53063. /**
  53064. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53065. * the creation of the material.
  53066. */
  53067. this.useScalarInLinearSpace = false;
  53068. /**
  53069. * BJS is using an harcoded light falloff based on a manually sets up range.
  53070. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53071. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53072. */
  53073. this.usePhysicalLightFalloff = true;
  53074. /**
  53075. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53076. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53077. */
  53078. this.useRadianceOverAlpha = true;
  53079. /**
  53080. * Allows using the bump map in parallax mode.
  53081. */
  53082. this.useParallax = false;
  53083. /**
  53084. * Allows using the bump map in parallax occlusion mode.
  53085. */
  53086. this.useParallaxOcclusion = false;
  53087. /**
  53088. * Controls the scale bias of the parallax mode.
  53089. */
  53090. this.parallaxScaleBias = 0.05;
  53091. /**
  53092. * If sets to true, disables all the lights affecting the material.
  53093. */
  53094. this.disableLighting = false;
  53095. /**
  53096. * Number of Simultaneous lights allowed on the material.
  53097. */
  53098. this.maxSimultaneousLights = 4;
  53099. /**
  53100. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53101. */
  53102. this.invertNormalMapX = false;
  53103. /**
  53104. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53105. */
  53106. this.invertNormalMapY = false;
  53107. this._renderTargets = new BABYLON.SmartArray(16);
  53108. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53109. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53110. this._tempColor = new BABYLON.Color3();
  53111. this._defines = new PBRMaterialDefines();
  53112. this._cachedDefines = new PBRMaterialDefines();
  53113. this._myScene = null;
  53114. this._myShadowGenerator = null;
  53115. this._cachedDefines.BonesPerMesh = -1;
  53116. this.getRenderTargetTextures = function () {
  53117. _this._renderTargets.reset();
  53118. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53119. _this._renderTargets.push(_this.reflectionTexture);
  53120. }
  53121. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53122. _this._renderTargets.push(_this.refractionTexture);
  53123. }
  53124. return _this._renderTargets;
  53125. };
  53126. }
  53127. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53128. get: function () {
  53129. return this._useLogarithmicDepth;
  53130. },
  53131. set: function (value) {
  53132. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53133. },
  53134. enumerable: true,
  53135. configurable: true
  53136. });
  53137. PBRMaterial.prototype.needAlphaBlending = function () {
  53138. if (this.linkRefractionWithTransparency) {
  53139. return false;
  53140. }
  53141. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53142. };
  53143. PBRMaterial.prototype.needAlphaTesting = function () {
  53144. if (this.linkRefractionWithTransparency) {
  53145. return false;
  53146. }
  53147. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53148. };
  53149. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53150. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53151. };
  53152. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53153. return this.albedoTexture;
  53154. };
  53155. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53156. if (!mesh) {
  53157. return true;
  53158. }
  53159. if (this._defines.INSTANCES !== useInstances) {
  53160. return false;
  53161. }
  53162. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53163. return true;
  53164. }
  53165. return false;
  53166. };
  53167. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53168. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53169. };
  53170. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53171. if (!useScalarInLinear) {
  53172. color.toLinearSpaceToRef(ref);
  53173. }
  53174. else {
  53175. ref.r = color.r;
  53176. ref.g = color.g;
  53177. ref.b = color.b;
  53178. }
  53179. };
  53180. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53181. var lightIndex = 0;
  53182. var depthValuesAlreadySet = false;
  53183. for (var index = 0; index < scene.lights.length; index++) {
  53184. var light = scene.lights[index];
  53185. if (!light.isEnabled()) {
  53186. continue;
  53187. }
  53188. if (!light.canAffectMesh(mesh)) {
  53189. continue;
  53190. }
  53191. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53192. // GAMMA CORRECTION.
  53193. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53194. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53195. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53196. if (defines["SPECULARTERM"]) {
  53197. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53198. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53199. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53200. }
  53201. // Shadows
  53202. if (scene.shadowsEnabled) {
  53203. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53204. }
  53205. lightIndex++;
  53206. if (lightIndex === maxSimultaneousLights)
  53207. break;
  53208. }
  53209. };
  53210. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53211. if (this.checkReadyOnlyOnce) {
  53212. if (this._wasPreviouslyReady) {
  53213. return true;
  53214. }
  53215. }
  53216. var scene = this.getScene();
  53217. if (!this.checkReadyOnEveryCall) {
  53218. if (this._renderId === scene.getRenderId()) {
  53219. if (this._checkCache(scene, mesh, useInstances)) {
  53220. return true;
  53221. }
  53222. }
  53223. }
  53224. var engine = scene.getEngine();
  53225. var needNormals = false;
  53226. var needUVs = false;
  53227. this._defines.reset();
  53228. if (scene.texturesEnabled) {
  53229. // Textures
  53230. if (scene.texturesEnabled) {
  53231. if (scene.getEngine().getCaps().textureLOD) {
  53232. this._defines.LODBASEDMICROSFURACE = true;
  53233. }
  53234. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53235. if (!this.albedoTexture.isReady()) {
  53236. return false;
  53237. }
  53238. else {
  53239. needUVs = true;
  53240. this._defines.ALBEDO = true;
  53241. }
  53242. }
  53243. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53244. if (!this.ambientTexture.isReady()) {
  53245. return false;
  53246. }
  53247. else {
  53248. needUVs = true;
  53249. this._defines.AMBIENT = true;
  53250. }
  53251. }
  53252. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53253. if (!this.opacityTexture.isReady()) {
  53254. return false;
  53255. }
  53256. else {
  53257. needUVs = true;
  53258. this._defines.OPACITY = true;
  53259. if (this.opacityTexture.getAlphaFromRGB) {
  53260. this._defines.OPACITYRGB = true;
  53261. }
  53262. }
  53263. }
  53264. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53265. if (!this.reflectionTexture.isReady()) {
  53266. return false;
  53267. }
  53268. else {
  53269. needNormals = true;
  53270. this._defines.REFLECTION = true;
  53271. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  53272. this._defines.INVERTCUBICMAP = true;
  53273. }
  53274. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  53275. switch (this.reflectionTexture.coordinatesMode) {
  53276. case BABYLON.Texture.CUBIC_MODE:
  53277. case BABYLON.Texture.INVCUBIC_MODE:
  53278. this._defines.REFLECTIONMAP_CUBIC = true;
  53279. break;
  53280. case BABYLON.Texture.EXPLICIT_MODE:
  53281. this._defines.REFLECTIONMAP_EXPLICIT = true;
  53282. break;
  53283. case BABYLON.Texture.PLANAR_MODE:
  53284. this._defines.REFLECTIONMAP_PLANAR = true;
  53285. break;
  53286. case BABYLON.Texture.PROJECTION_MODE:
  53287. this._defines.REFLECTIONMAP_PROJECTION = true;
  53288. break;
  53289. case BABYLON.Texture.SKYBOX_MODE:
  53290. this._defines.REFLECTIONMAP_SKYBOX = true;
  53291. break;
  53292. case BABYLON.Texture.SPHERICAL_MODE:
  53293. this._defines.REFLECTIONMAP_SPHERICAL = true;
  53294. break;
  53295. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  53296. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  53297. break;
  53298. }
  53299. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  53300. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  53301. needNormals = true;
  53302. if (this.reflectionTexture.isPMREM) {
  53303. this._defines.USEPMREMREFLECTION = true;
  53304. }
  53305. }
  53306. }
  53307. }
  53308. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53309. if (!this.lightmapTexture.isReady()) {
  53310. return false;
  53311. }
  53312. else {
  53313. needUVs = true;
  53314. this._defines.LIGHTMAP = true;
  53315. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  53316. }
  53317. }
  53318. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53319. if (!this.emissiveTexture.isReady()) {
  53320. return false;
  53321. }
  53322. else {
  53323. needUVs = true;
  53324. this._defines.EMISSIVE = true;
  53325. }
  53326. }
  53327. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53328. if (!this.reflectivityTexture.isReady()) {
  53329. return false;
  53330. }
  53331. else {
  53332. needUVs = true;
  53333. this._defines.REFLECTIVITY = true;
  53334. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  53335. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  53336. }
  53337. }
  53338. }
  53339. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53340. if (!this.bumpTexture.isReady()) {
  53341. return false;
  53342. }
  53343. else {
  53344. needUVs = true;
  53345. this._defines.BUMP = true;
  53346. if (this.useParallax) {
  53347. this._defines.PARALLAX = true;
  53348. if (this.useParallaxOcclusion) {
  53349. this._defines.PARALLAXOCCLUSION = true;
  53350. }
  53351. }
  53352. if (this.invertNormalMapX) {
  53353. this._defines.INVERTNORMALMAPX = true;
  53354. }
  53355. if (this.invertNormalMapY) {
  53356. this._defines.INVERTNORMALMAPY = true;
  53357. }
  53358. }
  53359. }
  53360. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53361. if (!this.refractionTexture.isReady()) {
  53362. return false;
  53363. }
  53364. else {
  53365. needUVs = true;
  53366. this._defines.REFRACTION = true;
  53367. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  53368. if (this.linkRefractionWithTransparency) {
  53369. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  53370. }
  53371. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  53372. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  53373. if (this.refractionTexture.isPMREM) {
  53374. this._defines.USEPMREMREFRACTION = true;
  53375. }
  53376. }
  53377. }
  53378. }
  53379. if (this.cameraColorGradingTexture) {
  53380. if (!this.cameraColorGradingTexture.isReady()) {
  53381. return false;
  53382. }
  53383. else {
  53384. this._defines.CAMERACOLORGRADING = true;
  53385. }
  53386. }
  53387. }
  53388. // Effect
  53389. if (scene.clipPlane) {
  53390. this._defines.CLIPPLANE = true;
  53391. }
  53392. if (engine.getAlphaTesting()) {
  53393. this._defines.ALPHATEST = true;
  53394. }
  53395. if (this._shouldUseAlphaFromAlbedoTexture()) {
  53396. this._defines.ALPHAFROMALBEDO = true;
  53397. }
  53398. if (this.useEmissiveAsIllumination) {
  53399. this._defines.EMISSIVEASILLUMINATION = true;
  53400. }
  53401. if (this.linkEmissiveWithAlbedo) {
  53402. this._defines.LINKEMISSIVEWITHALBEDO = true;
  53403. }
  53404. if (this.useLogarithmicDepth) {
  53405. this._defines.LOGARITHMICDEPTH = true;
  53406. }
  53407. if (this.cameraContrast != 1) {
  53408. this._defines.CAMERACONTRAST = true;
  53409. }
  53410. if (this.cameraExposure != 1) {
  53411. this._defines.CAMERATONEMAP = true;
  53412. }
  53413. if (this.cameraColorCurves) {
  53414. this._defines.CAMERACOLORCURVES = true;
  53415. }
  53416. if (this.overloadedShadeIntensity != 1 ||
  53417. this.overloadedShadowIntensity != 1) {
  53418. this._defines.OVERLOADEDSHADOWVALUES = true;
  53419. }
  53420. if (this.overloadedMicroSurfaceIntensity > 0 ||
  53421. this.overloadedEmissiveIntensity > 0 ||
  53422. this.overloadedReflectivityIntensity > 0 ||
  53423. this.overloadedAlbedoIntensity > 0 ||
  53424. this.overloadedAmbientIntensity > 0 ||
  53425. this.overloadedReflectionIntensity > 0) {
  53426. this._defines.OVERLOADEDVALUES = true;
  53427. }
  53428. // Point size
  53429. if (this.pointsCloud || scene.forcePointsCloud) {
  53430. this._defines.POINTSIZE = true;
  53431. }
  53432. // Fog
  53433. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53434. this._defines.FOG = true;
  53435. }
  53436. if (scene.lightsEnabled && !this.disableLighting) {
  53437. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  53438. }
  53439. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53440. // Fresnel
  53441. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53442. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53443. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53444. this._defines.OPACITYFRESNEL = true;
  53445. }
  53446. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53447. this._defines.EMISSIVEFRESNEL = true;
  53448. }
  53449. needNormals = true;
  53450. this._defines.FRESNEL = true;
  53451. }
  53452. }
  53453. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53454. this._defines.SPECULAROVERALPHA = true;
  53455. }
  53456. if (this.usePhysicalLightFalloff) {
  53457. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53458. }
  53459. if (this.useRadianceOverAlpha) {
  53460. this._defines.RADIANCEOVERALPHA = true;
  53461. }
  53462. // Attribs
  53463. if (mesh) {
  53464. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53465. this._defines.NORMAL = true;
  53466. }
  53467. if (needUVs) {
  53468. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53469. this._defines.UV1 = true;
  53470. }
  53471. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53472. this._defines.UV2 = true;
  53473. }
  53474. }
  53475. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53476. this._defines.VERTEXCOLOR = true;
  53477. if (mesh.hasVertexAlpha) {
  53478. this._defines.VERTEXALPHA = true;
  53479. }
  53480. }
  53481. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53482. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53483. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53484. }
  53485. // Instances
  53486. if (useInstances) {
  53487. this._defines.INSTANCES = true;
  53488. }
  53489. }
  53490. // Get correct effect
  53491. if (!this._defines.isEqual(this._cachedDefines)) {
  53492. this._defines.cloneTo(this._cachedDefines);
  53493. scene.resetCachedMaterial();
  53494. // Fallbacks
  53495. var fallbacks = new BABYLON.EffectFallbacks();
  53496. if (this._defines.REFLECTION) {
  53497. fallbacks.addFallback(0, "REFLECTION");
  53498. }
  53499. if (this._defines.REFRACTION) {
  53500. fallbacks.addFallback(0, "REFRACTION");
  53501. }
  53502. if (this._defines.REFLECTIVITY) {
  53503. fallbacks.addFallback(0, "REFLECTIVITY");
  53504. }
  53505. if (this._defines.BUMP) {
  53506. fallbacks.addFallback(0, "BUMP");
  53507. }
  53508. if (this._defines.PARALLAX) {
  53509. fallbacks.addFallback(1, "PARALLAX");
  53510. }
  53511. if (this._defines.PARALLAXOCCLUSION) {
  53512. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  53513. }
  53514. if (this._defines.SPECULAROVERALPHA) {
  53515. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  53516. }
  53517. if (this._defines.FOG) {
  53518. fallbacks.addFallback(1, "FOG");
  53519. }
  53520. if (this._defines.POINTSIZE) {
  53521. fallbacks.addFallback(0, "POINTSIZE");
  53522. }
  53523. if (this._defines.LOGARITHMICDEPTH) {
  53524. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  53525. }
  53526. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  53527. if (this._defines.SPECULARTERM) {
  53528. fallbacks.addFallback(0, "SPECULARTERM");
  53529. }
  53530. if (this._defines.OPACITYFRESNEL) {
  53531. fallbacks.addFallback(1, "OPACITYFRESNEL");
  53532. }
  53533. if (this._defines.EMISSIVEFRESNEL) {
  53534. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  53535. }
  53536. if (this._defines.FRESNEL) {
  53537. fallbacks.addFallback(3, "FRESNEL");
  53538. }
  53539. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  53540. fallbacks.addCPUSkinningFallback(0, mesh);
  53541. }
  53542. //Attributes
  53543. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53544. if (this._defines.NORMAL) {
  53545. attribs.push(BABYLON.VertexBuffer.NormalKind);
  53546. }
  53547. if (this._defines.UV1) {
  53548. attribs.push(BABYLON.VertexBuffer.UVKind);
  53549. }
  53550. if (this._defines.UV2) {
  53551. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53552. }
  53553. if (this._defines.VERTEXCOLOR) {
  53554. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53555. }
  53556. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  53557. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  53558. // Legacy browser patch
  53559. var shaderName = "pbr";
  53560. if (!scene.getEngine().getCaps().standardDerivatives) {
  53561. shaderName = "legacypbr";
  53562. }
  53563. var join = this._defines.toString();
  53564. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  53565. "vFogInfos", "vFogColor", "pointSize",
  53566. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  53567. "mBones",
  53568. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  53569. "depthValues",
  53570. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  53571. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  53572. "logarithmicDepthConstant",
  53573. "vSphericalX", "vSphericalY", "vSphericalZ",
  53574. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  53575. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  53576. "vMicrosurfaceTextureLods",
  53577. "vCameraInfos", "vCameraColorGradingInfos", "vCameraColorGradingScaleOffset"
  53578. ];
  53579. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  53580. "cameraColorGrading2DSampler"];
  53581. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  53582. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  53583. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  53584. }
  53585. if (!this._effect.isReady()) {
  53586. return false;
  53587. }
  53588. this._renderId = scene.getRenderId();
  53589. this._wasPreviouslyReady = true;
  53590. if (mesh) {
  53591. if (!mesh._materialDefines) {
  53592. mesh._materialDefines = new PBRMaterialDefines();
  53593. }
  53594. this._defines.cloneTo(mesh._materialDefines);
  53595. }
  53596. return true;
  53597. };
  53598. PBRMaterial.prototype.unbind = function () {
  53599. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  53600. this._effect.setTexture("reflection2DSampler", null);
  53601. }
  53602. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  53603. this._effect.setTexture("refraction2DSampler", null);
  53604. }
  53605. _super.prototype.unbind.call(this);
  53606. };
  53607. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53608. this._effect.setMatrix("world", world);
  53609. };
  53610. PBRMaterial.prototype.bind = function (world, mesh) {
  53611. this._myScene = this.getScene();
  53612. // Matrices
  53613. this.bindOnlyWorldMatrix(world);
  53614. // Bones
  53615. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53616. if (this._myScene.getCachedMaterial() !== this) {
  53617. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  53618. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53619. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53620. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  53621. }
  53622. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53623. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  53624. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  53625. }
  53626. }
  53627. // Textures
  53628. if (this._myScene.texturesEnabled) {
  53629. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53630. this._effect.setTexture("albedoSampler", this.albedoTexture);
  53631. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  53632. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  53633. }
  53634. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53635. this._effect.setTexture("ambientSampler", this.ambientTexture);
  53636. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  53637. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  53638. }
  53639. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53640. this._effect.setTexture("opacitySampler", this.opacityTexture);
  53641. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  53642. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  53643. }
  53644. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53645. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  53646. if (this.reflectionTexture.isCube) {
  53647. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  53648. }
  53649. else {
  53650. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  53651. }
  53652. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  53653. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  53654. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  53655. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  53656. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  53657. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  53658. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  53659. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  53660. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  53661. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  53662. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  53663. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  53664. }
  53665. }
  53666. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53667. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  53668. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  53669. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  53670. }
  53671. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53672. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  53673. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  53674. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  53675. }
  53676. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53677. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  53678. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  53679. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  53680. }
  53681. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53682. this._effect.setTexture("bumpSampler", this.bumpTexture);
  53683. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  53684. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  53685. }
  53686. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53687. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  53688. var depth = 1.0;
  53689. if (this.refractionTexture.isCube) {
  53690. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  53691. }
  53692. else {
  53693. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  53694. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  53695. if (this.refractionTexture.depth) {
  53696. depth = this.refractionTexture.depth;
  53697. }
  53698. }
  53699. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  53700. }
  53701. if ((this.reflectionTexture || this.refractionTexture)) {
  53702. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  53703. }
  53704. if (this.cameraColorGradingTexture) {
  53705. this._effect.setTexture("cameraColorGrading2DSampler", this.cameraColorGradingTexture);
  53706. this._cameraColorGradingInfos.x = this.cameraColorGradingTexture.level; // Texture Level
  53707. this._cameraColorGradingInfos.y = this.cameraColorGradingTexture.getSize().height; // Texture Size example with 8
  53708. this._cameraColorGradingInfos.z = this._cameraColorGradingInfos.y - 1.0; // SizeMinusOne 8 - 1
  53709. this._cameraColorGradingInfos.w = 1 / this._cameraColorGradingInfos.y; // Space of 1 slice 1 / 8
  53710. this._effect.setFloat4("vCameraColorGradingInfos", this._cameraColorGradingInfos.x, this._cameraColorGradingInfos.y, this._cameraColorGradingInfos.z, this._cameraColorGradingInfos.w);
  53711. var slicePixelSizeU = this._cameraColorGradingInfos.w / this._cameraColorGradingInfos.y; // Space of 1 pixel in U direction, e.g. 1/64
  53712. var slicePixelSizeV = 1.0 / this._cameraColorGradingInfos.y; // Space of 1 pixel in V direction, e.g. 1/8
  53713. 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
  53714. this._cameraColorGradingScaleOffset.y = this._cameraColorGradingInfos.z /
  53715. 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
  53716. this._cameraColorGradingScaleOffset.z = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  53717. this._cameraColorGradingScaleOffset.w = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  53718. this._effect.setFloat4("vCameraColorGradingScaleOffset", this._cameraColorGradingScaleOffset.x, this._cameraColorGradingScaleOffset.y, this._cameraColorGradingScaleOffset.z, this._cameraColorGradingScaleOffset.w);
  53719. }
  53720. }
  53721. // Clip plane
  53722. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  53723. // Point size
  53724. if (this.pointsCloud) {
  53725. this._effect.setFloat("pointSize", this.pointSize);
  53726. }
  53727. // Colors
  53728. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  53729. // GAMMA CORRECTION.
  53730. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  53731. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  53732. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  53733. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  53734. // GAMMA CORRECTION.
  53735. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  53736. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  53737. // GAMMA CORRECTION.
  53738. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  53739. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  53740. }
  53741. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  53742. // GAMMA CORRECTION.
  53743. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  53744. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  53745. // Lights
  53746. if (this._myScene.lightsEnabled && !this.disableLighting) {
  53747. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  53748. }
  53749. // View
  53750. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  53751. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  53752. }
  53753. // Fog
  53754. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  53755. this._lightingInfos.x = this.directIntensity;
  53756. this._lightingInfos.y = this.emissiveIntensity;
  53757. this._lightingInfos.z = this.environmentIntensity;
  53758. this._lightingInfos.w = this.specularIntensity;
  53759. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  53760. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  53761. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  53762. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  53763. this._cameraInfos.x = this.cameraExposure;
  53764. this._cameraInfos.y = this.cameraContrast;
  53765. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  53766. if (this.cameraColorCurves) {
  53767. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  53768. }
  53769. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  53770. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  53771. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  53772. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  53773. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  53774. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  53775. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  53776. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  53777. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  53778. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  53779. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  53780. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  53781. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  53782. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  53783. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  53784. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  53785. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  53786. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  53787. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  53788. // Log. depth
  53789. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  53790. }
  53791. _super.prototype.bind.call(this, world, mesh);
  53792. this._myScene = null;
  53793. };
  53794. PBRMaterial.prototype.getAnimatables = function () {
  53795. var results = [];
  53796. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  53797. results.push(this.albedoTexture);
  53798. }
  53799. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  53800. results.push(this.ambientTexture);
  53801. }
  53802. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  53803. results.push(this.opacityTexture);
  53804. }
  53805. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  53806. results.push(this.reflectionTexture);
  53807. }
  53808. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  53809. results.push(this.emissiveTexture);
  53810. }
  53811. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  53812. results.push(this.reflectivityTexture);
  53813. }
  53814. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  53815. results.push(this.bumpTexture);
  53816. }
  53817. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  53818. results.push(this.lightmapTexture);
  53819. }
  53820. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  53821. results.push(this.refractionTexture);
  53822. }
  53823. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  53824. results.push(this.cameraColorGradingTexture);
  53825. }
  53826. return results;
  53827. };
  53828. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53829. if (forceDisposeTextures) {
  53830. if (this.albedoTexture) {
  53831. this.albedoTexture.dispose();
  53832. }
  53833. if (this.ambientTexture) {
  53834. this.ambientTexture.dispose();
  53835. }
  53836. if (this.opacityTexture) {
  53837. this.opacityTexture.dispose();
  53838. }
  53839. if (this.reflectionTexture) {
  53840. this.reflectionTexture.dispose();
  53841. }
  53842. if (this.emissiveTexture) {
  53843. this.emissiveTexture.dispose();
  53844. }
  53845. if (this.reflectivityTexture) {
  53846. this.reflectivityTexture.dispose();
  53847. }
  53848. if (this.bumpTexture) {
  53849. this.bumpTexture.dispose();
  53850. }
  53851. if (this.lightmapTexture) {
  53852. this.lightmapTexture.dispose();
  53853. }
  53854. if (this.refractionTexture) {
  53855. this.refractionTexture.dispose();
  53856. }
  53857. if (this.cameraColorGradingTexture) {
  53858. this.cameraColorGradingTexture.dispose();
  53859. }
  53860. }
  53861. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53862. };
  53863. PBRMaterial.prototype.clone = function (name) {
  53864. var _this = this;
  53865. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  53866. };
  53867. PBRMaterial.prototype.serialize = function () {
  53868. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53869. serializationObject.customType = "BABYLON.PBRMaterial";
  53870. return serializationObject;
  53871. };
  53872. // Statics
  53873. PBRMaterial.Parse = function (source, scene, rootUrl) {
  53874. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  53875. };
  53876. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  53877. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  53878. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  53879. PBRMaterial._scaledReflection = new BABYLON.Color3();
  53880. __decorate([
  53881. BABYLON.serialize()
  53882. ], PBRMaterial.prototype, "directIntensity", void 0);
  53883. __decorate([
  53884. BABYLON.serialize()
  53885. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  53886. __decorate([
  53887. BABYLON.serialize()
  53888. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  53889. __decorate([
  53890. BABYLON.serialize()
  53891. ], PBRMaterial.prototype, "specularIntensity", void 0);
  53892. __decorate([
  53893. BABYLON.serialize()
  53894. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  53895. __decorate([
  53896. BABYLON.serialize()
  53897. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  53898. __decorate([
  53899. BABYLON.serialize()
  53900. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  53901. __decorate([
  53902. BABYLON.serialize()
  53903. ], PBRMaterial.prototype, "cameraExposure", void 0);
  53904. __decorate([
  53905. BABYLON.serialize()
  53906. ], PBRMaterial.prototype, "cameraContrast", void 0);
  53907. __decorate([
  53908. BABYLON.serializeAsTexture()
  53909. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  53910. __decorate([
  53911. BABYLON.serializeAsColorCurves()
  53912. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  53913. __decorate([
  53914. BABYLON.serializeAsColor3()
  53915. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  53916. __decorate([
  53917. BABYLON.serialize()
  53918. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  53919. __decorate([
  53920. BABYLON.serializeAsColor3()
  53921. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  53922. __decorate([
  53923. BABYLON.serialize()
  53924. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  53925. __decorate([
  53926. BABYLON.serializeAsColor3()
  53927. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  53928. __decorate([
  53929. BABYLON.serialize()
  53930. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  53931. __decorate([
  53932. BABYLON.serializeAsColor3()
  53933. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  53934. __decorate([
  53935. BABYLON.serialize()
  53936. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  53937. __decorate([
  53938. BABYLON.serializeAsColor3()
  53939. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  53940. __decorate([
  53941. BABYLON.serialize()
  53942. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  53943. __decorate([
  53944. BABYLON.serialize()
  53945. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  53946. __decorate([
  53947. BABYLON.serialize()
  53948. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  53949. __decorate([
  53950. BABYLON.serializeAsTexture()
  53951. ], PBRMaterial.prototype, "albedoTexture", void 0);
  53952. __decorate([
  53953. BABYLON.serializeAsTexture()
  53954. ], PBRMaterial.prototype, "ambientTexture", void 0);
  53955. __decorate([
  53956. BABYLON.serializeAsTexture()
  53957. ], PBRMaterial.prototype, "opacityTexture", void 0);
  53958. __decorate([
  53959. BABYLON.serializeAsTexture()
  53960. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  53961. __decorate([
  53962. BABYLON.serializeAsTexture()
  53963. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  53964. __decorate([
  53965. BABYLON.serializeAsTexture()
  53966. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  53967. __decorate([
  53968. BABYLON.serializeAsTexture()
  53969. ], PBRMaterial.prototype, "bumpTexture", void 0);
  53970. __decorate([
  53971. BABYLON.serializeAsTexture()
  53972. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  53973. __decorate([
  53974. BABYLON.serializeAsTexture()
  53975. ], PBRMaterial.prototype, "refractionTexture", void 0);
  53976. __decorate([
  53977. BABYLON.serializeAsColor3("ambient")
  53978. ], PBRMaterial.prototype, "ambientColor", void 0);
  53979. __decorate([
  53980. BABYLON.serializeAsColor3("albedo")
  53981. ], PBRMaterial.prototype, "albedoColor", void 0);
  53982. __decorate([
  53983. BABYLON.serializeAsColor3("reflectivity")
  53984. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  53985. __decorate([
  53986. BABYLON.serializeAsColor3("reflection")
  53987. ], PBRMaterial.prototype, "reflectionColor", void 0);
  53988. __decorate([
  53989. BABYLON.serializeAsColor3("emissive")
  53990. ], PBRMaterial.prototype, "emissiveColor", void 0);
  53991. __decorate([
  53992. BABYLON.serialize()
  53993. ], PBRMaterial.prototype, "microSurface", void 0);
  53994. __decorate([
  53995. BABYLON.serialize()
  53996. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  53997. __decorate([
  53998. BABYLON.serialize()
  53999. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54000. __decorate([
  54001. BABYLON.serializeAsFresnelParameters()
  54002. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54003. __decorate([
  54004. BABYLON.serializeAsFresnelParameters()
  54005. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54006. __decorate([
  54007. BABYLON.serialize()
  54008. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54009. __decorate([
  54010. BABYLON.serialize()
  54011. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54012. __decorate([
  54013. BABYLON.serialize()
  54014. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54015. __decorate([
  54016. BABYLON.serialize()
  54017. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54018. __decorate([
  54019. BABYLON.serialize()
  54020. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54021. __decorate([
  54022. BABYLON.serialize()
  54023. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54024. __decorate([
  54025. BABYLON.serialize()
  54026. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54027. __decorate([
  54028. BABYLON.serialize()
  54029. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54030. __decorate([
  54031. BABYLON.serialize()
  54032. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54033. __decorate([
  54034. BABYLON.serialize()
  54035. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54036. __decorate([
  54037. BABYLON.serialize()
  54038. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54039. __decorate([
  54040. BABYLON.serialize()
  54041. ], PBRMaterial.prototype, "useParallax", void 0);
  54042. __decorate([
  54043. BABYLON.serialize()
  54044. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54045. __decorate([
  54046. BABYLON.serialize()
  54047. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54048. __decorate([
  54049. BABYLON.serialize()
  54050. ], PBRMaterial.prototype, "disableLighting", void 0);
  54051. __decorate([
  54052. BABYLON.serialize()
  54053. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54054. __decorate([
  54055. BABYLON.serialize()
  54056. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54057. __decorate([
  54058. BABYLON.serialize()
  54059. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54060. __decorate([
  54061. BABYLON.serialize()
  54062. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54063. return PBRMaterial;
  54064. })(BABYLON.Material);
  54065. BABYLON.PBRMaterial = PBRMaterial;
  54066. })(BABYLON || (BABYLON = {}));
  54067. var BABYLON;
  54068. (function (BABYLON) {
  54069. var DebugLayer = (function () {
  54070. function DebugLayer(scene) {
  54071. var _this = this;
  54072. this._transformationMatrix = BABYLON.Matrix.Identity();
  54073. this._enabled = false;
  54074. this._labelsEnabled = false;
  54075. this._displayStatistics = true;
  54076. this._displayTree = false;
  54077. this._displayLogs = false;
  54078. this._skeletonViewers = new Array();
  54079. this._identityMatrix = BABYLON.Matrix.Identity();
  54080. this.axisRatio = 0.02;
  54081. this.accentColor = "orange";
  54082. this._scene = scene;
  54083. this._syncPositions = function () {
  54084. var engine = _this._scene.getEngine();
  54085. var canvasRect = engine.getRenderingCanvasClientRect();
  54086. if (_this._showUI) {
  54087. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  54088. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  54089. _this._statsDiv.style.width = "400px";
  54090. _this._statsDiv.style.height = "auto";
  54091. _this._statsSubsetDiv.style.maxHeight = "240px";
  54092. _this._optionsDiv.style.left = "0px";
  54093. _this._optionsDiv.style.top = "10px";
  54094. _this._optionsDiv.style.width = "200px";
  54095. _this._optionsDiv.style.height = "auto";
  54096. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  54097. _this._logDiv.style.left = "0px";
  54098. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  54099. _this._logDiv.style.width = "600px";
  54100. _this._logDiv.style.height = "160px";
  54101. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  54102. _this._treeDiv.style.top = "10px";
  54103. _this._treeDiv.style.width = "300px";
  54104. _this._treeDiv.style.height = "auto";
  54105. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  54106. }
  54107. _this._globalDiv.style.left = canvasRect.left + "px";
  54108. _this._globalDiv.style.top = canvasRect.top + "px";
  54109. _this._drawingCanvas.style.left = "0px";
  54110. _this._drawingCanvas.style.top = "0px";
  54111. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  54112. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  54113. var devicePixelRatio = window.devicePixelRatio || 1;
  54114. var context = _this._drawingContext;
  54115. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  54116. context.mozBackingStorePixelRatio ||
  54117. context.msBackingStorePixelRatio ||
  54118. context.oBackingStorePixelRatio ||
  54119. context.backingStorePixelRatio || 1;
  54120. _this._ratio = devicePixelRatio / backingStoreRatio;
  54121. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  54122. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  54123. };
  54124. this._onCanvasClick = function (evt) {
  54125. _this._clickPosition = {
  54126. x: evt.clientX * _this._ratio,
  54127. y: evt.clientY * _this._ratio
  54128. };
  54129. };
  54130. this._syncUI = function () {
  54131. if (_this._showUI) {
  54132. if (_this._displayStatistics) {
  54133. _this._displayStats();
  54134. _this._statsDiv.style.display = "";
  54135. }
  54136. else {
  54137. _this._statsDiv.style.display = "none";
  54138. }
  54139. if (_this._displayLogs) {
  54140. _this._logDiv.style.display = "";
  54141. }
  54142. else {
  54143. _this._logDiv.style.display = "none";
  54144. }
  54145. if (_this._displayTree) {
  54146. _this._treeDiv.style.display = "";
  54147. if (_this._needToRefreshMeshesTree) {
  54148. _this._needToRefreshMeshesTree = false;
  54149. _this._refreshMeshesTreeContent();
  54150. }
  54151. }
  54152. else {
  54153. _this._treeDiv.style.display = "none";
  54154. }
  54155. }
  54156. };
  54157. this._syncData = function () {
  54158. if (_this._labelsEnabled || !_this._showUI) {
  54159. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  54160. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  54161. var engine = _this._scene.getEngine();
  54162. var viewport = _this._camera.viewport;
  54163. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  54164. // Meshes
  54165. var meshes = _this._camera.getActiveMeshes();
  54166. var index;
  54167. var projectedPosition;
  54168. for (index = 0; index < meshes.length; index++) {
  54169. var mesh = meshes.data[index];
  54170. var position = mesh.getBoundingInfo().boundingSphere.center;
  54171. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  54172. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  54173. _this._renderAxis(projectedPosition, mesh, globalViewport);
  54174. }
  54175. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  54176. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  54177. }
  54178. }
  54179. // Cameras
  54180. var cameras = _this._scene.cameras;
  54181. for (index = 0; index < cameras.length; index++) {
  54182. var camera = cameras[index];
  54183. if (camera === _this._camera) {
  54184. continue;
  54185. }
  54186. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  54187. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  54188. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  54189. _this._camera.detachControl(engine.getRenderingCanvas());
  54190. _this._camera = camera;
  54191. _this._camera.attachControl(engine.getRenderingCanvas());
  54192. }, function () { return "purple"; });
  54193. }
  54194. }
  54195. // Lights
  54196. var lights = _this._scene.lights;
  54197. for (index = 0; index < lights.length; index++) {
  54198. var light = lights[index];
  54199. if (light.position) {
  54200. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  54201. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  54202. _this._renderLabel(light.name, projectedPosition, -20, function () {
  54203. light.setEnabled(!light.isEnabled());
  54204. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  54205. }
  54206. }
  54207. }
  54208. }
  54209. _this._clickPosition = undefined;
  54210. };
  54211. }
  54212. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  54213. while (this._treeSubsetDiv.hasChildNodes()) {
  54214. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  54215. }
  54216. // Add meshes
  54217. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  54218. sortedArray.sort(function (a, b) {
  54219. if (a.name === b.name) {
  54220. return 0;
  54221. }
  54222. return (a.name > b.name) ? 1 : -1;
  54223. });
  54224. for (var index = 0; index < sortedArray.length; index++) {
  54225. var mesh = sortedArray[index];
  54226. if (!mesh.isEnabled()) {
  54227. continue;
  54228. }
  54229. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  54230. m.isVisible = element.checked;
  54231. }, mesh);
  54232. }
  54233. };
  54234. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  54235. this._drawingContext.beginPath();
  54236. this._drawingContext.moveTo(zero.x, zero.y);
  54237. this._drawingContext.lineTo(unit.x, unit.y);
  54238. this._drawingContext.strokeStyle = color;
  54239. this._drawingContext.lineWidth = 4;
  54240. this._drawingContext.stroke();
  54241. this._drawingContext.font = "normal 14px Segoe UI";
  54242. this._drawingContext.fillStyle = color;
  54243. this._drawingContext.fillText(label, unitText.x, unitText.y);
  54244. };
  54245. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  54246. var position = mesh.getBoundingInfo().boundingSphere.center;
  54247. var worldMatrix = mesh.getWorldMatrix();
  54248. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  54249. var unit = (unprojectedVector.subtract(position)).length();
  54250. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  54251. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  54252. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  54253. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  54254. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  54255. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  54256. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  54257. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  54258. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  54259. };
  54260. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  54261. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  54262. this._drawingContext.font = "normal 12px Segoe UI";
  54263. var textMetrics = this._drawingContext.measureText(text);
  54264. var centerX = projectedPosition.x - textMetrics.width / 2;
  54265. var centerY = projectedPosition.y;
  54266. var clientRect = this._drawingCanvas.getBoundingClientRect();
  54267. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  54268. onClick();
  54269. }
  54270. this._drawingContext.beginPath();
  54271. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  54272. this._drawingContext.fillStyle = getFillStyle();
  54273. this._drawingContext.globalAlpha = 0.5;
  54274. this._drawingContext.fill();
  54275. this._drawingContext.globalAlpha = 1.0;
  54276. this._drawingContext.strokeStyle = '#FFFFFF';
  54277. this._drawingContext.lineWidth = 1;
  54278. this._drawingContext.stroke();
  54279. this._drawingContext.fillStyle = "#FFFFFF";
  54280. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  54281. this._drawingContext.beginPath();
  54282. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  54283. this._drawingContext.fill();
  54284. }
  54285. };
  54286. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  54287. if (!this._clickPosition) {
  54288. return false;
  54289. }
  54290. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  54291. return false;
  54292. }
  54293. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  54294. return false;
  54295. }
  54296. return true;
  54297. };
  54298. DebugLayer.prototype.isVisible = function () {
  54299. return this._enabled;
  54300. };
  54301. DebugLayer.prototype.hide = function () {
  54302. if (!this._enabled) {
  54303. return;
  54304. }
  54305. this._enabled = false;
  54306. var engine = this._scene.getEngine();
  54307. this._scene.unregisterBeforeRender(this._syncData);
  54308. this._scene.unregisterAfterRender(this._syncUI);
  54309. this._rootElement.removeChild(this._globalDiv);
  54310. this._scene.forceShowBoundingBoxes = false;
  54311. this._scene.forceWireframe = false;
  54312. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  54313. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  54314. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  54315. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  54316. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  54317. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  54318. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  54319. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  54320. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  54321. this._scene.shadowsEnabled = true;
  54322. this._scene.particlesEnabled = true;
  54323. this._scene.postProcessesEnabled = true;
  54324. this._scene.collisionsEnabled = true;
  54325. this._scene.lightsEnabled = true;
  54326. this._scene.texturesEnabled = true;
  54327. this._scene.lensFlaresEnabled = true;
  54328. this._scene.proceduralTexturesEnabled = true;
  54329. this._scene.renderTargetsEnabled = true;
  54330. this._scene.probesEnabled = true;
  54331. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  54332. this._clearSkeletonViewers();
  54333. };
  54334. DebugLayer.prototype._clearSkeletonViewers = function () {
  54335. for (var index = 0; index < this._skeletonViewers.length; index++) {
  54336. this._skeletonViewers[index].dispose();
  54337. }
  54338. this._skeletonViewers = [];
  54339. };
  54340. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  54341. if (showUI === void 0) { showUI = true; }
  54342. if (camera === void 0) { camera = null; }
  54343. if (rootElement === void 0) { rootElement = null; }
  54344. if (this._enabled) {
  54345. return;
  54346. }
  54347. this._enabled = true;
  54348. if (camera) {
  54349. this._camera = camera;
  54350. }
  54351. else {
  54352. this._camera = this._scene.activeCamera;
  54353. }
  54354. this._showUI = showUI;
  54355. var engine = this._scene.getEngine();
  54356. this._globalDiv = document.createElement("div");
  54357. this._rootElement = rootElement || document.body;
  54358. this._rootElement.appendChild(this._globalDiv);
  54359. this._generateDOMelements();
  54360. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  54361. this._syncPositions();
  54362. this._scene.registerBeforeRender(this._syncData);
  54363. this._scene.registerAfterRender(this._syncUI);
  54364. };
  54365. DebugLayer.prototype._clearLabels = function () {
  54366. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  54367. for (var index = 0; index < this._scene.meshes.length; index++) {
  54368. var mesh = this._scene.meshes[index];
  54369. mesh.renderOverlay = false;
  54370. }
  54371. };
  54372. DebugLayer.prototype._generateheader = function (root, text) {
  54373. var header = document.createElement("div");
  54374. header.innerHTML = text + "&nbsp;";
  54375. header.style.textAlign = "right";
  54376. header.style.width = "100%";
  54377. header.style.color = "white";
  54378. header.style.backgroundColor = "Black";
  54379. header.style.padding = "5px 5px 4px 0px";
  54380. header.style.marginLeft = "-5px";
  54381. header.style.fontWeight = "bold";
  54382. root.appendChild(header);
  54383. };
  54384. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  54385. var label = document.createElement("label");
  54386. label.style.display = "inline";
  54387. label.innerHTML = title;
  54388. label.style.color = color;
  54389. root.appendChild(label);
  54390. root.appendChild(document.createElement("br"));
  54391. };
  54392. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  54393. if (tag === void 0) { tag = null; }
  54394. var label = document.createElement("label");
  54395. label.style.display = "inline";
  54396. var boundingBoxesCheckbox = document.createElement("input");
  54397. boundingBoxesCheckbox.type = "checkbox";
  54398. boundingBoxesCheckbox.checked = initialState;
  54399. boundingBoxesCheckbox.style.display = "inline";
  54400. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  54401. boundingBoxesCheckbox.style.verticalAlign = "sub";
  54402. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  54403. task(evt.target, tag);
  54404. });
  54405. label.appendChild(boundingBoxesCheckbox);
  54406. var container = document.createElement("span");
  54407. var leftPart = document.createElement("span");
  54408. var rightPart = document.createElement("span");
  54409. rightPart.style.cssFloat = "right";
  54410. leftPart.innerHTML = leftTitle;
  54411. rightPart.innerHTML = rightTitle;
  54412. rightPart.style.fontSize = "12px";
  54413. rightPart.style.maxWidth = "200px";
  54414. container.appendChild(leftPart);
  54415. container.appendChild(rightPart);
  54416. label.appendChild(container);
  54417. root.appendChild(label);
  54418. root.appendChild(document.createElement("br"));
  54419. };
  54420. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  54421. if (tag === void 0) { tag = null; }
  54422. var label = document.createElement("label");
  54423. label.style.display = "inline";
  54424. var checkBox = document.createElement("input");
  54425. checkBox.type = "checkbox";
  54426. checkBox.checked = initialState;
  54427. checkBox.style.display = "inline";
  54428. checkBox.style.margin = "0px 5px 0px 0px";
  54429. checkBox.style.verticalAlign = "sub";
  54430. checkBox.addEventListener("change", function (evt) {
  54431. task(evt.target, tag);
  54432. });
  54433. label.appendChild(checkBox);
  54434. label.appendChild(document.createTextNode(title));
  54435. root.appendChild(label);
  54436. root.appendChild(document.createElement("br"));
  54437. };
  54438. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  54439. if (tag === void 0) { tag = null; }
  54440. var button = document.createElement("button");
  54441. button.innerHTML = title;
  54442. button.style.height = "24px";
  54443. button.style.width = "150px";
  54444. button.style.marginBottom = "5px";
  54445. button.style.color = "#444444";
  54446. button.style.border = "1px solid white";
  54447. button.className = "debugLayerButton";
  54448. button.addEventListener("click", function (evt) {
  54449. task(evt.target, tag);
  54450. });
  54451. root.appendChild(button);
  54452. root.appendChild(document.createElement("br"));
  54453. };
  54454. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  54455. if (tag === void 0) { tag = null; }
  54456. var label = document.createElement("label");
  54457. label.style.display = "inline";
  54458. var boundingBoxesRadio = document.createElement("input");
  54459. boundingBoxesRadio.type = "radio";
  54460. boundingBoxesRadio.name = name;
  54461. boundingBoxesRadio.checked = initialState;
  54462. boundingBoxesRadio.style.display = "inline";
  54463. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  54464. boundingBoxesRadio.style.verticalAlign = "sub";
  54465. boundingBoxesRadio.addEventListener("change", function (evt) {
  54466. task(evt.target, tag);
  54467. });
  54468. label.appendChild(boundingBoxesRadio);
  54469. label.appendChild(document.createTextNode(title));
  54470. root.appendChild(label);
  54471. root.appendChild(document.createElement("br"));
  54472. };
  54473. DebugLayer.prototype._generateDOMelements = function () {
  54474. var _this = this;
  54475. this._globalDiv.id = "DebugLayer";
  54476. this._globalDiv.style.position = "absolute";
  54477. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  54478. this._globalDiv.style.fontSize = "14px";
  54479. this._globalDiv.style.color = "white";
  54480. // Drawing canvas
  54481. this._drawingCanvas = document.createElement("canvas");
  54482. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  54483. this._drawingCanvas.style.position = "absolute";
  54484. this._drawingCanvas.style.pointerEvents = "none";
  54485. this._drawingCanvas.style.backgroundColor = "transparent";
  54486. this._drawingContext = this._drawingCanvas.getContext("2d");
  54487. this._globalDiv.appendChild(this._drawingCanvas);
  54488. if (this._showUI) {
  54489. var background = "rgba(128, 128, 128, 0.4)";
  54490. var border = "rgb(180, 180, 180) solid 1px";
  54491. // Stats
  54492. this._statsDiv = document.createElement("div");
  54493. this._statsDiv.id = "DebugLayerStats";
  54494. this._statsDiv.style.border = border;
  54495. this._statsDiv.style.position = "absolute";
  54496. this._statsDiv.style.background = background;
  54497. this._statsDiv.style.padding = "0px 0px 0px 5px";
  54498. this._generateheader(this._statsDiv, "STATISTICS");
  54499. this._statsSubsetDiv = document.createElement("div");
  54500. this._statsSubsetDiv.style.paddingTop = "5px";
  54501. this._statsSubsetDiv.style.paddingBottom = "5px";
  54502. this._statsSubsetDiv.style.overflowY = "auto";
  54503. this._statsDiv.appendChild(this._statsSubsetDiv);
  54504. // Tree
  54505. this._treeDiv = document.createElement("div");
  54506. this._treeDiv.id = "DebugLayerTree";
  54507. this._treeDiv.style.border = border;
  54508. this._treeDiv.style.position = "absolute";
  54509. this._treeDiv.style.background = background;
  54510. this._treeDiv.style.padding = "0px 0px 0px 5px";
  54511. this._treeDiv.style.display = "none";
  54512. this._generateheader(this._treeDiv, "MESHES TREE");
  54513. this._treeSubsetDiv = document.createElement("div");
  54514. this._treeSubsetDiv.style.paddingTop = "5px";
  54515. this._treeSubsetDiv.style.paddingRight = "5px";
  54516. this._treeSubsetDiv.style.overflowY = "auto";
  54517. this._treeSubsetDiv.style.maxHeight = "300px";
  54518. this._treeDiv.appendChild(this._treeSubsetDiv);
  54519. this._needToRefreshMeshesTree = true;
  54520. // Logs
  54521. this._logDiv = document.createElement("div");
  54522. this._logDiv.style.border = border;
  54523. this._logDiv.id = "DebugLayerLogs";
  54524. this._logDiv.style.position = "absolute";
  54525. this._logDiv.style.background = background;
  54526. this._logDiv.style.padding = "0px 0px 0px 5px";
  54527. this._logDiv.style.display = "none";
  54528. this._generateheader(this._logDiv, "LOGS");
  54529. this._logSubsetDiv = document.createElement("div");
  54530. this._logSubsetDiv.style.height = "127px";
  54531. this._logSubsetDiv.style.paddingTop = "5px";
  54532. this._logSubsetDiv.style.overflowY = "auto";
  54533. this._logSubsetDiv.style.fontSize = "12px";
  54534. this._logSubsetDiv.style.fontFamily = "consolas";
  54535. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  54536. this._logDiv.appendChild(this._logSubsetDiv);
  54537. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  54538. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  54539. };
  54540. // Options
  54541. this._optionsDiv = document.createElement("div");
  54542. this._optionsDiv.id = "DebugLayerOptions";
  54543. this._optionsDiv.style.border = border;
  54544. this._optionsDiv.style.position = "absolute";
  54545. this._optionsDiv.style.background = background;
  54546. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  54547. this._optionsDiv.style.overflowY = "auto";
  54548. this._generateheader(this._optionsDiv, "OPTIONS");
  54549. this._optionsSubsetDiv = document.createElement("div");
  54550. this._optionsSubsetDiv.style.paddingTop = "5px";
  54551. this._optionsSubsetDiv.style.paddingBottom = "5px";
  54552. this._optionsSubsetDiv.style.overflowY = "auto";
  54553. this._optionsSubsetDiv.style.maxHeight = "200px";
  54554. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  54555. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  54556. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  54557. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  54558. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  54559. _this._displayTree = element.checked;
  54560. _this._needToRefreshMeshesTree = true;
  54561. });
  54562. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54563. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  54564. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  54565. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  54566. _this._labelsEnabled = element.checked;
  54567. if (!_this._labelsEnabled) {
  54568. _this._clearLabels();
  54569. }
  54570. });
  54571. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  54572. if (element.checked) {
  54573. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  54574. }
  54575. else {
  54576. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  54577. }
  54578. });
  54579. ;
  54580. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54581. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  54582. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  54583. if (element.checked) {
  54584. _this._scene.forceWireframe = false;
  54585. _this._scene.forcePointsCloud = false;
  54586. }
  54587. });
  54588. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  54589. if (element.checked) {
  54590. _this._scene.forceWireframe = true;
  54591. _this._scene.forcePointsCloud = false;
  54592. }
  54593. });
  54594. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  54595. if (element.checked) {
  54596. _this._scene.forceWireframe = false;
  54597. _this._scene.forcePointsCloud = true;
  54598. }
  54599. });
  54600. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54601. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  54602. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  54603. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  54604. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  54605. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  54606. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  54607. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  54608. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  54609. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  54610. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  54611. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  54612. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54613. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  54614. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  54615. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  54616. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  54617. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  54618. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  54619. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  54620. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  54621. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  54622. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  54623. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  54624. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  54625. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  54626. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  54627. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  54628. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  54629. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54630. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  54631. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  54632. if (element.checked) {
  54633. _this._scene.headphone = true;
  54634. }
  54635. });
  54636. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  54637. if (element.checked) {
  54638. _this._scene.headphone = false;
  54639. }
  54640. });
  54641. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  54642. _this._scene.audioEnabled = !element.checked;
  54643. });
  54644. }
  54645. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54646. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  54647. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  54648. if (!element.checked) {
  54649. _this._clearSkeletonViewers();
  54650. return;
  54651. }
  54652. for (var index = 0; index < _this._scene.meshes.length; index++) {
  54653. var mesh = _this._scene.meshes[index];
  54654. if (mesh.skeleton) {
  54655. var found = false;
  54656. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  54657. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  54658. found = true;
  54659. break;
  54660. }
  54661. }
  54662. if (found) {
  54663. continue;
  54664. }
  54665. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  54666. viewer.isEnabled = true;
  54667. _this._skeletonViewers.push(viewer);
  54668. }
  54669. }
  54670. });
  54671. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54672. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  54673. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  54674. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  54675. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  54676. if (_this._camera) {
  54677. console.log(_this._camera);
  54678. }
  54679. else {
  54680. console.warn("No camera defined, or debug layer created before camera creation!");
  54681. }
  54682. });
  54683. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54684. this._globalDiv.appendChild(this._statsDiv);
  54685. this._globalDiv.appendChild(this._logDiv);
  54686. this._globalDiv.appendChild(this._optionsDiv);
  54687. this._globalDiv.appendChild(this._treeDiv);
  54688. }
  54689. };
  54690. DebugLayer.prototype._displayStats = function () {
  54691. var scene = this._scene;
  54692. var engine = scene.getEngine();
  54693. var glInfo = engine.getGlInfo();
  54694. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  54695. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  54696. + "<b>Count</b><br>"
  54697. + "Total meshes: " + scene.meshes.length + "<br>"
  54698. + "Total lights: " + scene.lights.length + "<br>"
  54699. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  54700. + "Total materials: " + scene.materials.length + "<br>"
  54701. + "Total textures: " + scene.textures.length + "<br>"
  54702. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  54703. + "Active indices: " + scene.getActiveIndices() + "<br>"
  54704. + "Active bones: " + scene.getActiveBones() + "<br>"
  54705. + "Active particles: " + scene.getActiveParticles() + "<br>"
  54706. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  54707. + "<b>Duration</b><br>"
  54708. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  54709. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  54710. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  54711. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  54712. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  54713. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  54714. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  54715. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  54716. + "</div>"
  54717. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  54718. + "<b>Extensions</b><br>"
  54719. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  54720. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  54721. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  54722. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  54723. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  54724. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  54725. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  54726. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  54727. + "</div><br>"
  54728. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  54729. + "<b>Caps.</b><br>"
  54730. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  54731. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  54732. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  54733. + "<b>Info</b><br>"
  54734. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  54735. + glInfo.version + "<br>"
  54736. + "</div><br>"
  54737. + glInfo.renderer + "<br>";
  54738. if (this.customStatsFunction) {
  54739. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  54740. }
  54741. };
  54742. return DebugLayer;
  54743. })();
  54744. BABYLON.DebugLayer = DebugLayer;
  54745. })(BABYLON || (BABYLON = {}));
  54746. 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}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\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#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\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 ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\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}","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}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec2 origin;\natt vec2 boundingMin;\natt vec2 boundingMax;\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#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvec4 pos;\npos.xy=position.xy-((origin.xy-vec2(0.5,0.5))*(boundingMax-boundingMin));\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,zBias.y);\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\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\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);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\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) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\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 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#endif\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*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}","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}"};
  54747. 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 INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\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","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \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(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","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","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"};
  54748. 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.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},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.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=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,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},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.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},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.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},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.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},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.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),s=0>o?-1:1,e=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*s,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*s;return e>0&&h>0&&2*o*s>e+h},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.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var s=r.subtract(i),e=Math.max(0,Math.min(1,n.Dot(t.subtract(i),s)/o)),h=i.add(s.multiplyByFloats(e,e));return n.Distance(t,h)},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.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},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.getClassName=function(){return\"Vector4\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},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.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},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.prototype.add=function(i){var n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,s=i.height+(n.height-i.height)*r;return new t(o,s)},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.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},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,C=s*x-a*p,Z=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,H=e*y-h*m,N=s*c-a*u,D=s*y-h*u,V=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*C+o*Z)*F,t.m[10]=(i*L-n*C+o*S)*F,t.m[14]=-(i*P-n*Z+r*S)*F,t.m[3]=-(n*I-r*q+o*H)*F,t.m[7]=(i*I-r*N+o*D)*F,t.m[11]=-(i*q-n*N+o*V)*F,t.m[15]=(i*H-n*D+r*V)*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],C=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*F+e*C,i[n+1]=r*d+o*_+s*A+e*Z,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*C,i[n+5]=h*d+a*_+u*A+m*Z,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*C,i[n+9]=y*d+c*_+p*A+f*Z,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*C,i[n+13]=l*d+x*_+z*A+w*Z,i[n+14]=l*g+x*M+z*L+w*S,\ni[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.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;16>i;i++)t=397*t^(this.m[i]||0);return t},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,z.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.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},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={}));";
  54749. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54750. module.exports = BABYLON;
  54751. };